How to Upload Files to Web Server in PHP?

 PHP is a server side scripting language and mostly used for creating dynamic web pages. The live examples of PHP are: Facebook.com, WordPress.com, Joomla.com and many other websites. PHP is an open source free of cost web language which is used by millions of web developers now a days. It simplify your online web projects and applications and adds beauty to them. I’m myself a lover of PHP and studying it for couple of months. I am also interested to teach PHP on this blog by making video tutorials and text-based tutorials for all those who want to learn practical usage of PHP. So today, I have a tutorial for you in which we’ll be discussing how to upload files to web server via PHP.
If you are interested in learning PHP then you might know about a complete offline package for Using PHP called “XAMPP” and also “WAMP”. So before starting learning PHP you must have installed either “XAMPP” or “WAMP” which provide you a complete environment for making web applications in PHP.
Whether you install xampp or wamp, after installing the software you’ll find its folder directly in your C: drive. There will be a folder called “htdocs” (in Xampp) & “www” (in wamp) in your installed folder, so this is your root folder and you’ll have to save all your files there in that folder, and after creating a file or new folder there. You’ll just open it on your browser with this address:http://localhost/test/file.php, so in this example localhost is my local server and the test is a folder which I created inside “htdocs” folder and the file.php is my file inside test folder. Also after installing the xampp or wamp package check the installation by entering this address in your browser:http://localhost, so if it is installed correctly then it should work just fine.
These two software have all the necessary tools which are required in order to run PHP on your computer, because PHP is not a normal web language like HTML, CSS & JavaScript. It is an advance server side language which needs to be execute by a server. Now lets start the tutorial about adding files via PHP.

How to add images in PHP?

There are many type of files you can upload to your server via PHP such as images, videos, text files and so on. But we’ll upload some images in today’s tutorial and you can also add other files by using the same method.
In order to upload files to your web server or local server, you’ll need to create a new file by using Notepad or Notepad++ or Dreamweaver.
For uploading files we’ll need to create an HTML page to show the uploading options to the users, and we can create a script in PHP for uploading the files into our server. However, you can use a single HTML page in which you’ll insert all the HTML and PHP codes together. Here is the simple HTML code which we’ll need to receive the data from the user, and for this purpose we use HTML forms:

<center>
<form action=”file.php” method=”post” enctype=”multipart/form-data”> 
<table border=”2″>
<tr height=”100″><td>Upload A file:</td>
<td><input type=”file” name=”file”></td></tr>
<tr height=”100″><td>Click Upload File:</td><td><input type=”submit” name=”submit” value=”Upload File”></td></tr>
</table>
</form></center>
In above coding you can see we added a form in HTML and its attributes are: actionmethod andenctype, these three attributes are very important in order to receive data like images & videos etc. The file.php will be the file to which the user will be sent after clicking the upload file button. Method is post for receiving the data and it is indeed the best method in PHP. Also the enctype is very very important in this case, because we must need it for receiving data like images and videos etc. Images and videos have multiple parts such as their names, types, sizes and so on. So therefore, we add enctype in this. The rest coding is just for making the form readable.
Now here is the PHP simple script for above form: 
if (isset($_POST[‘submit’])) {
$name=$_FILES[‘file’][‘name’];
$type=$_FILES[‘file’][‘type’];
$size=$_FILES[‘file’][‘size’];
$tmp=$_FILES[‘file’][‘tmp_name’];
echo “$name <br> $type <br> $size”;
}
In above PHP script we used the $_POST array with an if statement, because we earlier mentioned in form that we’ll get the data via Post method, and we created 4 different variables for all the parts of the file such as name, type, size and tmp; and we collected the data via another default PHP array $_FILES which is used for getting files’ data. And in last we printed the data and when the user will click the upload file button he will see the name of the image, type of the image, size of the image on the same page. We did this because we wanted to check our script whether it’s working or not.

How to validate the files before uploading?

Now the interesting part is here. We can’t allow people to upload the files as they want. We’ll validate the variables for allowing people to upload only the specific kind of files. We’ll validate the type of the files, the size of the files and after that we’ll save the files somewhere on our local computer or in web server. So here is the complete PHP script for validating the files uploading them:
<?php
if (isset($_POST[‘submit’])) {
$name=$_FILES[‘file’][‘name’];
$type=$_FILES[‘file’][‘type’];
$size=$_FILES[‘file’][‘size’];
$tmp=$_FILES[‘file’][‘tmp_name’];
if ($name==”){
echo “<script>alert(‘Please Select a file from computer!’)</script>”;
exit();
}
if (($type == “image/jpeg”) || ($type == “image/gif”) || ($type == “image/png”)) {
if (file_exists(“images/” . $_FILES[“file”][“name”]))
{
echo “This file $name is already exist!<br> please try another one..”;
exit();
}
if ($size <= 50000){
move_uploaded_file($tmp,”images/$name”);
echo “<center><font color=red>File was uploaded successfully!</font><br>Uploaded Image is here<br><img src=’images/$name’> </center>”;
}
else {
echo “Size of the image $size is larger than 50kb and it’s not allowed… <br> image size must be less than 50kb..”;
}
}
else {
echo “$type this is not a valid type of file<br>only upload Jpeg, PNG and Gif images”;
}
}
?>
In above example I’ve given the complete PHP script altogether. In this script we added all the necessary validations and also we uploaded the file to our server via the move_uploaded_filedefault PHP command.
In above example, we said in an if statement that only Jpeg, PNG & gif type of images will be allowed to upload, also we said that size must be less than 50kb, and we also used a query which checks for the existing file names, this query will stop the script if it finds a file which is already existing. And finally we added the file to our computer by using move_uploaded_file function.
We also printed the image on the same page. So when you’ll upload an image and click the upload file button the image will be shown on the same page. And we moved the uploaded file to a folder called “images” which you should create inside the folder where you’ve kept the file.php file. However, if you don’t want to save the images inside a folder then change: $tmp,”images/$name”to only $tmp, $name and also change <img src=’images/$name’> to <img src=’$name’> so it will be uploaded directly to the same folder where the file.php is existing.
Now for your clarification the final code including both HTML and PHP which you can directly copy and paste inside a blank notepad document, you’ll have to just save it as file.php and will have to save it inside “htdocs” folder in the xampp or wamp installation folder, here is the complete code:
<html>
<head>
<title>Uploading Files via PHP</title>
</head>
<body>
<center><form action=”file.php” method=”post” enctype=”multipart/form-data”>
<table border=”2″>
<tr height=”100″><td>Upload A file:</td>
<td><input type=”file” name=”file”></td></tr>
<tr height=”100″><td>Click Upload File:</td><td><input type=”submit” name=”submit” value=”Upload File”></td></tr>
</table>
</form></center>
<?php
if (isset($_POST[‘submit’])) {
$name=$_FILES[‘file’][‘name’];
$type=$_FILES[‘file’][‘type’];
$size=$_FILES[‘file’][‘size’];
$tmp=$_FILES[‘file’][‘tmp_name’];
if ($name==”){
echo “<script>alert(‘Please Select a file from computer!’)</script>”;
exit();
}
if (($type == “image/jpeg”) || ($type == “image/gif”) || ($type == “image/png”)) {
if (file_exists(“images/” . $_FILES[“file”][“name”]))
{
echo “This file $name is already exist!<br> please try another one..”;
exit();
}
if ($size <= 50000){
move_uploaded_file($tmp,”images/$name”);
echo “<center><font color=red>File was uploaded successfully!</font><br>Uploaded Image is here<br><img src=’images/$name’> </center>”;
}
else {
echo “Size of the image $size is larger than 50kb and it’s not allowed… <br> image size must be less than 50kb..”;
}
}
else {
echo “$type this is not a valid type of file<br>only upload Jpeg, PNG and Gif images”;
}
}
?>
</body>
</html>
Now after saving the file check it on the browser with this address: http://localhost/test/file.php and you’ll find the HTML form which will be showing the file upload field and uploading button, just upload a picture and click the button; you’ll see the result, but making it sure you’ve created  a folder ‘test’inside ‘htdocs‘ and have saved the file.php inside test folder.
This tutorial was for uploading files to your local server by using XAMPP or wamp packages, but you can also use this tutorial for uploading files to your online web server.
I hope you’ve learned something from this tutorial and if you want to learn advance PHP applications then must subscribe to my blog and like it on Facebook, because I’ve planned to publish advance tutorials of PHP, HTML, CSS, JavaScript, DW, Jquery and other popular web languages. Peace OUT!