PHP和html上传器

时间:2015-05-21 15:19:53

标签: php html

我的代码有问题,但不是关于和错误。

1)当我点击刷新时,我仍然看到以前回显的变量。

2)当我选择一个文件时,它应该从temp_name转移到'uploads /'但它不会+它不会抛出'上传'消息。

3)当我没有选择文件并提交时,应该说'请选择一个文件。

你能解释我如何来解决我的问题,为什么这些事情会发生?

   <?php

    if (isset($_POST['submit'])){
    $size=$_FILES['file']['size'].'kb'."<br>";
    $name=$_FILES['file']['name']."<br>";
    $type=$_FILES['file']['type']."<br>";
    $tmp_name=$_FILES['file']['tmp_name']."<br>";
    if (isset($name))
    {
        if(!empty($name))
        {
            $location='uploads/';
        if  (move_uploaded_file($tmp_name,$location.$name))
            {
                echo 'UPLOADED';
            } 
          echo 'OK.';
        }else 
            {
            echo 'please choose a file.';
            }
    }


    }

    ?>

    <form action="upload.php" method="POST" enctype="multipart/form-data">
     <br>
    <input type ="file" name="file">
     <br> <br>
    <input type="submit" name="submit" value ="Submit">

    </form> 

    <?php


    echo 'File size: '.$size;
    echo 'File name: '.$name;
    echo 'File type: '.$type;
    //echo 'File temporary place: '.$tmp_name;
    ?>

PS:这是点击刷新按钮后的页面截图

enter image description here

1 个答案:

答案 0 :(得分:2)

在这里,您可以使用文件错误值。对于不同的问题,值为0到8:http://php.net/manual/en/features.file-upload.errors.php

if (isset($_POST['submit'])){
    if ($_FILES["file"]["error"]==0){ //success so far

        $size=$_FILES['file']['size'];
        $name=$_FILES['file']['name'];
        $type=$_FILES['file']['type'];
        $tmp_name=$_FILES['file']['tmp_name'];     
        $location='uploads/';
        try{
             $result =  move_uploaded_file($tmp_name,$location.$name); // this will throw warnings though!
             if($result){
                 echo 'UPLOADED AND MOVED';
             }else{
                    echo "Unable to move the file";
             }
        }catch(Exception $e){
            echo "Sorry there was a problem ".$e.getMessage();
        }
    }else{ //some sort of problem
        echo "There was a problem with the upload (error code: ".$_FILES["file"]["error"].")";
        if($_FILES["file"]["error"]==4 ){ // UPLOAD_ERR_NO_FILE
            echo "<br/> Please choose a file to upload";
        }
    }
}

确保您的uploads文件夹存在且权限设置正确。显示正确的错误可能有所帮助。