在OpenShift上使用PHP上传文件

时间:2015-12-04 13:30:08

标签: php file-upload openshift redhat

我正在尝试使用以下代码上传图片:

的index.php:

<form action="upload_photo.php" method="post" enctype="multipart/form-data">
    <p>
        Upload a new photo to the server:<br/><br/><br/>
        <input type="file" name="myphoto"/><br/><br/>
        <input type="submit" value="Upload photo"/>
    </p>
</form>

upload_photo.php:

// This function is included from another .php file
function checkUploadedPhoto() {
    $target_dir = "uploads/";
    $target_file = $target_dir . basename($_FILES["myphoto"]["name"]);

    if(isset($_FILES['myphoto']) AND $_FILES['myphoto']['error'] == 0) {
        // Check size
        if($_FILES['myphoto']['size'] <= 1000000) {
            // Get extension name
            $fileInfo = pathinfo($_FILES['myphoto']['name']);
            $upload_extension = $fileInfo['extension'];
            $allowed_extensions = array('jpg', 'jpeg', 'gif', 'png');

            // Check if the file already exists
            if (file_exists($target_file)) {
                echo "Sorry, file already exists.";
            }

            // Check if the file has a correct, expected extension
            if(in_array($upload_extension, $allowed_extensions)) {
                if(move_uploaded_file($_FILES['myphoto']['tmp_name'], $target_file)) {
                    return true;
                }
            }
            else
                echo "error3";
        }
        else
            echo "error2";
    }
    else
        echo "error1";

    echo "<pre>". print_r($_FILES) ."</pre>";
    echo "Error code: " .$_FILES['myphoto']['error'] ."<br/>";
    return false;
}

if(checkUploadedPhoto()) {
    header("Location: index.php");
}
else {
    echo "upload error";
}

浏览器结果:

Rendering

即使错误代码为0上传失败。这是一个许可问题吗?我似乎无法分辨出问题出在哪里。

我检查的其他参考资料虽然没有帮助:

link1 / link2 / link3 / W3Schools PHP upload

编辑:

这是我应用的结构:

Structure

UPDATE:

我添加此测试以检查uploads/目录是否可写,&amp;事实证明它无法访问

// This condition is true
if (!is_writeable('uploads/' . $_FILES['myphoto']['name'])) {
    die("Cannot write to destination file");
}

UPDATE2:

我将目标目录"uploads/"更改为"/uploads/"&amp;它适用于 localhost ,但不适用于托管服务器。

1 个答案:

答案 0 :(得分:1)

我找到了解决方案。我不得不改变:

$target_dir = "uploads/";

$target_dir = dirname(__FILE__) ."/uploads/";

dirname(__FILE__)指的是文件的完整路径文件名