PHP文件上传导致Windows Apache服务器上的文件损坏


PHP file upload results in broken files on Windows Apache server

我为PHP编写了一个文件上传脚本。我正在Windows Apache服务器上进行测试,但它最终必须在带有Apache的CentOS服务器上工作。因为我还在调试,所以我还没有在运行的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说:不能同步…拒绝访问)。"照片查看器"窗口显示:无法打开此图片,因为您无法访问文件位置。在浏览器中查看该文件会导致权限被拒绝。链接到图片

谁熟悉这个问题和/或知道解决方案?希望你能帮我解决这个问题!

我也有过这样的经历。这是PHP 5.3.x中的一个bug。从5.3.3升级到5.6后,问题就消失了!

好吧,这是关于这个问题的最新消息…上面描述的问题是由我办公室的本地服务器引起的。在我家里的本地服务器上,移动后的图像还很好。所以这不是我的脚本,而是服务器。我猜PHP的处理方式不一样。

我办公室的PHP版本是5.4.9,家里的PHP版本是5.3.3。也许这些信息能帮上忙?