PHP无法从HTML表单上传文件

问题描述:

This is how I handle my form:

        # Create the message
        # ----------------------------------------------------------------
        $name = $_POST['name'];
        $email = $_POST['email'];
        $title = $_POST['title'];
        $course = $_POST['course'];
        $file = $_POST['file'];

        $message  = "Name: ".$name."
";
        $message .= "Email: ".$email."

";
        $message .= "Title of Article: ".$title."
";
        $message .= "Program: ".$course."

";
        $message .= "Additional Info: ".$info;

        # Upload temporary files
        # ----------------------------------------------------------------
        $uploaddir = '/home/public/uploads/';
        $uploadfile = $uploaddir . basename($_FILES['file']['name']);
        if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile) == false) {
            echo 'Could not move file';
            exit;
        }

        if ($_FILES['file']['type'] != "application/pdf") {
            echo 'Not a pdf file';
            unlink($uploadfile);
            exit;
        }

The end product is hopefully sending an email with the file as an attachment. Right now I'm failing and getting the "Could not move file" message I built in. Is there an obvious reason why? $file is what I get from a file dialog in HTML (input type="file")

这就是我处理表单的方式: p>

  #Create 消息
#---------------------------------------------  ------------------- 
 $ name = $ _POST ['name']; 
 $ email = $ _POST ['email']; 
 $ title =  $ _POST ['title']; 
 $ course = $ _POST ['course']; 
 $ file = $ _POST ['file']; 
 
 $ message =“Name:”。$ name。“  
“; 
 $ message。=”电子邮件:“。$ email。”
 
“; 
 $ message。=”文章标题:“。$ title。”
“; 
 $ message  。=“程序:”。$ course。“
 
”; 
 $ message。=“其他信息:”。$ info; 
 
#上传临时文件
#-------  --------------------------------------------------  ------- 
 $ uploaddir ='/ home / public / uploads /'; 
 $ uploadfile = $ uploaddir。  basename($ _ FILES ['file'] ['name']); 
 if(move_uploaded_file($ _ FILES ['file'] ['tmp_name'],$ uploadfile)== false){
 echo'无法移动 文件'; 
退出; 
} 
 
 if($ _FILES ['file'] ['type']!=“application / pdf”){
 echo'不是pdf文件'; 
 unlink  ($ uploadfile); 
 exit; 
} 
  code>  pre> 
 
 

最终产品有望发送一封电子邮件,其中包含该文件作为附件。 现在我失败并得到我内置的“无法移动文件”消息。有一个明显的原因吗? 我从HTML中的文件对话框中获取 $ file code>( input type =“file” code>) p> div>

Two things:
1. Is the form set to:

<form method="POST" enctype="multipart/form-data" action="INSERT ACTION">

2. Is the folder your posting the file to, is it set to 777?

Your form needs to have the appropriate enctype attribute set, ie

<form enctype="multipart/form-data" method="post" action=... >

Update

A couple of suggestions...

  1. Check the file type and do any other general validation before you move the uploaded file. That should be your last step.
  2. Can't remember exactly right now but I don't think you'll get anything useful (or at all) in the $_POST['file'] value. Use the $_FILES array for all uploaded file data.