Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

How to Upload Images with PHP

php upload image

  • Please log in to reply
3 replies to this topic

#1 RikRoy

RikRoy

    CC Lurker

  • New Member
  • Pip
  • 4 posts

Posted 12 February 2014 - 06:28 AM

This is my first post. So, I decided to post an easy tutorial for the beginners of PHP. I will give line to line explanation of everything. So don't give up if you don't understand the code (Though, it'd be very easy. I promise ) 
 
First of all, create a folder named upload in directory where you wish to store the pages. This will be the location where our images will be uploaded.
 
You'll need two pages for it:
  • form.php
    <html>
      <head>
        <title>
          CodeCall Tutorials
        </title>
      </head>
      <body bgcolor="#000000" text="#ffffff">
        <form method="post" action="upload.php" enctype="multipart/form-data">
          <label for="upload">
            Choose an image
          </label>
          <input type="file" name="upload">
          <br>
          <input type="submit" value="Upload your file">
        </form>
      </body>
    </html>
    
    Explanation:
     
    It is simple HTML and I don't think I need to explain but here is the explaination

    title tag defines what the title bar should say and its very clear.
    bgcolor attribute defines the background color of the page which I have set to black.
    text attribute defines the text color which is set white.
    form tag defines the start of a form and enctype defines how it should be encrypted.
    Its value that is multipart/form-data is used for parsing binary files.
    input tag creates a specified input feild I have set its type to file which creates an input feild along with a browse button next to it.

    And if anyone wants to know why I have used label tag instead of font, I would like to inform him/her that font tag has been removed in HTML 5.
     
  • upload.php
    <?php
    $allowed = array(
       "jpg",
       "jpeg",
       "bmp",
       "gif",
       "png"
    );
    $name = explode(".", $_FILES["upload"]["name"]);
    $ext = end($name);
    
    if ((($_FILES["upload"]["type"] == "image/jpg") || ($_FILES["upload"]["type"] == "image/jpeg") || ($_FILES["upload"]["type"] == "image/bmp") || ($_FILES["upload"]["type"] == "image/gif") || ($_FILES["upload"]["type"] == "image/png")) && ($_FILES["upload"]["size"] < 20000) && in_array($ext, $allowed)) {
       if ($_FILES["upload"]["error"] > 0) {
          echo $_FILES["upload"]["error"];
       }
       else {
          if (file_exists("upload/" . $_FILES["upload"]["name"])) {
             echo "File already exists";
          }
          else {
             move_uploaded_file($_FILES["upload"]["tmp_name"], "upload/" . $_FILES["upload"]["name"]);
             echo "Upload Successful";
          }
       }
    }
    else {
       echo "Invalid File";
    }
    
    ?>
Explanation:
 
First, we declare three variables.
First is an array in which I have listed all the extensions that are allowed.
Secondly, I created another array and stored the name of the uploaded file.
 
You might be wondering what is that explode() function. Well, it breaks a string into an array.
 
It needs two parameters. First one defines from where, the string should be broken (here "."). And the
second defines the string.
 
The $_FILES variable stores information about the uploaded file.
 
Thus, by the second line, I have broken the name of the uploaded file into two parts. First contains the
name and the second contains the extension of the file.
 
Then, I have created another variable to store the extension only. The end function selects only the last
value from an array.
 
Now, I think you have understood what I have done in these lines.
 
After that, I have checked if the file size is below 20 KB
 
The next few lines either store the uploaded file into a temporary file or produce an error.
 
Then, I have checked whether a file with the same name already exists. Then we move the uploaded file to the folder upload in the server and if any other error occurs, it writes Invalid file.
 
I hope you enjoyed the tutorial.
 
Note: Letting users to upload files to your web site is very risky because now days, everyone wants to hack the sites. So I suggest some security measures

Edited by Alexander, 12 February 2014 - 07:51 PM.
HTML formatting, PHP formatting (K&R style)

  • 1

#2 BlackRabbit

BlackRabbit

    CodeCall Legend

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3871 posts
  • Location:Argentina
  • Programming Language:C, C++, C#, PHP, JavaScript, Transact-SQL, Bash, Others
  • Learning:Java, Others

Posted 13 February 2014 - 07:29 AM

Welcome aboard RickRoy,

 

Nice tutorial, we are glad to have you around.

I think it will be nice if you fill your programing profile info.

 

I will be looking forward to your next tutorials.


  • 0

#3 zerokill

zerokill

    CC Lurker

  • Just Joined
  • Pip
  • 1 posts

Posted 06 June 2014 - 12:01 AM

i just want to ask you what stops me from doing this? shell.php;.jpg shell.php.jpg shell.php..jpg shell.php.jpg shell.php.jpg:; shell.php.jpg%; shell.php.jpg; shell.php.jpg; shell.php.jpg:; than just simply accessing the image and it should now have a valid php shell running with the apache daemons access rights if im not mistaken this code is 0% secure and also you are echoing back the data as long as you dont echo back my input directly xss may be a dead issue but you may want to look into htmlspecial chars i believe this is off the top of my head
  • 0

#4 surajkumardotin

surajkumardotin

    CC Regular

  • Member
  • PipPipPip
  • 29 posts
  • Location:Ludhiana
  • Programming Language:PHP, JavaScript
  • Learning:C, C++, PHP, JavaScript

Posted 18 August 2015 - 12:27 AM

Hello "RikRoy",

 

I am going to provide you a link where i have create a script for upload image with php.You can also learn here that how to upload multiple images with php file functions.

 

Here is example code of php:

 

Display forum

<?php require('upload.php'); ?>
<!doctype html>
<html>
    <head>
        <title>Uploading Multiple Images</title>
        <link rel="stylesheet" type="text/css" href="bootstrap.min.css" />
    </head>
    <body>
        <div class="container">
            <h3 class="page-header">Uploading Multiple Images</h3>
            <form method="post" action="" enctype="multipart/form-data">
            <table class="table table-bordered">
                <tr>
                    <td>Upload Image</td>
                    <td><input type="file" name="images[]" multiple /></td>
                </tr>
                <tr>
                    <td colspan="2"><input type="submit" class="btn btn-primary" name="upload" value="Submit" /></td>
                </tr>
                <tr>
                    <td colspan="2">
                        <?php
                            if(isset($_POST['upload'])){
                                $images=$_FILES['images']['name'];
                                $images_tmp=$_FILES['images']['tmp_name'];
                                $images_size=$_FILES['images']['size'];
                                $directory='uploads';
                                if(count($images)<=0){
                                    $upload_res=upload_multiple_images($images,$images_tmp,$images_size,$directory);
                                }else{
                                    $upload_res='Please select images';
                                }

                                echo '<pre>';
                                print_r($upload_res);
                                echo '</pre>';
                            }
                        ?>
                    </td>
                </tr>
            </table>
            </form>
        </div>
    </body>
</html>

Upload Image php Code  "upload.php"

	// Define function for uploading image
	function upload_multiple_images($images_array,$images_tmp,$images_size,$dir){
		$res=array();

		// extension array
		$ext=array('png','jpg','gif','jpeg','bmp');

		// Define size of image in kb
		$size=2000;

		// Count images
		$total_images=count($images_array);
		$res['total_uploaded_images']=$total_images;

		// check directory exist or not
		if(file_exists($dir)){
			// loop over image
			$count=0;
			foreach($images_array as $single_image){
				// Get image extension
				$image_ext=pathinfo($single_image,PATHINFO_EXTENSION);

				// Check image is valid or not
				if(in_array($image_ext,$ext)){
					// check size of each image
					$image_size=round($images_size[$count]/1000);
					if($image_size>$size){
						$res[$single_image][]='This has exceed limit of maximum size.';
					}else{
						$res['filesize'][]=$image_size;
						// rename image if exist else upload in folder
						if(file_exists($dir.'/'.$single_image)){
							// create random number
							$rand_num=rand(101,99999);
							$single_image=$rand_num.'_'.$single_image;
							// upload file on server
							move_uploaded_file($images_tmp[$count],$dir.'/'.$single_image);
							$res[$single_image][]='file has been uploaded';
						}else{
							// upload file on server
							move_uploaded_file($images_tmp[$count],$dir.'/'.$single_image);
							$res[$single_image][]='file has been uploaded';
						}
					}
				}else{
					$res['msg']='Image is not valid.';
				}
				$count++;
			}
		}else{
			$res['msg']=$dir.' directory doesn\'t exist.';
		}

		return $res;
	}

Upload Images with php


Edited by surajkumardotin, 18 August 2015 - 12:31 AM.

  • 0





Also tagged with one or more of these keywords: php, upload, image