【发布时间】:2013-03-19 16:28:53
【问题描述】:
我为 PHP 编写了一个文件上传脚本。我正在 Windows Apache 服务器上进行测试,但它最终必须在带有 Apache 的 CentOS 服务器上工作。因为我还在调试,所以没有在live linux机器上测试过。谷歌了一下,没找到好的解决办法。
会发生什么?当我上传 .png 或 .jp(e)g 文件时,一切顺利。该脚本将我的文件移动到正确的目录,但随后输出一个不可读的文件。检查下面的图像。我上传的部分脚本:
if ($posting_photo === true) {
$uploaded_file = $_FILES['review_photo'];
$uploaded_file['ext'] = explode('.', $uploaded_file['name']);
//Only continue if a file was uploaded with a name and an extension
if ((!empty($uploaded_file['name'])) && (is_array($uploaded_file['ext']))) {
$uploaded_file['ext'] = secure(strtolower(end($uploaded_file['ext'])));
$upload_session = secure($_COOKIE[COOKIE_NAME_POST_REVIEW_SESSION]);
$upload_dir = realpath(getcwd() . DIR_REVIEW_IMAGES) . DIRECTORY_SEPARATOR . $upload_session . DIRECTORY_SEPARATOR;
$upload_ext = array('jpg', 'jpeg', 'png');
//Only continue if a file was uploaded in a right way
if (($uploaded_file['error'] == 0) && ($uploaded_file['size'] > 0) && ($uploaded_file['size'] <= MAX_FILESIZE_REVIEW_PHOTO_BYTES) && (in_array($uploaded_file['ext'], $upload_ext))) {
//Check if upload dir already exists. If so, there will be probably files in it. So we check for that too. If not, we can start with the first file.
if (is_dir($upload_dir)) {
//
//
//Part where a new file name gets generated. Not very interesting and it works well, so I left it out on Stack Overflow
//
//
} else {
mkdir($upload_dir, 0777, true);
$upload_name = $upload_session . '-1.' . $uploaded_file['ext'];
}
//Check if new upload name was generated. If not, something is wrong and we will not continue
if (!empty($upload_name)) {
chmod($upload_dir, 0777);
if (move_uploaded_file($uploaded_file['tmp_name'], $upload_dir . $upload_name)) {
$files = array_diff(@scandir($upload_dir), array('.', '..'));
//Change slashes on Windows machines for showing the image later
$upload_dir = str_replace('\\', '/', $upload_dir);
}
}
}
}
}
此处未初始化的所有变量均较早初始化。 cookie 是之前设置和检查的,用于唯一的目录和文件名。检查此图像以获取输出文件。左边的 x 来自 Dropbox(Dropbox 说:无法同步……访问被拒绝)。照片查看器窗口显示:无法打开此图片,因为您无权访问文件位置。在浏览器中查看文件会导致权限被拒绝。 Link to image
谁熟悉这个问题和/或知道解决方案?希望你能在这里帮助我!
【问题讨论】:
-
检查 move_uploaded_file() 函数是返回 true 还是 false,您当前的 if 似乎没有做任何感兴趣的事情。添加一个 else 并将成功或错误输出到错误日志/屏幕。
-
尝试在可能出现问题的地方记录或输出信息。现在它只是猜测会发生什么。
-
文件每次都移动,所以我假设 move_uploaded_file() 每次都返回 true。但我检查了一下,它确实返回了 true。我没有在最后一个 if 语句中添加 else,因为如果脚本结束而不对上传的文件做任何事情,php cleans 会从临时文件夹中删除文件。
-
@Bart 我打印了一些变量。 $upload_name 返回正确的值, $upload_dir 确实存在并且创建的文件确实存在。 move_uploaded_file() 返回 true。
-
我不知道权限在 Windows 上是如何工作的。但是在上传的文件上尝试
chmod(0777)。它应该使它对您可读。还可以查看php.net/manual/en/function.umask.php,它可以在脚本中创建文件时提供帮助。
标签: php apache file-upload broken-image