File Upload to Server in PHP

For uploading Files to the server, we need to run two files, For example let us say upload.html (to select the file) and upload.php (to upload)…. let us define each of the two files

//upload.html

<form method=post action=upload.php enctype=multipart/form-data>
Select a File: <input type=file name=myfile>
<input type=submit value=upload>
</form>

//upload.php

<?php
echo $_FILES['myfile']['size'];
echo $_FILES['myfile']['type'];
echo $_FILES['myfile']['tmp_name'];
echo $_FILES['myfile']['name'];
@copy(echo $_FILES['myfile']['tmp_name'], “./upload/”.$_FILES['myfile']['name']) or die(”Couldn’t Upload);
?>

in the above php script, instead of copy() function, move_uploaded_file() function can also be used. Before running this script, a folder called as upload should be created in the root path, for example, if /var/www/ is the document root, then a folder upload should be created at /var/www/upload

suppose if the server allows for file size less than 1 megabytes and file types to be images of jpg only, then the above code can be modified in the following way.

//upload.php

<?php
echo $_FILES['myfile']['size'].”<BR>”;
echo $_FILES['myfile']['type'].”<BR>”;
echo $_FILES['myfile']['tmp_name'].”<BR>”;
echo $_FILES['myfile']['name'].”<BR>”;
if($_FILES['myfile']['size']<=1048576 and $_FILES['myfile']['size'] == “image/jpeg” or $_FILES['myfile']['size']==”image/jpg”)
{
@copy($_FILES['myfile']['tmp_name'], “./upload/”.$_FILES['myfile']['name']) or die(”Couldn’t Upload”);
}
else
{
echo ” The file size should be less than 1 Megabytes and file type should be jPEG files only”;
}
?>

Comments

Popular Posts