【问题标题】:File uploading works on local server but not web server文件上传适用于本地服务器,但不适用于 Web 服务器
【发布时间】:2017-11-09 12:34:33
【问题描述】:

当在我的本地 XAMPP 服务器上上传文件但将其上传到我的网络服务器时,这个确切的代码可以正常工作,这将停止工作。同一个项目的其他功能仍然可以正常工作。

    //Image Uploading
if(isset($_FILES['file'])) {
    $file = $_FILES['file'];

    $file_name = $file['name'];
    $file_tmp = $file['tmp_name'];
    $file_size = $file['size'];
    $file_error = $file['error'];

    $file_ext = explode('.', $file_name);
    $file_ext = strtolower(end($file_ext));

    $allowed = array('png', 'jpg', 'jpeg');

    if(in_array($file_ext, $allowed)) {
        $file_name_new = $username.'.png';
        $file_dest = '../images/'.$file_name_new;
        if($file_error > 0){
            echo "There was an error uploading this image! Try another.";
        } else {
            if(move_uploaded_file($file_tmp, $file_dest)) {
                header("Location: ../user/editprofile.php?user=".$username);
            }
        }
    }
}

HTML 位

                <h2>Profile Image</h2>
            <form action="editprofile.php?user=<?php echo $user; ?>" method="post" enctype="multipart/form-data">
                <input type="file" name="file">
                <input type="submit" value="Upload">
            </form>

【问题讨论】:

    标签: php html image file uploading


    【解决方案1】:

    首先,我会pathinfo 来获取上传文件的文件名和文件扩展名。其次,您应该通过将$_FILES['userfile']['type'] 中的内容与mimetypes 列表进行比较来验证mimetype 而不是扩展名,在这种情况下,您需要检查['image/png', 'image/jpeg'] 以防止有人上传带有jpg 扩展名的PHP 脚本之类的东西。您可能还希望保留上传文件的扩展名,而不是将它们全部设为 png,因为这可能会导致意外错误。

    这样一来,信息将在$file_error 中,让您确切知道文件未上传的原因。你会收到一个file error code,它会告诉你出了什么问题。

    它将是以下之一:

    • UPLOAD_ERR_INI_SIZE 值:1;上传的文件超过了 php.ini 中的 upload_max_filesize 指令。
    • UPLOAD_ERR_FORM_SIZE 值:2;上传的文件超出了 HTML 表单中指定的 MAX_FILE_SIZE 指令。
    • UPLOAD_ERR_PARTIAL 值:3;上传的文件只上传了一部分。
    • UPLOAD_ERR_NO_FILE 值:4;未上传任何文件。
    • UPLOAD_ERR_NO_TMP_DIR 值:6;缺少一个临时文件夹。在 PHP 5.0.3 中引入。
    • UPLOAD_ERR_CANT_WRITE 值:7;无法将文件写入磁盘。在 PHP 5.1.0 中引入。
    • UPLOAD_ERR_EXTENSION 值:8; PHP 扩展停止了文件上传。 PHP 不提供确定是哪个扩展名导致文件上传停止的方法;使用 phpinfo() 检查加载的扩展列表可能会有所帮助。在 PHP 5.2.0 中引入。

    共享主机上最常见的情况是您上传到的文件的权限不正确(值 7)。

    【讨论】:

      【解决方案2】:

      我认为这是上传的目录权限问题。只需更改目录权限模式,如下所示:

      chmod 777 uploaded_folder_name
      

      【讨论】:

        猜你喜欢
        • 2012-09-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-04
        • 2013-07-08
        • 2021-05-24
        • 1970-01-01
        相关资源
        最近更新 更多