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:
<form enctype="multipart/form-data" method="post"> Upload a file <input name="my_file" type="file" /> <input type="submit" value="Upload" /> </form>
Note: You should have this enctype=”multipart/form-data”‘ in your form tag while uploading files.
The php source code to upload the files
if(isset($_FILES['my_file']['name']) && $_FILES['my_file']['name'] != '')
{
$upload_dir = 'home/myaccount/public_html/images';//uploading directory, this folder should have write permission to the current user
$upload_file = $upload_dir.'/'.basename($_FILES['my_file']['name']);
//check if the file name already exists
if(file_exists($upload_file))
{
echo "File Already Exists"; //if file already exists print the error message
}
else
{
if(move_uploaded_file($_FILES['my_file']['tmp_name'],$upload_file))
{
echo "File Uploaded";
}
else
{
echo "There was a problem to upload file";
}
}
}
?>
