Upload a file to website?

2019-07-22 12:59发布

问题:

Hey guys i was just wondering, how do you use PHP to upload a file directly to your website?

for example:

Person uses a browse button to look for file to upload, then once selected file directory comes up in a textbox and when they click and "upload" button it uploads to a directory on the website named "uploads".

Could someone tell me how to do this and maybe explain a little about or link me to a resource which will help me?

Thanks.

回答1:

Have a form and put an file input in it:

<form name="my_form" method="post" enctype="multipart/form-data" action="my_php_script.php">
    <input type="file" name="my_file" />
</form>

Then in my_php_script.php, handle the file upload just like any other POST request. See this page for details on the backend: http://www.tizag.com/phpT/fileupload.php

The $_FILES array holds data pertaining to the uploaded file.

  • $_FILES['uploadedfile']['name'] - the original path of the user uploaded file.
  • $_FILES['uploadedfile']['tmp_name'] - the path to the temporary file that resides on the server. The file should exist on the server in a temporary directory with a temporary name.

You should move the file from the temporary directory to more permanent storage (like an uploads/ folder). You can do this using the move_uploaded_file() function like so:

move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $uploads_folder);


回答2:

Everything is explained in the Handling file uploads section in the PHP manual.

I'd recommend to avoid using the MAX_FILE_SIZE hidden field since it's not part of any standard, there is no known browsers support and it's easy to modify it's value to affect PHP behavior on the server side.



回答3:

Make sure you specify multipart/form-data in the form element, then include file fields. You'll need to do some additional work on the receiving end to get the file data and store it with an appropriate name, instead of a default/temporary directory on the server.

<form action="/some/url" enctype="multipart/form-data" method="post">
    <input type="file" name="some_file" />
    <intput type="submit" name="Upload that file!" />
</form>


回答4:

You should use an HTML form with enctype set to multipart/form-data like:

<form action="upload_file.php" method="post" enctype="multipart/form-data">
    <input type="file" name="thefile" />
</form>

Then in PHP you can check $_FILES['thefile'] to get the information you want. The file will be in $_FILES['thefile']['tmpname'] and you can move it from there to your uploaded file to the correct folder using move_uploaded_file():

move_uploaded_file($_FILES['thefile']['tmpname'], 'uploads/'.$_FILES['thefile']['name']);

Of course you'll want to do additional sanity checks to make sure that you're not overwriting an exisiing file and the file was uploaded successfully without error.