简体   繁体   中英

php move_uploaded_file()

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.

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 tmp folder on the server (for example: /tmp/php8rrKoW ). When I check the tmp folder the file is not there. (It's supposed to get deleted after the script finish executing.) I also don't see the /php8rrkoW folder. I'm not sure if it's supposed to be there. I set the permission for both the tmp folder and /var/www/upload/ to 777 using 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/upload and if there is a way to test this.

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>

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.

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

Let me know if that works

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'.

And finally: where is $filename defined?

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

Try adding '/home/your-username' to the beginning of '/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'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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