简体   繁体   English

文件上传在PHP中不起作用

[英]File Upload not Working in PHP

I am new to PHP and am trying to create a page to upload a jpeg file. 我是PHP的新手,正在尝试创建一个页面来上传jpeg文件。 The webpage seems to run fine and it appears the file is uploading, however the file is not appearing on the server. 该网页似乎运行良好,似乎文件正在上传,但是文件未出现在服务器上。 Any help you can provide will be great. 您可以提供的任何帮助都会很棒。

The PHP code is: PHP代码为:

<?php
    $target_dir="/var/www/html/";
    $fileName=$_FILES['file']['name'];
    $target_file=$target_dir . basename($fileName);
    $imageFileType=pathinfo($target_file,PATHINFO_EXTENSION);
    $fileTempName=$_FILES["file"]["tmp_name"];
    $fileType=$_FILES["file"]["type"];
    $fileSize=$_FILES["file"]["size"];
    $fileError=$_FILES["file"]["error"];
    if(($fileType=="image/jpeg")&&($fileSize<100000)){
            if($fileError>0){
                    echo "Return Code: " . $fileError . "<br />";
            }
            else{
                    echo "Upload: " .$fileName . "<br />";
                    echo "Type: " . $fileType . "<br />";
                    echo "Size: " . ($fileSize / 1024) . " kb<br />";
                    echo "Temp file: " . $fileTempName . "<br />";
            if (file_exists($fileName)){
                    unlink($fileName);
            }
            move_uploaded_file($fileTempName,$target_file);
            echo "<br><br>File Temp Name: " .$fileTempName."\r\n <br>";
            echo "Uploaded file stored as : " .$target_file ."<br><br>";
            }       
    }
    else{
            echo "File is not a JPEG or too big.";
    }
?>

And the HTML code is as follows: HTML代码如下:

 <html>
       <body>
       <form action="save2web.php" method="post" enctype="multipart/form-data">
       <label for="file">Filename:</label>
       <input type="file" name="file" id="file"/>
       <br/>
       <input type="submit" name="submit" value="Upload"/>
       </form>
       </body>
       </html>

The problem is that, you don't check the returned value of move_uploaded_file() at all. 问题是,您根本不检查move_uploaded_file()的返回值。 But looks like, you're running your script on the host , and since most host disallow relative paths, you'd better provide an absolute. 但是看起来,您正在主机上运行脚本,并且由于大多数主机都不允许相对路径,因此最好提供绝对路径。

So try, replacing: 因此,尝试替换:

$target_dir = "/var/www/html/"; // <- This is relative, which might be blocked due to security reasons

with

$target_dir = dirname(__FILE__) . "/var/www/html/"; // dirname(__FILE__) is a path to root

And then, make sure that the file was uploaded: 然后,确保文件已上传:

if (!move_uploaded_file(...)) {
  // error
}

Change your target directory like this. 像这样更改目标目录。 Add a .(dot) before the directory name. 在目录名称前添加。(点)。

$target_directory = './var/www/html';

假设您的服务器从路径开始是linux,则可能需要更改尝试上传到的文件夹的权限,尝试将文件夹所有者更改为www-data,这对我来说解决了同样的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM