Uploading the files using PHP

By admin at 22 July, 2008, 2:00 pm

I think you have got a lot of tutorial regarding to the file upload. Uploading a file in PHP is not a great deal. If you are still confound and searching for the uploading stuff then let me help you. Do not worry, it’s simple. You may just copy and paste to use it.
Firstly you need to create a simple HTML form to let user select a file to upload. So lets create it.

[upload_form.html]

1
2
3
4
5
6
7
8
9
 
<form action="upload.php" method="post" enctype="multipart/form-data" name="upload" >
<div align="center" style="line-height: 1.9em">
Choose file to upload
<br />
<input name="userfile" type="file"><br />
<input name="upload" type="submit" value="Upload" /> 
</div>
</form>

Secondly, you need to create PHP script that is going to handle our uploads. This PHP file should make a key decision with all uploads: keep the file or throw it away. A file might be thrown away from many reasons, including:

  • The file is too large and you do not want to have it on your server.
  • You want to restrict that the file must be image (.jpeg, jpg, bmp etc) file and not other.
  • Others

[upload.php]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 
<?php
 
##################################
#Copyright 2008, Jayesh Shrestha
#You may use, modify and distribute  
#this code as long as this copyright
# notice is preserved.
##################################
 
$target_path = "upload/"; // define the path where the files are to be kept
 
$target_path = $target_path . basename( $_FILES['userfile']['name']); 
 
if(move_uploaded_file($_FILES['userfile']['tmp_name'], $target_path)) {
    echo "The file has been uploaded";
} else{
    echo "There was an error uploading the file, please try again!";
}
 
?>

Note :: You may use copy() function as well. This makes a copy of the file source to destination. Returns TRUE on success or FALSE on failure


Spread the Words!




No comments yet.

Sorry, the comment form is closed at this time.