How to upload a files in php

How to upload a files in php

At some point in time, we all had requirements to upload some file on a website whether it’s for gallery image or CV for a career page.

Here we have created a simple page that will upload multiple files and place them in a directory. We will also have a look at how to manage files using DB so that you can show them in your gallery/front end.

Upload some files to directory

First, you need to add enctype in your form.

<form  method="post" enctype="multipart/form-data">
	<input style="margin-top:30px" id="image1" name="image1" multiple="multiple" type="file" />
        <button type="submit" name="submit" class="btn btn-primary">Submit</button>

once this form is submitted it will set the value of submit as we have named our button as submit. You can use below code so your file gets uploaded and saved to images directory inside your server.


// check if form was submitted
	// directory where you want to keep files
	// Look for files and upload them to images folder
		foreach($_FILES as $key => $image_data)
				//echo "image $counter is valid temp path : ".$image_data['tmp_name']." actual path: images/".$image_data['name'];
				//generate a unique file name
				$fileName = $imageNamePrefix . ($counter+1).'_'.$image_data['name'];
				$uploaded = move_uploaded_file($image_data['tmp_name'], $fileDirectory.$fileName);


This code supports for multiple files upload. So you can have multiple file tags inside your form and all of them will be uploaded.

Note: Make sure you have directory images where you have your code or change the name in php code.

Get complete file from GitHub



Leave a Reply

Your email address will not be published. Required fields are marked *