Upload a single file using PHP – II
In the previous post, we’ve seen how to upload a file using php. In this post, how to rename a file and validate file size and type.
Rename a file
First, lets create the form with enctype “multipart/form-data”, method “post” and input tags file, submit using the html:
<form method="post" enctype="multipart/form-data" > <input type="file" name="attachment" /> <input type="submit" name="Submit" value="Upload" /> </form>
If a uploaded file name already exists in server then rename the file name. The sample PHP script for rename file as follow.
<?
if($_POST['Submit']=='Upload')
{
$attachment= $_FILES['attachment']['name'];
if($attachment)
{
$path= "upload/".addslashes($attachment);
if(file_exists($path))
{
$path_info = pathinfo($_FILES['attachment']['name']);
$extension = strtolower($path_info['extension']);
$path= "upload/".date('dmyHis').".".$extension;
}
if(move_uploaded_file($_FILES['attachment']['tmp_name'], $path))
echo 'Successfully Uploaded...';
}
}
?>File size validation
The following PHP script used to validate the file size should be less than 1 mb.
<?PHP
if($_POST['Submit']=='Upload')
{
$attachment= $_FILES['attachment']['name'];
if($attachment)
{
$fileSize = ($_FILES['attachment']['size']/1024);
if($fileSize<1024)
{
$path= "upload/".addslashes($attachment);
if(copy($_FILES['attachment']['tmp_name'], $path))
echo 'Successfully Uploaded...';
}
else
echo 'File size < 1mb...';
} }
?>File type validation
The following PHP script used to validate the file type should be jpg, png and gif.
<?PHP
if($_POST['Submit']=='Upload')
{
$attachment= $_FILES['attachment']['name'];
if($attachment)
{
$path_info = pathinfo($_FILES['attachment']['name']);
$allowed_type=array('jpg','png','gif');
if(in_array(strtolower($path_info['extension']),$allowed_type)==true)
{
$path= "upload/".addslashes($attachment);
if(copy($_FILES['attachment']['tmp_name'], $path))
echo 'Successfully Uploaded...';
}
else
echo 'Invalid File type...';
} }
?>

Upload a single file using PHP
[…] next post, how to rename a file and validate file size and […]
Upload multiple files using PHP
[…] Click here – Upload a single file using PHP – II (rename, size and type validation) […]