May 2018


          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31            
 
FEEDS
 
ARCHIVES
 
RECENT ENTRIES
 
OTHER BLOGGERS
 
AGGREGATORS
 
SOCIAL NETWORKS
:: 08/30/2012 ::
Creating a Hybrid Photo Uploader with PHP, HTML5, and mySQL
Return   Back To Top
Welcome to my latest article - "Creating a Hybrid Photo Uploader with PHP, HTML5, and mySQL". I had fun putting this example application together, mixing in some things I find interesting (file uploads with PHP, converting an uploaded color photo to a black and white version leveraging a HTML5 Canvas and some JavaScript, previewing the photo prior to uploading with JQuery, and storing the data in a mySQL database). The app not only runs on desktop browsers but also on my Android phone (I'm using KSWeb for the PHP/mySQL that runs on my Galaxy Note). The complete code is available as an archive zip file. I hope you find this information useful. Thanks for reading, by the way. Now, on to the meat and potatoes of this post.
The app uses a simple form to browse to the image that will be uploaded. Listing 1 shows the code. Line 14 has a PHP variable where the maximum file size allowed is declared (1000 KB) and line 58 leverages that value in a hidden form field. Lines 27 - 44 is a JQuery snippet that enables the image preview prior to actually doing the upload. On a mobile device, this is particularly useful as the Android OS's default File Manager generally shows the filename without a thumbnail (making it hard to know what photo you're about to upload). This app's preview functionality helps to get around that limitation.

Figure 1 shows the simple form, and Figure 2 shows the preview image in use.

Figure 1. Simple Form

Figure 1 - Simple Form

Figure 2. Image Preview

Figure 2 - Image Preview

Listing 1. upload.form.php

1. <?php
2.
3. // filename: upload.form.php
4.
5. // first let's set some variables
6.
7. // make a note of the current working directory relative to root.
8. $directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);
9.
10. // make a note of the location of the upload handler
11. $uploadHandler = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'upload.processor.php';
12.
13. // set a max file size for the html upload form
14. $max_file_size = 1024000; // size in bytes
15.
16. // now echo the html page
17. ?><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
18. "http://www.w3.org/TR/html4/strict.dtd">
19.
20. <html lang="en">
21. 	<head>
22. 		<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
23. 		<link rel="stylesheet" type="text/css" href="css/stylesheet.css">
24. 		<script src="js/jquery-latest.js"></script>
25. 		<title>Upload form</title>
26. 		<script language="JavaScript">
27. 			function showPreview(ele) {
28. 					document.getElementById('lblAvatar').style.display = 'none';
29.
30. 					$('#imgAvatar').attr('src', ele.value); // for IE
31. 					if (ele.files && ele.files[0]) {
32.
33. 						var reader = new FileReader();
34.
35. 						reader.onload = function (e) {
36. 							$('#imgAvatar').attr('height', '180px');
37. 							$('#imgAvatar').attr('src', e.target.result);
38. 						}
39.
40. 						reader.readAsDataURL(ele.files[0]);
41. 					}
42.
43. 					document.getElementById('lblAvatar').style.display = 'inherit';
44. 			}
45. 		</script>
46. 	</head>
47.
48. 	<body>
49.
50. 	<div align="center">
51. 	<form id="Upload" name="Upload" action="<?php echo $uploadHandler ?>" enctype="multipart/form-data" method="post">
52.
53. 		<h1>
54. 			Upload Form
55. 		</h1>
56.
57. 		<p>
58. 			<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size ?>">
59. 		</p>
60.
61. 		<p style="text-align: left">
62. 			<label for="file">File to upload:</label>
63. 			<input id="file" type="file" name="file" onchange="showPreview(this)">
64. 		</p>
65.
66. 		<p style="text-align: left">
67. 			<label id="lblAvatar" for="imgAvatar" style="display: none">Image Preview:</label>
68. 		</p><br/>
69.
70. 		<p style="text-align: center">
71. 			<img id="imgAvatar" src="images/welcome.jpg" height="100px">
72. 		</p>
73.
74. 		<p style="text-align: left">
75. 			<label for="submit">Press to...</label>
76. 			<input id="submit" type="submit" name="submit" value="Upload me!">
77. 		</p>
78.
79. 	</form>
80. 	</div>
81.
82.
83. 	</body>
84.
85. </html>

Once the image is selected and the "Upload me!" button is clicked, the upload.processor.php file is called. Listing 2 shows the code. Line 20 sets the successful upload redirect. Lines 140 - 160 are present for error-handling. Line 50 uses the PHP function filesize to determine the file size in bytes. You should pass the file path/name to the function. Lines 52 - 107 are used to determine the image type of the upload leveraging another PHP function, getimagesize. Interestingly, this function actually returns an array with multiple values - index 0 and 1 contains the width and the height of the image, respectively; index 2 is one of the IMAGETYPE_XXX constants indicating the type of the image; index 3 is a text string with the correct height="yyy" width="xxx" string that can be used directly in an IMG tag. Lines 117 - 118 are the variables for the image name and the image url, where the image is actually uploaded, respectively. Line 121 uses the PHP function, move_uploaded_file, to move (save) the image to its final resting place. Lines 127 - 134 handle the mySQL database insert of the image upload-related information - the file name, the image URL, the file size, and the image type. Last, but not least, line 137 is where the redirect to the success page, upload.success.php, is located.

Listing 2. upload.processor.php

1. <?php
2.
3. // filename: upload.processor.php
4.
5. // first let's set some variables
6.
7. // make a note of the current working directory, relative to root.
8. $directory_self = str_replace(basename($_SERVER['PHP_SELF']), '', $_SERVER['PHP_SELF']);
9.
10. // make a note of the directory that will receive the uploaded files
11. $uploadsDirectory = $_SERVER['DOCUMENT_ROOT'] . $directory_self . 'uploaded_files/';
12.
13. // make a note of the location of the upload form in case we need it
14. $uploadForm = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'upload.form.php';
15.
16. // make a note of the location of the upload processor in case we need it
17. $uploadProcessor = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'upload.processor.php';
18.
19. // make a note of the location of the success page
20. $uploadSuccess = 'http://' . $_SERVER['HTTP_HOST'] . $directory_self . 'upload.success.php';
21.
22. // name of the fieldname used for the file in the HTML form
23. $fieldname = 'file';
24.
25. // Now let's deal with the upload
26.
27. // possible PHP upload errors
28. $errors = array(1 => 'php.ini max file size exceeded',
29.                 2 => 'html form max file size exceeded',
30.                 3 => 'file upload was only partial',
31.                 4 => 'no file was attached');
32.
33. // check the upload form was actually submitted else print form
34. isset($_POST['submit'])
35. 	or error('the upload form is needed', $uploadForm);
36.
37. // check for standard uploading errors
38. ($_FILES[$fieldname]['error'] == 0)
39. 	or error($errors[$_FILES[$fieldname]['error']], $uploadForm);
40.
41. // check that the file we are working on really was an HTTP upload
42. @is_uploaded_file($_FILES[$fieldname]['tmp_name'])
43. 	or error('not an HTTP upload', $uploadForm);
44.
45. // validation... since this is an image upload script we
46. // should run a check to make sure the upload is an image
47. @getimagesize($_FILES[$fieldname]['tmp_name'])
48. 	or error('only image uploads are allowed', $uploadForm);
49.
50. $size = filesize($_FILES[$fieldname]['tmp_name']);
51.
52. $imagetype = getimagesize($_FILES[$fieldname]['tmp_name']);
53. $imgext = "";
54.
55. switch ($imagetype[2]) {
56.     case 1:
57.         $imgext = "GIF";
58.         break;
59.     case 2:
60.         $imgext = "JPG";
61.         break;
62.     case 3:
63.         $imgext = "PNG";
64.         break;
65.     case 4:
66.         $imgext = "SWF";
67.         break;
68.     case 5:
69.         $imgext = "PSD";
70.         break;
71.     case 6:
72.         $imgext = "BMP";
73.         break;
74.     case 7:
75.         $imgext = "TIF";
76.         break;
77.     case 8:
78.         $imgext = "TIF";
79.         break;
80.     case 9:
81.         $imgext = "JPC";
82.         break;
83.     case 10:
84.         $imgext = "JP2";
85.         break;
86.     case 11:
87.         $imgext = "JPX";
88.         break;
89.     case 12:
90.         $imgext = "JB2";
91.         break;
92.     case 13:
93.         $imgext = "SWC";
94.         break;
95.     case 14:
96.         $imgext = "IFF";
97.         break;
98.     case 15:
99.         $imgext = "WBMP";
100.         break;
101.     case 16:
102.         $imgext = "XBM";
103.         break;
104.     case 17:
105.         $imgext = "ICO";
106.         break;
107. }
108.
109. // make a unique filename for the uploaded file and check it is
110. // not taken... if it is keep trying until we find a vacant one
111. $now = time();
112. while(file_exists($uploadFilename = $uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name']))
113. {
114. 	$now++;
115. }
116.
117. $imagename = $now.'-'.$_FILES[$fieldname]['name'];
118. $imageurl = "http://".$_SERVER['HTTP_HOST']."/prototypes/uploader/uploaded_files/".basename($uploadsDirectory.$now.'-'.$_FILES[$fieldname]['name'])."";
119.
120. // now let's move the file to its final and allocate it with the new filename
121. @move_uploaded_file($_FILES[$fieldname]['tmp_name'], $uploadFilename)
122. 	or error('receiving directory insuffiecient permission', $uploadForm);
123.
124. // If you got this far, everything has worked and the file has been successfully saved.
125.
126. // connect to database and insert a record
127. $link = mysqli_connect("yourIP","yourUsername","yourPassword","yourDatabase");
128. $q = "insert into pictures (imagename, imageurl, filesize, filetype) values('$imagename', '$imageurl', $size, '$imgext')"; //some sql
129. //echo $q;
130. // run query 1
131. $result = mysqli_query($link, $q);
132.
133. // close connection
134. mysqli_close($link);
135.
136. // We are now going to redirect the client to the success page.
137. header('Location: ' .$uploadSuccess.'?imgname='.$now.'-'.$_FILES[$fieldname]['name'].'');
138.
139. // make an error handler which will be used if the upload fails
140. function error($error, $location, $seconds = 5)
141. {
142. 	header("Refresh: $seconds; URL=\"$location\"");
143. 	echo '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"'."\n".
144. 	'"http://www.w3.org/TR/html4/strict.dtd">'."\n\n".
145. 	'<html lang="en">'."\n".
146. 	'	<head>'."\n".
147. 	'		<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">'."\n\n".
148. 	'		<link rel="stylesheet" type="text/css" href="css/stylesheet.css">'."\n\n".
149. 	'	<title>Upload error</title>'."\n\n".
150. 	'	</head>'."\n\n".
151. 	'	<body>'."\n\n".
152. 	'	<div id="Upload">'."\n\n".
153. 	'		<h1>Upload failure</h1>'."\n\n".
154. 	'		<p>An error has occured: '."\n\n".
155. 	'		<span class="red">' . $error . '...</span>'."\n\n".
156. 	'	 	The upload form is reloading</p>'."\n\n".
157. 	'	 </div>'."\n\n".
158. 	'</html>';
159. 	exit;
160. } // end error handler
161.
162. ?>

Next up, the top half of the success page result is shown in Figure 3.

Figure 3. Upload Success (upper)

Figure 3 - Upload Success (upper)

Figure 4 depicts the lower half of the success page result.

Figure 4. Upload Success (lower)

Figure 4 - Upload Success (lower)

Listing 3 shows the code for the success page, upload.success.php. Two important JavaScript functions are listed on lines 103 - 145 (CanvasSaver) and lines 149 - 184 (Create_BnW()). The Create_BnW() function converts the color image to a black and white version, particularly lines 160 - 169. The CanvasSaver function captures the data of the black and white image displayed in the HTML5 Canvas and places it in a form field, imgdata. When the "Save BW Image" button is clicked, the saveBWAction.php file is called.

Listing 3. upload.success.php

1. <?php
2.
3. // filename: upload.success.php
4. $imgname = $_GET['imgname'];
5. $size = getimagesize('uploaded_files/'.$imgname.'');
6. $width = $size[0];
7. $height = $size[1];
8. $imagetype = $size[2];
9. $imgext = "";
10. switch ($imagetype) {
11.    case 1:
12.        $imgext = "GIF";
13.        break;
14.    case 2:
15.        $imgext = "JPG";
16.        break;
17.    case 3:
18.        $imgext = "PNG";
19.        break;
20.    case 4:
21.        $imgext = "SWF";
22.        break;
23.    case 5:
24.        $imgext = "PSD";
25.        break;
26.    case 6:
27.        $imgext = "BMP";
28.        break;
29.    case 7:
30.        $imgext = "TIF";
31.        break;
32.    case 8:
33.        $imgext = "TIF";
34.        break;
35.    case 9:
36.        $imgext = "JPC";
37.        break;
38.    case 10:
39.        $imgext = "JP2";
40.        break;
41.    case 11:
42.        $imgext = "JPX";
43.        break;
44.    case 12:
45.        $imgext = "JB2";
46.        break;
47.    case 13:
48.        $imgext = "SWC";
49.        break;
50.    case 14:
51.        $imgext = "IFF";
52.        break;
53.    case 15:
54.        $imgext = "WBMP";
55.        break;
56.    case 16:
57.        $imgext = "XBM";
58.        break;
59.    case 17:
60.        $imgext = "ICO";
61.        break;
62.     }
63. ?>
64. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
65.
66. <html lang="en">
67.     <head>
68.         <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
69.         <link rel="stylesheet" type="text/css" href="css/stylesheet.css">
70.         <title>Successful upload</title>
71.         <style>
72.              body {
73.                 background: rgba(150, 205, 5, 0.3);
74.              }
75.              #canvas {
76.                 margin: 10px 20px 0px 20px;
77.                 border: thin solid Black;
78.                 cursor: crosshair;
79.              }
80.              #BlacknWhite {
81.                 width: 81px;
82.              }
83.         </style>
84.     </head>
85.
86.     <body>
87.
88.         <div id="Upload" align="center">
89.             <h1>File uploaded</h1>
90.             <p>Congratulations! Your file upload was successful</p>
91.             <img src="uploaded_files/<?php echo $imgname ?>" alt="<?php echo $imgext ?> image" width="<?php echo $width ?>" height="<?php echo $height ?>">
92.             <p><a href="upload.form.php" title="Upload another picture...">Upload Another</a></p>
93.             <p>
94.             <hr color="navy">
95.             <p>
96.             <h1>Convert to a Black and White Image</h1>
97.             <input id='BnWButton' type='button' value="Click Me" onclick="return BnWButton_onclick()" />
98.             <canvas id="canvas" width="<?php echo $width ?>" height="<?php echo $height ?>">
99.              Sorry, Canvas is not supported in this Browser..
100.             </canvas>
101.             <script type="text/javascript">
102.                 //JavaScript Code
103.                 var cs = new CanvasSaver('SaveBWAction.php')
104.                 cs.generateButton('Save BW Image', canvas, '<?php echo $imgname ?>');
105.                 function CanvasSaver(url) {
106.
107.                     this.url = url;
108.
109.                     this.savePNG = function(cnvs, fname) {
110.                         if(!cnvs || !url) return;
111.                         fname = fname || 'picture';
112.
113.                         var data = cnvs.toDataURL("image/png");
114.                         data = data.substr(data.indexOf(',') + 1).toString();
115.
116.                         var dataInput = document.createElement("input") ;
117.                         dataInput.setAttribute("name", 'imgdata') ;
118.                         dataInput.setAttribute("value", data);
119.
120.                         var nameInput = document.createElement("input") ;
121.                         nameInput.setAttribute("name", 'name') ;
122.                         nameInput.setAttribute("value", fname + '.png');
123.
124.                         var myForm = document.createElement("form");
125.                         myForm.method = 'post';
126.                         myForm.action = url;
127.                         myForm.appendChild(dataInput);
128.                         myForm.appendChild(nameInput);
129.
130.                         document.body.appendChild(myForm) ;
131.                         myForm.submit() ;
132.                         document.body.removeChild(myForm) ;
133.                     };
134.
135.                     this.generateButton = function (label, cnvs, fname) {
136.                         var btn = document.createElement('button'), scope = this;
137.                         btn.innerHTML = label;
138.                         btn.style['class'] = 'canvassaver';
139.                         btn.addEventListener('click', function(){scope.savePNG(cnvs, fname);}, false);
140.
141.                         document.body.children[0].appendChild(btn);
142.
143.                         return btn;
144.                     };
145.                 }
146.             </script>
147.             <script type="text/javascript">
148.              //JavaScript Code
149.              var canvas = document.getElementById('canvas');
150.              context = canvas.getContext('2d');
151.              image = new Image();
152.              BnWButton = document.getElementById('BnWButton');
153.              image.src = 'uploaded_files/<?php echo $imgname ?>';
154.              image.onload = function () {
155.                  context.clearRect(0, 0, canvas.width, canvas.height);
156.                  context.drawImage(image, 0, 0, image.width, image.height, 0, 0, context.canvas.width, context.canvas.height);
157.              };
158.              function Create_BnW() {
159.                  var data = undefined;
160.                  i = 0;
161.                  imagedata = context.getImageData(0, 0, canvas.width, canvas.height);
162.                  data = imagedata.data;
163.                  for (i = 0; i < data.length - 4; i += 4) {
164.                      average = (data[i] + data[i + 1] + data[i + 2]) / 3;
165.                      data[i] = average;
166.                      data[i + 1] = average;
167.                      data[i + 2] = average;
168.                  }
169.                  context.putImageData(imagedata, 0, 0);
170.              }
171.              function Create_Color() {
172.                  context.drawImage(image, 0, 0,image.width, image.height, 0, 0,context.canvas.width, context.canvas.height);
173.              }
174.              var a=0;
175.              function BnWButton_onclick() {
176.                  if (a == 0) {
177.                      Create_BnW();
178.                      a++;
179.                  }
180.                  else {
181.                      Create_Color();
182.                      a--;
183.                  }
184.              };
185.             </script>
186.             <p>
187.                 <object type="application/x-shockwave-flash" width="410" height="18" data="swfs/xspf_player_slim.swf?playlist_url=music.xml&autoplay=1&autoresume=1">
188.                     <param name="movie" value="swfs/xspf_player_slim.swf?playlist_url=music.xml&autoplay=1&autoresume=1" />
189.                 </object>
190.             </p>
191.         </div>
192.
193.     </body>
194.
195. </html>

Figure 5 shows the saveBWAction page result.

Figure 5. Saved Black & White Image

Figure 5 - Saved Black and White Image

Listing 4 contains several PHP functions utilized for this page - str_replace (line 2 and 4), base64_decode (line 5), file_put_contents (line 8). The str_replace function in line 2 appends _bw to the black and white version of the uploaded image. The base64_decode function in line 5 decodes the base64 encoded data posted from the HTML5 Canvas' form field, imgdata. The file_put_contents function used in line 8 writes the black and white decoded data to the file system. Lines 70 - 78 insert a row in the mySQL database table for the black and white version of the uploaded image.

Listing 4. saveBWAction.php

1. <?php
2. $imgname = str_replace('.jpg', '_bw', $_POST['name']);
3. $encoded = $_POST['imgdata'];
4. $encoded = str_replace(' ', '+', $encoded);
5. $decoded = base64_decode($encoded);
6. //var_dump($output);
7. //write the PNG B&W file
8. file_put_contents('uploaded_files/'.$imgname.'', $decoded);
9.
10. $size = filesize('uploaded_files/'.$imgname.'');
11. $imageurl = "http://".$_SERVER['HTTP_HOST']."/prototypes/uploader/uploaded_files/".basename($imgname)."";
12.
13. $imagetype = getimagesize('uploaded_files/'.$imgname.'');
14. $imgext = "";
15.
16. switch ($imagetype[2]) {
17.     case 1:
18.         $imgext = "GIF";
19.         break;
20.     case 2:
21.         $imgext = "JPG";
22.         break;
23.     case 3:
24.         $imgext = "PNG";
25.         break;
26.     case 4:
27.         $imgext = "SWF";
28.         break;
29.     case 5:
30.         $imgext = "PSD";
31.         break;
32.     case 6:
33.         $imgext = "BMP";
34.         break;
35.     case 7:
36.         $imgext = "TIF";
37.         break;
38.     case 8:
39.         $imgext = "TIF";
40.         break;
41.     case 9:
42.         $imgext = "JPC";
43.         break;
44.     case 10:
45.         $imgext = "JP2";
46.         break;
47.     case 11:
48.         $imgext = "JPX";
49.         break;
50.     case 12:
51.         $imgext = "JB2";
52.         break;
53.     case 13:
54.         $imgext = "SWC";
55.         break;
56.     case 14:
57.         $imgext = "IFF";
58.         break;
59.     case 15:
60.         $imgext = "WBMP";
61.         break;
62.     case 16:
63.         $imgext = "XBM";
64.         break;
65.     case 17:
66.         $imgext = "ICO";
67.         break;
68. }
69.
70. // connect to database and insert a record
71. $link = mysqli_connect("yourIP","yourUsername","yourPassword","yourDatabase");
72. $q = "insert into pictures (imagename, imageurl, filesize, filetype) values('$imgname', '$imageurl', $size, '$imgext')"; //some sql
73. //echo $q;
74. // run query 1
75. $result = mysqli_query($link, $q);
76.
77. // close connection
78. mysqli_close($link);
79.
80. ?>
81. <html>
82. <head>
83. <title>Saved the B&W Image</title>
84. </head>
85. <body>
86. <div align="center">
87. <h3>Black & White Version Saved Successfully</h3
88. <p><img src="uploaded_files/<?php echo $imgname ?>"></p>
89. <p><a href="upload.form.php" title="Upload another picture...">Upload Another</a></p>
90. </div>
91. </body>
92. </html>

Try out the online version here: Upload Form

Finally, here are some screenshots of the application running on an Android phone:

Upload Form on Android

Upload Success on Android

Convert To Black and White on Android

Saving the Black and White on Android

Screenshot of the KSWeb application on Google Play:
KSWeb Android Application

        Tip Jar:

 
Related Entries:
 

canada goose femme pas cher Soldes Louboutin Chaussures Soldes Louboutin louis vuitton taschen outlet louboutin outlet uk billig canada goose canada goose tilbud goyard pas cher longchamp bags outlet Monlcer udsalg billige parajumpers YSL replica sac louis vuitton pas cher Canada Goose Pas Cher Canada Goose Outlet UK Moncler Outlet uk goyard replica bags polo Lacoste pas cher Bolsos Longchamp España Moncler Jakker tilbud Doudoune moncler pas cher Parajumpers Jakker tilbud Ralph Lauren Soldes Parajumpers Outlet louis vuitton replica Moncler Jas sale Billiga Canada Goose Jacka Canada Goose outlet Billiga Moncler Doudoune Canada Goose Pas Cher Canada Goose Pas Cher Louboutin Soldes Canada Goose Pas Cher Hemers replica Doudoune Canada Goose Pas Cher prada replica Canada Goose Pas Cher Canada Goose Soldes Doudoune Canada Goose Pas Cher Canada Goose Pas Cher Canada Goose outlet Canada Goose outlet Canada Goose outlet