Uploading of Photos using Advance PHP

In this tutorial I’m going to show you how to upload photo using PHP/MySQL, and this tutorial is a continuation of our previous topic called Social Networking Site: Simple Uploading of Profile picture in the home page. But in this time we’re not going to use the “home.php” file instead, we’re going to create a new page named “upload_photos.php”. To start in this lesson, first we will create a new PHP file called “photos.php” and save it inside includes folder. Then add the following code: What we’re doing here in this class is that, we are creating a class for handle the saving, updating, deleting and error messages for photos.
  1. <?php
  2. /**
  3. * Description: This is a class for Photos.
  4. * Author: Joken Villanueva
  5. * Date Created: october 26, 2013
  6. * Revised By:
  7. */
  8. require_once(LIB_PATH.DS.'database.php');
  9. class photos {
  10.  
  11. protected static $tbl_name = "photos";
  12.  
  13.  
  14. public function attach_file($file) {
  15. // Perform error checking on the form parameters
  16. if(!$file || empty($file) || !is_array($file)) {
  17. // error: nothing uploaded or wrong argument usage
  18. $this->errors[] = "No file was uploaded.";
  19. return false;
  20. } elseif($file['error'] != 0) {
  21. // error: report what PHP says went wrong
  22. $this->errors[] = $this->upload_errors[$file['error']];
  23. return false;
  24. } else {
  25. // Set object attributes to the form parameters.
  26. $this->temp_path = $file['tmp_name'];
  27. $this->filename = basename($file['name']);
  28. $this->type = $file['type'];
  29. $this->size = $file['size'];
  30. // Don't worry about saving anything to the database yet.
  31. return true;
  32.  
  33. }
  34. }
  35. public function save() {
  36. // A new record won't have an id yet.
  37. if(isset($this->id)) {
  38. // Really just to update the caption
  39. $this->update();
  40. } else {
  41. // Make sure there are no errors
  42.  
  43. // Can't save if there are pre-existing errors
  44. if(!empty($this->errors)) { return false; }
  45.  
  46. // Make sure the caption is not too long for the DB
  47. if(strlen($this->caption) > 255) {
  48. $this->errors[] = "The caption can only be 255 characters long.";
  49. return false;
  50. }
  51.  
  52. // Can't save without filename and temp location
  53. if(empty($this->filename) || empty($this->temp_path)) {
  54. $this->errors[] = "The file location was not available.";
  55. return false;
  56. }
  57.  
  58. // Determine the target_path
  59. $target_path = SITE_ROOT .DS. 'uploads' .DS. $this->upload_dir .DS. $this->filename;
  60.  
  61. // Make sure a file doesn't already exist in the target location
  62. if(file_exists($target_path)) {
  63. $this->errors[] = "The file {$this->filename} already exists.";
  64. return false;
  65. }
  66.  
  67. // Attempt to move the file
  68. if(move_uploaded_file($this->temp_path, $target_path)) {
  69. // Success
  70. // Save a corresponding entry to the database
  71. if($this->create()) {
  72. // We are done with temp_path, the file isn't there anymore
  73. unset($this->temp_path);
  74. return true;
  75. }
  76. } else {
  77. // File was not moved.
  78. $this->errors[] = "The file upload failed, possibly due to incorrect permissions on the upload folder.";
  79. return false;
  80. }
  81. }
  82. }
  83.  
  84. public function image_path() {
  85. return $this->upload_dir.DS.$this->filename;
  86. }
  87.  
  88. public function size_as_text($size) {
  89. if($size < 1024) {
  90. return "{$size} bytes";
  91. } elseif($size < 1048576) {
  92. $size_kb = round($size/1024);
  93. return "{$size_kb} KB";
  94. } else {
  95. $size_mb = round($size/1048576, 1);
  96. return "{$size_mb} MB";
  97. }
  98. }
  99.  
  100.  
  101. // Common Database Methods
  102. public static function find_all() {
  103. return self::find_by_sql("SELECT * FROM ".self::$table_name);
  104. }
  105.  
  106. function db_fields(){
  107. global $mydb;
  108. return $mydb->getFieldsOnOneTable(self::$tbl_name);
  109. }
  110.  
  111.  
  112. /*---Instantiation of Object dynamically---*/
  113. static function instantiate($record) {
  114. $object = new self;
  115.  
  116. foreach($record as $attribute=>$value){
  117. if($object->has_attribute($attribute)) {
  118. $object->$attribute = $value;
  119. }
  120. }
  121. return $object;
  122. }
  123.  
  124. /*--Cleaning the raw data before submitting to Database--*/
  125. private function has_attribute($attribute) {
  126. // We don't care about the value, we just want to know if the key exists
  127. // Will return true or false
  128. return array_key_exists($attribute, $this->attributes());
  129. }
  130.  
  131. protected function attributes() {
  132. // return an array of attribute names and their values
  133. global $mydb;
  134. $attributes = array();
  135. foreach($this->db_fields() as $field) {
  136. if(property_exists($this, $field)) {
  137. $attributes[$field] = $this->$field;
  138. }
  139. }
  140. return $attributes;
  141. }
  142.  
  143. protected function sanitized_attributes() {
  144. global $mydb;
  145. $clean_attributes = array();
  146. // sanitize the values before submitting
  147. // Note: does not alter the actual value of each attribute
  148. foreach($this->attributes() as $key => $value){
  149. $clean_attributes[$key] = $mydb->escape_value($value);
  150. }
  151. return $clean_attributes;
  152. }
  153.  
  154.  
  155. /*--Create,Update and Delete methods--*/
  156.  
  157.  
  158. public function create() {
  159. global $mydb;
  160. // Don't forget your SQL syntax and good habits:
  161. // - INSERT INTO table (key, key) VALUES ('value', 'value')
  162. // - single-quotes around all values
  163. // - escape all values to prevent SQL injection
  164. $attributes = $this->sanitized_attributes();
  165. $sql = "INSERT INTO ".self::$tbl_name." (";
  166. $sql .= join(", ", array_keys($attributes));
  167. $sql .= ") VALUES ('";
  168. $sql .= join("', '", array_values($attributes));
  169. $sql .= "')";
  170. echo $mydb->setQuery($sql);
  171.  
  172. if($mydb->executeQuery()) {
  173. $this->id = $mydb->insert_id();
  174. return true;
  175. } else {
  176. return false;
  177. }
  178. }
  179.  
  180. public function update($id=0) {
  181. global $mydb;
  182. $attributes = $this->sanitized_attributes();
  183. $attribute_pairs = array();
  184. foreach($attributes as $key => $value) {
  185. $attribute_pairs[] = "{$key}='{$value}'";
  186. }
  187. $sql = "UPDATE ".self::$tbl_name." SET ";
  188. $sql .= join(", ", $attribute_pairs);
  189. $sql .= " WHERE b_id=". $id;
  190. $mydb->setQuery($sql);
  191. if(!$mydb->executeQuery()) return false;
  192.  
  193. }
  194.  
  195. public function delete($id=0) {
  196. global $mydb;
  197. $sql = "DELETE FROM ".self::$tbl_name;
  198. $sql .= " WHERE b_id=". $id;
  199. $sql .= " LIMIT 1 ";
  200. $mydb->setQuery($sql);
  201.  
  202. if(!$mydb->executeQuery()) return false;
  203.  
  204. }
  205.  
  206.  
  207. }
  208.  
  209. ?>
Next, since we have already set up our class photo. We now going to create the “upload_photos.php”. And add the following code. The code below is almost the same with our “index.php” file. And it will handle the form for uploading and saving the data of a photo into a database. and this upload_photos.php will be submitted to itself.
  1. <?php
  2. require_once("includes/initialize.php");
  3.  
  4. $message = "";
  5. if(isset($_POST['submit'])){
  6. $photo = new photos();
  7. $photo->caption = $_POST['caption'];
  8. $photo->attach_file($_FILES['uploadphoto']);
  9.  
  10. if($photo->save()){
  11. $message= "The file has successfully saved!";
  12. }else{
  13. $message = join("<br/>", $photo->errors);
  14. }
  15. }
  16. ?>
  17.  
  18. <!DOCTYPE html>
  19. <html lang="en">
  20. <head>
  21. <meta charset="utf-8">
  22. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  23. <meta name="description" content="">
  24. <meta name="author" content="">
  25. <link rel="shortcut icon" href="#">
  26.  
  27. <title>Philsocial</title>
  28.  
  29. <!-- Bootstrap core CSS -->
  30. <link href="css/bootstrap.css" rel="stylesheet">
  31.  
  32. <!-- Custom styles for this template -->
  33. <link href="jumbotron.css" rel="stylesheet">
  34.  
  35. <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
  36. <!--[if lt IE 9]>
  37. <script src="../../assets/js/html5shiv.js"></script>
  38. <script src="../../assets/js/respond.min.js"></script>
  39. <![endif]-->
  40. </head>
  41.  
  42. <body>
  43.  
  44. <div class="navbar navbar-inverse navbar-fixed-top">
  45. <div class="container">
  46. <div class="navbar-header">
  47. <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
  48. <span class="icon-bar"></span>
  49. <span class="icon-bar"></span>
  50. <span class="icon-bar"></span>
  51. </button>
  52. <a class="navbar-brand" href="#"> <h2>Philsocial</h2></a>
  53. </div>
  54.  
  55. <div class="navbar-collapse collapse">
  56.  
  57. <form class="navbar-form navbar-right">
  58. <div class="form-group">
  59. <input type="text" placeholder="Email" class="form-control">
  60. </div>
  61. <div class="form-group">
  62. <input type="password" placeholder="Password" class="form-control">
  63. </div>
  64. <button type="submit" class="btn btn-success">Sign in</button>
  65. </form>
  66. </div><!--/.navbar-collapse -->
  67. </div>
  68. </div>
  69.  
  70. <!-- Main jumbotron for a primary marketing message or call to action -->
  71. <div class="jumbotron">
  72. <div class="container">
  73.  
  74. <div class="rows">
  75.  
  76. <div class="col-xs-6">
  77. <h3>Philsocial helps you connected and share with
  78. the other people in your life</h3>
  79.  
  80. </div>
  81. <div class="col-xs-6">
  82.  
  83.  
  84. <form action="upload_photos.php" enctype="multipart/form-data" class="form-horizontal well" method="post">
  85. <fieldset>
  86. <!---This will display some messages about the status of the uploaded photo
  87. and it is either successfully uploaded or not--->
  88. <?php echo output_message($message);?>
  89.  
  90. <legend>Upload Photo</legend>
  91.  
  92. <div class="form-group">
  93. <div class="rows">
  94. <div class="col-md-12">
  95. <div class="rows">
  96. <div class="col-md-8">
  97. <input type="hidden" name="MAX_FILE_SIZE" value="1000000">
  98. <input type="file" id="uploadphoto" name="uploadphoto">
  99. </div>
  100. <div class="col-md-4">
  101.  
  102.  
  103. </div>
  104. </div>
  105. </div>
  106. </div>
  107. </div>
  108. <div class="form-group">
  109. <div class="rows">
  110. <div class="col-md-12">
  111. <div class="rows">
  112. <div class="col-md-8">
  113. <p>Caption<input type="text" name="caption" class="form-control input-lg"></p>
  114. </div>
  115. </div>
  116. </div>
  117. </div>
  118. </div>
  119.  
  120. <div class="form-group">
  121. <div class="rows">
  122. <div class="col-md-12">
  123. <div class="rows">
  124. <div class="col-md-2">
  125.  
  126.  
  127. <input type="submit" name="submit" class="btn btn-success btn-lg" value="Upload">
  128. </div>
  129. </div>
  130. </div>
  131. </div>
  132. </div>
  133.  
  134.  
  135. </div>
  136.  
  137. </div>
  138. </fieldset>
  139. </form>
  140. </div>
  141. </div><!--rows-->
  142.  
  143.  
  144. </div><!--container-->
  145. </div><!--jumbotron-->
  146.  
  147.  
  148. <hr>
  149.  
  150. <footer>
  151. <p align="center">&copy; Philsocial 2013</p>
  152. </footer>
  153. </div> <!-- /container -->
  154.  
  155.  
  156. <!-- Bootstrap core JavaScript
  157. ================================================== -->
  158. <!-- Placed at the end of the document so the pages load faster -->
  159. <script src="assets/js/jquery.js"></script>
  160. <script src="js/bootstrap.min.js"></script>
  161. </body>
  162. </html>
And here’s the database table structure used in this tutorial.
  1. CREATE TABLE IF NOT EXISTS `photos` (
  2. `id` INT(11) NOT NULL AUTO_INCREMENT,
  3. `filename` VARCHAR(255) NOT NULL,
  4. `type` VARCHAR(100) NOT NULL,
  5. `size` INT(11) NOT NULL,
  6. `caption` VARCHAR(255) NOT NULL,
  7. `member_id` INT(11) NOT NULL,
  8. PRIMARY KEY (`id`)
  9. ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=27 ;
And you can follow this link Uploading files using PHP if you want to understand more how to upload file using PHP.

Add new comment