php move_uploaded_file()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10291655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 21:50:52  来源:igfitidea点击:

php move_uploaded_file()

phpfile-uploadupload

提问by user1352777

So I'm testing out the move_uploaded_file() php script from the w3schools website http://www.w3schools.com/php/php_file_upload.asp. Here is my code.

所以我正在测试 w3schools 网站http://www.w3schools.com/php/php_file_upload.asp 上的 move_uploaded_file() php 脚本。这是我的代码。

if ($_FILES["file"]["size"] < 2000000)
{
    if ($_FILES["file"]["error"] > 0)
        echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
    else
    {
        echo "Upload: " . $_FILES["file"]["name"] . "<br />";
        echo "Type: " . $_FILES["file"]["type"] . "<br />";
        echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
        echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

        if (file_exists("/var/www/upload/" . $_FILES["file"]["name"]))
        {
          echo $_FILES["file"]["name"] . " already exists. ";
        }
        elseif(move_uploaded_file($_FILES["file"]["tmp_name"], "/var/www/upload/".$fileName))
            echo "Stored in: " . "/var/www/upload/".$fileName;
    }
}
else
    echo "Invalid file";

The problem is if(move_uploaded_file($_FILES["file"]["tmp_name"],"/var/www/upload/".$fileName))returns false all the time but it seems the file is stored in the tmpfolder on the server (for example: /tmp/php8rrKoW). When I check the tmpfolder the file is not there. (It's supposed to get deleted after the script finish executing.) I also don't see the /php8rrkoWfolder. I'm not sure if it's supposed to be there. I set the permission for both the tmpfolder and /var/www/upload/to 777using chmod, but I'm not sure if I should set the owner to apache. So I want to know why the file isn't copied over to /var/www/uploadand if there is a way to test this.

问题是一直if(move_uploaded_file($_FILES["file"]["tmp_name"],"/var/www/upload/".$fileName))返回 false 但似乎文件存储在tmp服务器上的文件夹中(例如:)/tmp/php8rrKoW。当我检查tmp文件夹时,文件不存在。(它应该在脚本执行完成后被删除。)我也没有看到该/php8rrkoW文件夹。我不确定它是否应该在那里。我设置的许可,允许该tmp文件夹,/var/www/upload/777使用chmod,但我不知道我是否应该拥有者设置为apache。所以我想知道为什么文件没有被复制到,/var/www/upload以及是否有办法测试这个。

回答by Lawrence Cherone

Here is a basic image upload class I made for another question the other day, simple to use, perhaps your find it interesting.

这是我前几天为另一个问题制作的一个基本的图片上传类,使用简单,也许你觉得有趣。

<?php 
error_reporting(E_ALL); //Will help you debug a [server/path/permission] issue
Class uploadHandler{
    public $upload_path;
    public $full_path;
    public $name;
    public $size;
    public $ext;
    public $output;
    public $input;
    public $prefix;
    private $allowed;

    function upload(){
        if($_SERVER['REQUEST_METHOD'] == 'POST'){
            if(isset($_FILES[$this->input]['error'])){
                if($_FILES[$this->input]['error'] == 0){
                    $this->name      = basename($_FILES[$this->input]['name']);
                    $file_p          = explode('.', $this->name);
                    $this->ext       = end($file_p);
                    $this->full_path = rtrim($this->upload_path,'/').'/'.preg_replace('/[^a-zA-Z0-9.-]/s', '_', $this->prefix.'_'.$file_p[0]).'.'.$this->ext;
                    $info            = getimagesize($_FILES[$this->input]['tmp_name']);
                    $this->size      = filesize($_FILES[$this->input]['tmp_name']);

                    if($info[0]>$this->allowed['dimensions']['width'] || $info[1] > $this->allowed['dimensions']['height']){
                        $this->output = 'File dimensions too large!';
                    }else{
                        if($info[0] > 0 && $info[1] > 0 && in_array($info['mime'],$this->allowed['types'])){
                            move_uploaded_file($_FILES[$this->input]['tmp_name'],$this->full_path);
                            $this->output = 'Upload success!';
                        }else{
                            $this->output = 'File not supported!';
                        }
                    }
                }else{
                    if($_FILES[$this->input]['error']==1){$this->output = 'The uploaded file exceeds the upload_max_filesize directive!';}
                    if($_FILES[$this->input]['error']==2){$this->output = 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in our HTML form!';}
                    if($_FILES[$this->input]['error']==3){$this->output = 'The uploaded file was only partially uploaded!';}
                    if($_FILES[$this->input]['error']==4){$this->output = 'No file was uploaded!';}
                    if($_FILES[$this->input]['error']==6){$this->output = 'Missing a temporary folder!';}
                    if($_FILES[$this->input]['error']==7){$this->output = 'Failed to write uploaded file to disk!';}
                    if($_FILES[$this->input]['error']==8){$this->output = 'A PHP extension stopped the file upload!';}
                }
            }
        }
    }

    function setPath($var){
        $this->upload_path = $var;
    }
    function setAllowed($var=array()){
        $this->allowed = $var;
    }
    function setFilePrefix($var){
        $this->prefix = preg_replace('/[^a-zA-Z0-9.-]/s', '_', $var);
    }
    function setInput($var){
        $this->input = $var;
    }

}



//Start class
$upload = new uploadHandler();
//Set path
$upload->setPath('./');
//Prefix the file name
$upload->setFilePrefix('user_uploads');
//Allowed types
$upload->setAllowed(array('dimensions'=>array('width'=>200,'height'=>200),
                          'types'=>array('image/png','image/jpg','image/gif')));
//form property name                   
$upload->setInput('myfile');
//Do upload
$upload->upload();


//notice
if(isset($upload->output)){
    echo $upload->output;
}
?>

<form action="" method="POST" enctype="multipart/form-data">
     <!--1 MB = 1048576 bytes-->
     <input type="hidden" name="MAX_FILE_SIZE" value="1048000" />

     <p>Upload your image:<input type="file" name="myfile"><input type="submit" value="Upload"></p>

</form>

回答by Jon Kloske

The destination directory you want to move the files into should be writable by the webserver user. Also don't forget that some webservers operate inside a changeroot, so parts of the destination path may not be needed. The PHP help doc also says you should check the HTLM form to ensure it's enctype='multipart/form-data'.

您要将文件移动到的目标目录应该是网络服务器用户可写的。也不要忘记一些网络服务器在 changeroot 内运行,因此可能不需要目标路径的一部分。PHP 帮助文档还说您应该检查 HTLM 表单以确保它是 enctype='multipart/form-data'。

And finally: where is $filename defined?

最后: $filename 在哪里定义?

回答by Bruce Tong

Your path must consist of '/home/usr-name'

您的路径必须包含“/home/usr-name”

Try adding '/home/your-username' to the beginning of '/var/www/upload' .

尝试将 '/home/your-username' 添加到 '/var/www/upload' 的开头。

To get an idea, add a info.php into your root directory, open it up in a browser and look under 'Loaded Configuration File'.

要获得一个想法,请将 info.php 添加到您的根目录中,在浏览器中打开它并在“加载的配置文件”下查看。

回答by mlishn

It seems that you should be using ./upload/ instead of /var/www/upload/ since you are already in the main directory of the accessible website.

似乎您应该使用 ./upload/ 而不是 /var/www/upload/ 因为您已经在可访问网站的主目录中。

You can also refer to http://www.tizag.com/phpT/fileupload.phpor the API : http://php.net/manual/en/function.move-uploaded-file.php

您也可以参考http://www.tizag.com/phpT/fileupload.php或 API:http: //php.net/manual/en/function.move-uploaded-file.php

Let me know if that works

让我知道这是否有效