PHP can't upload file from HTML form

2019-01-28 20:56发布

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."\n";
        $message .= "Email: ".$email."\n\n";
        $message .= "Title of Article: ".$title."\n";
        $message .= "Program: ".$course."\n\n";
        $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")

2条回答
贪生不怕死
2楼-- · 2019-01-28 21:25

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?

查看更多
何必那么认真
3楼-- · 2019-01-28 21:29

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.
查看更多
登录 后发表回答