Skip to main content

Upload Image Into A Folder In Php Step By Step

This tutorial is about upload image to folder using PHP language. If you want to consider uploading to database you might read my tutorial. Uploading image is a feature in our application that everyone will love. So we begin...

Step 1. Create your html with form and file field and submit button inside. Name the form to imageUploadand apply enctype="multipart/form-data", this will allow the form to accept file as input. Name the input file to upload and submit button to xsubmit.

01<html>
02<head>
03<title>Upload Image To Folder In PHP Step By Step</title>
04</head>
05
06<body>
07<form name="imgUpload" action=""method="post" enctype="multipart/form-data">
08<input type="file" name="upload" />
09<input type="submit" name="xsubmit" value="Upload" />
10</form>
11</body>
12</html>

...Before we proceed to step two, first we must understand about file information:
The global $_FILES  exists as of PHP 4.1.0 (Use $HTTP_POST_FILES  instead if using an earlier version). These arrays will contain all the uploaded file information. The contents of $_FILES from the example form is as follows. Note that this assumes the use of the file upload name upload, as used in the example script above. This can be any name.

The original name of the file on the client machine.
$_FILES['upload']['name']

The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.
$_FILES['upload']['type']

The size, in bytes, of the uploaded file.
$_FILES['upload']['size']

The temporary filename of the file in which the uploaded file was stored on the server. 
$_FILES['upload']['tmp_name']

The error code associated with this file upload. This element was added in PHP 4.2.0 
$_FILES['upload']['error']

Step 2. We gonna create our PHP upload code.
01<?php
02//Check if submit button exist and click
03if(isset($_POST['xsubmit'])) {
04  // get the original filename
05  $image = $_FILES['upload']['name'];
06  
07  // image storing folder, make sure you indicate the right path
08  $folder "images/";
09  
10  // image checking if exist or the input field is not empty
11  if($image) {
12    // creating a filename
13    $filename = $folder . $image;
14  
15    // uploading image file to specified folder
16    $copied copy($_FILES['upload']['tmp_name'], $filename);
17  
18    // checking if upload succesfull
19    if (!$copied) {
20  
21      // creating variable for the purpose of checking:
22      // 0-unsuccessfull, 1-successfull
23      $ok 0;
24    } else {
25      $ok 1;
26    }
27  }
28}
29?>
30
31
32<html>
33<head>
34<title>Upload Image To Folder In PHP Step By Step</title>
35</head>
36
37<body>
38<form name="imgUpload" action="" method="post" enctype="multipart/form-data">
39<input type="file" name="upload" id="upload" />
40<input type="submit" name="xsubmit" value="Upload" />
41</form>
42</body>
43</html>

Step 3. After uploading the image, lets try to display it. Using our $ok variable we can apply checking for image existing and apply it to the image src of the image display. Here's the final code.

01<?php
02//Check if submit button exist and click
03if(isset($_POST['xsubmit'])) {
04  // get the original filename
05  $image = $_FILES['upload']['name'];
06  
07  // image storing folder, make sure you indicate the right path
08  $folder "images/";
09  
10  // image checking if exist or the input field is not empty
11  if($image) {
12    // creating a filename
13    $filename = $folder . $image;
14  
15    // uploading image file to specified folder
16    $copied copy($_FILES['upload']['tmp_name'], $filename);
17  
18    // checking if upload succesfull
19    if (!$copied) {
20  
21      // creating variable for the purpose of checking:
22      // 0-unsuccessfull, 1-successfull
23      $ok 0;
24    } else {
25      $ok 1;
26    }
27  }
28}
29?>
30
31
32<html>
33<head>
34<title>Upload Image To Folder In PHP Step By Step</title>
35
36</head>
37
38<body>
39<?php
40    //check if upload succesful then display it
41    if($ok == 1) {
42?>
43<img src="<?php echo $filename; ?>">
44<?php
45    }
46?>
47<form name="imgUpload" action="" method="post" enctype="multipart/form-data">
48<input type="file" name="upload" id="upload" />
49<input type="submit" name="xsubmit" value="Upload" />
50</form>
51</body>
52</html>

Before upload
File selected
After upload
Step 4. The upload accept anything aside from images, to filter and to accept only images we gonna add  validation function using Javascript. We gonna add id to our file input field, this id is the same as the name. To trigger our validation we can apply to onsubmit event in form or using onclick and attach to our submit button. Here's again the complete source code.

01<?php
02//Check if submit button exist and click
03if(isset($_POST['xsubmit'])) {
04  // get the original filename
05  $image = $_FILES['upload']['name'];
06  
07  // image storing folder, make sure you indicate the right path
08  $folder "images/";
09  
10  // image checking if exist or the input field is not empty
11  if($image) {
12    // creating a filename
13    $filename = $folder . $image;
14  
15    // uploading image file to specified folder
16    $copied copy($_FILES['upload']['tmp_name'], $filename);
17  
18    // checking if upload succesfull
19    if (!$copied) {
20  
21      // creating variable for the purpose of checking:
22      // 0-unsuccessfull, 1-successfull
23      $ok 0;
24    } else {
25      $ok 1;
26    }
27  }
28}
29?>
30
31
32<html>
33<head>
34<title>Upload Image To Folder In PHP Step By Step</title>
35<script type="text/javascript">
36  function checkExt(){
37    var filename = document.getElementById('upload').value;
38    var filelength = parseInt(filename.length) - 3;
39    var fileext = filename.substring(filelength,filelength + 3);
40   
41    // Check file extenstion
42    if (fileext.toLowerCase() != "gif" && fileext.toLowerCase() != "jpg" && fileext.toLowerCase() != "png") {
43      alert ("You can only upload png or gif or jpg images.");
44      return false;
45    } else {
46      return true;
47    }
48}
49</script>
50</head>
51
52<body>
53<?php
54    //check if upload succesful then display it
55    if($ok == 1) {
56?>
57<img src="<?php echo $filename; ?>">
58<?php
59    }
60?>
61<form name="imgUpload" action="" method="post" enctype="multipart/form-data">
62<input type="file" name="upload" id="upload" />
63<input type="submit" name="xsubmit" value="Upload" onClick="return checkExt();" />
64</form>
65</body>
66</html>

This will pop-up if non-image uploaded

Comments

Popular posts from this blog

Off-Page SEO – 7 Tips On How To Build BackLinks

Well a site cannot get expected traffic without doing seo in the world of completion. After introducing  on page seo . Now come back to introduce off page seo and basics of off page seo. As the word off page seo shows to do seo staying off from own page. Means to optimize a website from other sources. In simple a short we can define it as link building or creating backlinks. Off page seo helps site to get rank in search engines.   Fairly Off page seo is to create and build backlinks from several of ways. Off page seo is a hungriness of backlinks.”There so many ways to do off page seo or creating backlinks but now, let me show you how to build links to your pages: 1. Profile Pages Build Profile Pages in the top Social Media sites like: Google+ Profiles-           https://profiles.google.com            (A Must) Facebook Pages –     ...

August 6, 2017 CSE-PPT Professional Level - List of Passers (REGION XII)

August 6, 2017 CSE-PPT Professional Level  - List of Passers Civil Service Commission Regional Office No. 12 SOURCE: PRC ABALOS, ROMEO III G ABANG, CHRISTIAN MARK B ABAS, AMIRA A ABBA, BRYAN M ABDULADSIS, SAYEED MOHBEN K ABDULSATAR, SAHID M ABEAR, KRIZIA ANDREA Q ABELLON, SHIENA MAE F ABING, MARY SOL T ABOLENCIA, SEAN HOPE C ACIDO, DANIEL CARLO G ACUPAN, NONA MARIE P ADANG, SAIMA D ADELAN, MAILA LOUISA N ADVENTAJADO, CLYDELL S AGAD, LUCILLE ANGELIKKA DC AGAWA, YSA LOU S AGCARAO, APRIL BERNADETH P AGUILAR, RUTH D AGUJA, MARCO D AGURING, FROILAN J AJOC, LOVELL L AKIL, SAGUIRA M ALAMADA, SHAINETRA C ALAMAN, OMAR ADRIANNE P ALBARAN, GLORY GRACE C ALBRANDO, GERALDINE P ALCANTARA, KIMBERLY V ALCOBA, MARY ANN L ALCORDO, QUENNIE N ALDAVE, ANNABELLE JOY B ALLAGA, LOREN F ALLOSO, MERCY FE N ALMOJALLAS, JAN MARIE MAY J ALONZO, CHARMAINE KLAIRE A ALTIZO, ALEN JANE E ALURAN, ELLEN JANE C ALVAREZ, NEALL DOMINICK T AMAN, JOHN PAUL C AMANDE, JOEVEN A AMBAY, ARRIZ PAULA D AMER, ABJUHARY H AMINO, ...

Future Pinoy scientists, a Museum of Natural History

Michael Purugganan, when he was an elementary student at Union Science Elementary School in Malate, used to sneak into the National Science Development Board premises, where he would spend hours in a small museum.  "It just fascinated me. I just wanted to learn more about these things and what these people were doing there," Purruganan told GMA News Online.  "That was really what inspired me to become a scientist," said Purugganan, who is currently the Dean for Science at New York University and a world leader in evolutionary and ecological genomics.   With a new museum in the works, more young Filipinos may be inspired to become scientists. In a couple of years, the Philippines will have its own world class Museum of Natural History, showcasing endemic plants and animals that can be found in the country, according to a report on State of the Nation on January 23. Museums bridge the past and present, but the government believes these can also meet...