December 16, 2023 5:01 am

File uploading with PHP

This post will explain you that how to upload an image on your web host from browser. First of all you need to make HTML form.

[wpdm_file id=2]

HTML Code

Simple HTML Code

<form enctype="multipart/form-data" action="upload.php" method="POST">
 Please choose a file: <input name="file" type="file" /><br />
 <input type="submit" value="Upload" />
 </form>

This form will send file to upload.php now make upload.php file.

PHP Code

Actual upload is very simple

<?php 
 $target = "upload/"; 
 $target = $target . basename( $_FILES['file']['name']) ; 
 if(move_uploaded_file($_FILES['file']['tmp_name'], $target)) 
 {
 echo "The file ". basename( $_FILES['file']['name']). " has been uploaded";
 } 
 else {
 echo "Sorry, there was a problem uploading your file.";
 }
 ?>

This is very small piece of code upload file send to it by HTML

$target = “upload/”; is where we assign the folder that files will be uploaded to.

As you can see in the second line, this folder is relative to the upload.php file. So for example, if your file was at www.yours.com/files/upload.php then it would upload files to www.yours.com/files/upload/yourfile.gif. Be sure you remember to create this folder!

We then move the uploaded file to where it belongs using move_uploaded_file ().

Limit the File Size

if ($uploaded_size > 350000)
 {
 echo "Your file is too large.<br>"; 
 $ok=0;
 }

You can change this line to be a larger or smaller size if you wish by changing 350000 to a different number.

Limit Files by Type

if ($uploaded_type =="text/php")
 {
 echo "No PHP files<br>";
 $ok=0;
 }

Above code checks whether user upload a .php file or not.

In this block we restrict user to upload only .gif file.

if (!($uploaded_type=="image/gif")) 
{
 echo "You may only upload GIF files.<br>";
 $ok=0;
 }

Author Huzoor Bux

I am Huzoor Bux from Karachi (Pakistan). I have been working as a PHP Developer from last 5+ years, and its my passion to learn new things and implement them as a practice. Basically I am a PHP developer but now days exploring more in HTML5, CSS and jQuery libraries.


Tutorial Categories:

6 responses to “File uploading with PHP”

  1. Great tutorial.
    It is very easy and helpful for new PHP programmer like me.
    Thanks

  2. this saved my time….thanks huzoor

  3. Gaurav says:

    very helpful site I ever got……

  4. milan says:

    thanx phpgang

  5. Bashir Noori says:

    didn’t apply any security , so it’s not secure to use in public !

Leave a Reply

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