【问题标题】:Uploaded file in PHP can't be used in Bash script在 PHP 中上传的文件不能在 Bash 脚本中使用
【发布时间】:2015-06-22 11:08:30
【问题描述】:

您好,我使用这个简单的代码来上传“txt”文件(index.html + upload.php)。它工作正常,上传的 txt 文件保存在服务器上,我可以看到 txt 内容。只有当我想在脚本中使用文件作为输入来过滤文本中的某些单词时,才会出现问题。我使用的脚本是:http://pastebin.com/U9yJL0t0 我知道这个脚本很好。我通过终端手动创建的txt文件对其进行了测试,效果很好。问题仅在于使用 HTML 和 PHP 上传的文件。

index.html

<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input type="file" name="fileToUpload" id="fileToUpload">
    <input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>

上传.php

<?php
$target_dir = "/var/www/tmp/test/$mid.txt";
$target_file = $target_dir;
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image

// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "txt") {
    echo "Sorry, only txt  files are allowed.";
    $uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}
?>

【问题讨论】:

  • 您是否尝试更改 jf 上传文件 (chmod) 的权限?
  • @Andriy,是的,我也尝试过对文件和文件夹进行 chmod,但同样的问题再次出现。
  • @Nikolaus 你有什么错误吗?也许打开error_reportingphp.net/manual/en/function.error-reporting.php,看看会出现什么错误?
  • @divaka 我可以在“error.log”文件中看到错误,没有任何错误。上传似乎运行正常,没有错误,还有脚本。但文件中没有内容:(
  • 所以你得到了这个:Sorry, there was an error uploading your file. ?

标签: php html bash file-upload


【解决方案1】:

问题是,当 PHP 创建文件时,文件的所有者和组很可能是 www-data。您可以使用 sudo 运行脚本,或更改文件的所有者或权限。出于安全原因,我建议更改所有权。

这是更改所有权的命令:

chown username.username filename.txt

【讨论】:

  • 是的上传文件组是www-data,我试过运行脚本sudo,我也试过文件和目录的chmod。我还尝试使用“chown www-data:root 1.txt”更改文件的所有者,但出现了同样的问题:文本文件中没有内容
  • 我也更改了组:“chgrp group 1.txt”,但出现了同样的问题:在脚本中使用后文本文件中没有内容
  • 我看不到你将 $mid 设置为任何东西。如果这实际上是您的工作脚本,那么您会得到一个上传的文件,这很奇怪。如果您上传的 txt 文件包含内容和正确的权限,则问题必须出在您的 bash 脚本中。我能想到的唯一一件事是你测试你在 Linux 中编写的文本文件,它可以工作,并从不起作用的 windows 上传。如果是这种情况,则可能是换行符处理的问题。 Windows 使用回车和换行符,即 \r\n。不过这只是猜测。
猜你喜欢
  • 2023-03-17
  • 1970-01-01
  • 2015-07-05
  • 1970-01-01
  • 1970-01-01
  • 2014-03-22
  • 1970-01-01
  • 2017-01-03
  • 2018-10-20
相关资源
最近更新 更多