php 上传脚本不起作用

标签 php file upload

我想在我的主页上上传图片。 我正在使用 w3schools 的脚本来执行此操作:

这是upload.html

<!DOCTYPE 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>

这是 upload.php

<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
    $check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
    if($check !== false) {
        echo "File is an image - " . $check["mime"] . ".";
        $uploadOk = 1;
    } else {
        echo "File is not an image.";
        $uploadOk = 0;
    }
}
// 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 != "jpg" && $imageFileType != "png" && $imageFileType !="jpeg" && $imageFileType != "gif" ) {
    echo "Sorry, only JPG, JPEG, PNG & GIF 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.";
    }
}
?>

我已经创建了一个文件夹/var/www/uploads/ 当尝试上传 3KB jpeg 时,我得到以下输出:

File is an image - image/jpeg.
Sorry, there was an error uploading your file.
Array ( [fileToUpload] => Array ( [name] => Test Bild Website Upload.jpg [type] => image/jpeg [tmp_name] => /tmp/phpyxW0TX [error] => 0 [size] => 2999 ) )

我是 php 初学者,真的不知道问题是什么。 也许有人可以帮助我解决这个问题。 :)

最佳答案

  1. 检查是否可以通过在命令行执行以下命令来上传文件:

    chmod -R 777/var/www/uploads/

  2. 然后尝试上传一些内容。如果有效,您就知道这是权限问题。但您不想将上传文件夹保留为 777 权限(允许所有人访问)

  3. 如果是权限问题,我喜欢这样做:

    chown [您的用户名]:www-data -R/var/www/uploads/

    chmod -R 775/var/www/uploads/

这会将文件夹的组分配更改为 www-data,这通常是 apache 在 Ubuntu Linux 服务器上运行的方式。

关于php 上传脚本不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31837561/

相关文章:

java - 使用单独的 Java 进程在映射驱动器上写入和读取文件

c++ - linux 防止文件描述符在程序退出时关闭

android - 在Google Play商店中上传失败

javascript - 上传时防止空闲状态(iOS 上的网络应用程序)

php - 带有特殊字符的 TCPDF HTML 显示空 PDF 文件

php - Laravel 5.6 分贝 :seed throws FatalThrowableError : Class 'APP\Todo' not found

php - 如何使用 PHP CONCAT 来自 MySQL 的垂直线

c - 当文件达到一定大小时,如何暂停文件写入,然后创建一个新文件

php - 有没有人为 codeigniter 和 uploadify session 问题提供新的解决方案

php - 无法更改数据库中的数据