Tuesday, August 12, 2008

File Uploading in PHP

File uploading is very simple in PHP when comparing to other server side programming languages. File uploading is very useful in most of the situations like uploading user’s photos, uploading csv reports, uploading pdf reports and so on.

Making a simple front end with file browsing box:

1.

2.

3.
Upload a file
4.

5.

6.


Note: You should have this enctype=”multipart/form-data”‘ in your form tag while uploading files.
The php source code to upload the files

1.

2.
if(isset($_FILES[‘my_file’][‘name’]) && $_FILES[‘my_file’][‘name’] != ”)
3.
{
4.
$upload_dir = ‘home/myaccount/public_html/images’;//uploading directory, this folder should have write permission to the current user
5.
$upload_file = $upload_dir.‘/’.basename($_FILES[‘my_file’][‘name’]);
6.

7.
//check if the file name already exists
8.
if(file_exists($upload_file))
9.
{
10.
echo "File Already Exists"; //if file already exists print the error message
11.
}
12.
else
13.
{
14.
if(move_uploaded_file($_FILES[‘my_file’][‘tmp_name’],$upload_file))
15.
{
16.
echo "File Uploaded";
17.
}
18.
else
19.
{
20.
echo "There was a problem to upload file";
21.
}
22.
}
23.
}
24.
?>

No comments: