如何通过不需要的表单上传文件?

时间:2014-01-28 15:02:22

标签: php if-statement file-upload

我正在处理我的第一个PHP文件上传代码并提出一些问题。对不起,我是新手,但期待学习,可以使用一些帮助。

我需要知道如何通过表单将文件上传作为不需要步骤。

现在我的代码正在执行if/else,但如果用户没有上传文件,那么我仍然会收到错误消息。可能是因为if语句以false的形式返回。

我是否需要另一个else声明或者还有其他类似or声明的内容?

    // Where the file is going to be placed 
    $target_path = "uploads/";

    /* Add the original filename to our target path.  
    Result is "uploads/filename.extension" */
    $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 

    if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)){
    echo "The file ".  basename( $_FILES['uploadedfile']['name']). 
    " has been uploaded";
    }
    else{
    echo "There was an error uploading the file, please try again!";
    }

3 个答案:

答案 0 :(得分:0)

包裹所有内容

if (isset($_FILES['uploadedfile'])) {}

答案 1 :(得分:0)

代码应

if (isset($_FILES['uploadedfile'])) {
    // Where the file is going to be placed 
    $target_path = "uploads/";

    /* Add the original filename to our target path.  
    Result is "uploads/filename.extension" */
    $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 

    if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
        echo "The file ".  basename( $_FILES['uploadedfile']['name']). " has been uploaded";
    } else{
        echo "There was an error uploading the file, please try again!";
    }
}else{
    echo "No File uploaded";
}

答案 2 :(得分:0)

您需要将所有代码包装在if语句中,以查看该文件是否已上载。否则,您将收到警告和通知,说明变量未定义。像这样的东西

if(!empty($_FILES['uploadedfile'])) {
    // Where the file is going to be placed 
    $target_path = "uploads/";

    /* Add the original filename to our target path.  
    Result is "uploads/filename.extension" */
    $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); 

    if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
        echo "The file ".  basename( $_FILES['uploadedfile']['name']). 
        " has been uploaded";
    } else{
        echo "There was an error uploading the file, please try again!";
    }
} else {
    //nothing needed in here or echo some message
}
//Your other required stuff should be here

警告:我没有测试过这个