Now lets upload one file to some user directory on a server. Lets create file upload_form.php on our server. It will contain mainly html code:
upload_form.php
<html> <body> <form enctype="multipart/form-data" action="upload.php" method="POST"> File: <input name="ourfile" type="file" /> <button type="submit">Upload</button> </form> </body> </html>
Its very simple file with only one form. Don’t forget to add enctype="multipart/form-data" to your form when its used for file uploads. In this form we have to fields - the first is our file and the second is the submit button.
Now we need another file upload.php. Here is its content
upload.php
<?php $dir = '/var/www/files/'; $destinationfile = $dir . basename($_FILES['ourfile']['name']); if (move_uploaded_file($_FILES['ourfile']['tmp_name'], $destinationfile)) { echo "Upload successful!"; } else { echo "File attack!\n"; } ?>
Here we have destination directory for our uploads - $dir = '/var/www/files/'. Our file will be saved in this directory and will have the name of the uploaded file.
The function move_uploaded_file checks if the file (first parameter) is a valid uploaded file and if its valid it moves it to $destinationfile. If you just want to check the file without moving it use is_uploaded_file instead.
And that’s all. Now if you have done everything the right way you must see “Upload successful!” when you use upload_file.php and upload file.
The original of this tutorial is here http://ldeveloper.blogspot.com/2011/08/php-and-handling-file-uploads-easy.html
No comments:
Post a Comment