File Uploading in PHP
Necessary Functions and Variables
1. $_FILES Global Variable
Atrributes
a) $_FILES['userfile']['name'] -> return the name of the file
b) $_FILES['userfile']['type'] -> return the type of the file
File Types
1.Microsoft Word Document => application/msword
2.Microsoft Powerpoint => application/vnd.ms-powerpoint
3.Open Office Document => application/octet-stream
4.PDF files => application/pdf
5.JPEG Image => image/jpeg
6.GIF Image => image/gif
7.MP3 File => audio/mpeg
8.Text File => text/plain
c) $_FILES['userfile']['size'] -> return the size of the file in Bytes
d) $_FILES['userfile']['error'] -> return 0 if file uploaded successfully
e) $_FILES['userfile']['tmp_name'] -> return temporary path which is specified in php.ini file
2.move_uplaoded_file(tmpname,destname) -> file will bw copied from temporary folder to destination folder.
Example Program
Conditions
1. User can upload only
a) Text Files,
b) Images (JPEG and GIF) ,
c) Portable Document File(pdf),and
d) MP3 Songs
2. Maximum File Size is 10 MB (10485760 Bytes)
HTML Page (file-upload.html)
<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en_US”>
<!–
* Author : Antony
* Created on 13-Feb-08
* Program Name : file-upload.html
–>
<head>
<title> </title>
</head>
<body>
<form enctype=”multipart/form-data” action =”upload.php” method=”post”>
<center>
<h3> File Uploading Using PHP</h3>
<br><br>
Select the file <input type=”file” name=”userfile”><br><br>
<input type=”submit” value=”Upload”>
</center>
</form>
</body>
</html>
PHP Program (upload.php)
<?php
/*
* Author : Antony
* Created on 13-Feb-08
* Program Name : upload.php
*/
$uploaddir = ‘/home/anthoniraj/uploads/’;
$uploadfile = $uploaddir . $_FILES['userfile']['name'];
$type =$_FILES['userfile']['type'];
$size =$_FILES['userfile']['size'];
if( ($type == “text/plain”) || ($type == “application/pdf”) || ($type == “image/jpeg”) || ($type == “image/gif”) || ($type == “audio/mpeg”))
{
if($size<=10485760)
{
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile))
{
echo “File is valid, and was successfully uploaded.\n”;
}
else
{
echo “File upload failed<br> “;
}
/*echo ‘Here is some more debugging info:<br>’;
print_r($_FILES); */
}
else
{
echo “File Size Exceeded . Max :10 MB Only”;
}
}
else
{
echo “Only Image,Text,Audio and pdf files are valid to upload”;
}
?>
