用PHP上传和下载文件

时间:2018-08-15 13:26:06

标签: php

下面的代码是否有问题?因为我可以无误地单击按钮,但是文件不会保存到"public_html/resume/"

$uploadOk = true;

if(isset($_FILES)) {

    $folder_dir = "public_html/resume/";

    $base = basename($_FILES['resume']['name']); 

    $resumeFileType = pathinfo($base, PATHINFO_EXTENSION); 

    $file = uniqid() . "." . $resumeFileType;   

    $filename = $folder_dir .$file;  

    if(file_exists($_FILES['resume']['tmp_name'])) { 

        if($resumeFileType == "pdf")  {

            if($_FILES['resume']['size'] < 500000) { // File size is less than 5MB

                move_uploaded_file($_FILES["resume"]["tmp_name"], $filename);

            } else {
                $_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
                header("Location: edit-profile.php");
                exit();
            }
        } else {
            $_SESSION['uploadError'] = "Wrong Format. Only PDF Allowed";
            header("Location: edit-profile.php");
            exit();

1 个答案:

答案 0 :(得分:1)

不幸的是,您的PHP代码的每一行都需要改进。

出现错误的原因是/public_hml/不是绝对文件路径,因此PHP将其解释为相对。并寻找{肯定是无效的<current directory>/public_html/resume/

下面,我已经为您修复了几乎所有内容。

$uploadOk = false; // Always assume false until proven ok.  

if(!empty($_FILES['resume'])) {
   // Check errors    
   if($_FILES['resume']['error'] === 0){

        $folder_dir = $_SERVER['DOCUMENT_ROOT']."/resume/"; // use absolute path.

    // $base = basename($_FILES['resume']['name']); //worthless.
    // $resumeFileType = pathinfo($base, PATHINFO_EXTENSION); 

        $finfo = new finfo();
        $fileMimeType = $finfo->file($_FILES['resume']['tmp_name'], FILEINFO_MIME_TYPE);
        if(strtolower($fileMimeType) !== 'applicaton/pdf'){
               $_SESSION['uploadError'] = "Wrong Format. Only PDF Allowed";
                header("Location: edit-profile.php");
                exit();
        }
        $file = uniqid("",true) . ".PDF";    // make sure unique is unique. 

        $filename = $folder_dir .$file;  

    //if(file_exists($_FILES['resume']['tmp_name'])) {  

    //   if($resumeFileType == "pdf")  {//worthless.

       if($_FILES['resume']['size'] > 500000) { // File size is less than 5MB
            $_SESSION['uploadError'] = "Wrong Size. Max Size Allowed : 5MB";
            header("Location: edit-profile.php");
            exit();
       } 

       move_uploaded_file($_FILES["resume"]["tmp_name"], $filename);
   }
   else {
     //There were file upload errors. Handle here.
    }
}

来源