In this article I will show you, how to upload file into server in PHP. Let’s have an example, how to upload file into server using PHP.
Creating File Uploading Form:
Here I am giving an example to file uploading form.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title></title>
</head>
<body>
<form id ="frmBody"method="post" action="FileUpload.php" enctype="multipart/form-data">
<table>
<tr>
<td>Select File :</td>
<td> <input type="file" name ="file" id ="file" width="300px"></input> </td>
</tr>
<tr>
<td> </td>
<td><input type ="submit" name ="btnsubmit" value =" Upload"></input> </td>
</tr>
</table>
</form>
</body>
</html>
Form Design:
Here you can browse file (i.e. select file for uploading into server) by clicking on ‘Browse button. After selecting file, click on ‘Upload’ button for uploading file into server.
When you click on ‘Upload’ button then ‘FileUpload.php’ php script is called.
<?php
// Check error duringfile uploading
if($_FILES["file"]["error"] > 0)
{
// display error message
echo "<b>Error</b>".$_FILES["file"]["erro"]."</br>";
}
else
{
// display uploding file information
echo "<b>File Upload:</b> " . $_FILES["file"]["name"] . "<br/>";
echo "<b>File Type: </b>" . $_FILES["file"]["type"] . "<br/>";
echo "<b>File Size: </b>" . ($_FILES["file"]["size"] / 2048) . " Kb<br/>";
echo "<b>Stored in Place: </b>" . $_FILES["file"]["tmp_name"];
}
?>
Output:
When you click on Browse button then dialog box will be open where you can select a file to upload on server.
Now click on ‘Upload’ button, we will get following output.
Example:
Uploading file into server with some restriction
<?php
// check uploadingfile restriction
$ext = substr($_FILES["file"]["name"], strrpos($_FILES["file"]["name"], '.') + 1);
if(($_FILES["file"]["type"] == "image/jpeg") || ($ext == txt))
{
// Check error during file uploading
if($_FILES["file"]["error"] > 0)
{
// display error message
echo "<b>Error</b>".$_FILES["file"]["erro"]."</br>";
}
else
{
// display uploding file information
echo "<b>File Upload:</b> " . $_FILES["file"]["name"] . "<br/>";
echo "<b>File Type: </b>" . $_FILES["file"]["type"] . "<br/>";
echo "<b>File Size: </b>" . ($_FILES["file"]["size"] / 2048) . " Kb<br/>";
echo "<b>Stored in Place: </b>" . $_FILES["file"]["tmp_name"];
if (file_exists("Upload/".$_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] ."already exist";
}
else
{
// Save file within UploadFiles directory
move_uploaded_file($_FILES["file"]["name"], "UploadFiles/".$_FILES["file"]["name"]).'</br>';
echo "Stored in:"."Upload/".$_FILES["file"]["name"];
}
}
}
else
{
echo 'Invalid file format';
}
?>
Leave Comment