Uploading of Photos using Advance PHP
Submitted by GeePee on Wednesday, April 15, 2015 - 22:59.
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.
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.
And here’s the database table structure used in this tutorial.
And you can follow this link Uploading files using PHP if you want to understand more how to upload file using PHP.
- <?php
- /**
- * Description: This is a class for Photos.
- * Author: Joken Villanueva
- * Date Created: october 26, 2013
- * Revised By:
- */
- require_once(LIB_PATH.DS.'database.php');
- class photos {
- protected static $tbl_name = "photos";
- public function attach_file($file) {
- // Perform error checking on the form parameters
- // error: nothing uploaded or wrong argument usage
- $this->errors[] = "No file was uploaded.";
- return false;
- } elseif($file['error'] != 0) {
- // error: report what PHP says went wrong
- $this->errors[] = $this->upload_errors[$file['error']];
- return false;
- } else {
- // Set object attributes to the form parameters.
- $this->temp_path = $file['tmp_name'];
- $this->type = $file['type'];
- $this->size = $file['size'];
- // Don't worry about saving anything to the database yet.
- return true;
- }
- }
- public function save() {
- // A new record won't have an id yet.
- // Really just to update the caption
- $this->update();
- } else {
- // Make sure there are no errors
- // Can't save if there are pre-existing errors
- // Make sure the caption is not too long for the DB
- $this->errors[] = "The caption can only be 255 characters long.";
- return false;
- }
- // Can't save without filename and temp location
- $this->errors[] = "The file location was not available.";
- return false;
- }
- // Determine the target_path
- $target_path = SITE_ROOT .DS. 'uploads' .DS. $this->upload_dir .DS. $this->filename;
- // Make sure a file doesn't already exist in the target location
- $this->errors[] = "The file {$this->filename} already exists.";
- return false;
- }
- // Attempt to move the file
- // Success
- // Save a corresponding entry to the database
- if($this->create()) {
- // We are done with temp_path, the file isn't there anymore
- return true;
- }
- } else {
- // File was not moved.
- $this->errors[] = "The file upload failed, possibly due to incorrect permissions on the upload folder.";
- return false;
- }
- }
- }
- public function image_path() {
- return $this->upload_dir.DS.$this->filename;
- }
- public function size_as_text($size) {
- if($size < 1024) {
- return "{$size} bytes";
- } elseif($size < 1048576) {
- return "{$size_kb} KB";
- } else {
- return "{$size_mb} MB";
- }
- }
- // Common Database Methods
- public static function find_all() {
- return self::find_by_sql("SELECT * FROM ".self::$table_name);
- }
- function db_fields(){
- global $mydb;
- return $mydb->getFieldsOnOneTable(self::$tbl_name);
- }
- /*---Instantiation of Object dynamically---*/
- static function instantiate($record) {
- $object = new self;
- foreach($record as $attribute=>$value){
- if($object->has_attribute($attribute)) {
- $object->$attribute = $value;
- }
- }
- return $object;
- }
- /*--Cleaning the raw data before submitting to Database--*/
- private function has_attribute($attribute) {
- // We don't care about the value, we just want to know if the key exists
- // Will return true or false
- }
- protected function attributes() {
- // return an array of attribute names and their values
- global $mydb;
- foreach($this->db_fields() as $field) {
- if(property_exists($this, $field)) {
- $attributes[$field] = $this->$field;
- }
- }
- return $attributes;
- }
- protected function sanitized_attributes() {
- global $mydb;
- // sanitize the values before submitting
- // Note: does not alter the actual value of each attribute
- foreach($this->attributes() as $key => $value){
- $clean_attributes[$key] = $mydb->escape_value($value);
- }
- return $clean_attributes;
- }
- /*--Create,Update and Delete methods--*/
- public function create() {
- global $mydb;
- // Don't forget your SQL syntax and good habits:
- // - INSERT INTO table (key, key) VALUES ('value', 'value')
- // - single-quotes around all values
- // - escape all values to prevent SQL injection
- $attributes = $this->sanitized_attributes();
- $sql = "INSERT INTO ".self::$tbl_name." (";
- $sql .= ") VALUES ('";
- $sql .= "')";
- echo $mydb->setQuery($sql);
- if($mydb->executeQuery()) {
- $this->id = $mydb->insert_id();
- return true;
- } else {
- return false;
- }
- }
- public function update($id=0) {
- global $mydb;
- $attributes = $this->sanitized_attributes();
- foreach($attributes as $key => $value) {
- $attribute_pairs[] = "{$key}='{$value}'";
- }
- $sql = "UPDATE ".self::$tbl_name." SET ";
- $sql .= " WHERE b_id=". $id;
- $mydb->setQuery($sql);
- if(!$mydb->executeQuery()) return false;
- }
- public function delete($id=0) {
- global $mydb;
- $sql = "DELETE FROM ".self::$tbl_name;
- $sql .= " WHERE b_id=". $id;
- $sql .= " LIMIT 1 ";
- $mydb->setQuery($sql);
- if(!$mydb->executeQuery()) return false;
- }
- }
- ?>
- <?php
- require_once("includes/initialize.php");
- $message = "";
- $photo = new photos();
- $photo->caption = $_POST['caption'];
- $photo->attach_file($_FILES['uploadphoto']);
- if($photo->save()){
- $message= "The file has successfully saved!";
- }else{
- }
- }
- ?>
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta name="description" content="">
- <meta name="author" content="">
- <link rel="shortcut icon" href="#">
- <title>Philsocial</title>
- <!-- Bootstrap core CSS -->
- <link href="css/bootstrap.css" rel="stylesheet">
- <!-- Custom styles for this template -->
- <link href="jumbotron.css" rel="stylesheet">
- <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
- <!--[if lt IE 9]>
- <script src="../../assets/js/html5shiv.js"></script>
- <script src="../../assets/js/respond.min.js"></script>
- <![endif]-->
- </head>
- <body>
- <div class="navbar navbar-inverse navbar-fixed-top">
- <div class="container">
- <div class="navbar-header">
- <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- </button>
- <a class="navbar-brand" href="#"> <h2>Philsocial</h2></a>
- </div>
- <div class="navbar-collapse collapse">
- <form class="navbar-form navbar-right">
- <div class="form-group">
- <input type="text" placeholder="Email" class="form-control">
- </div>
- <div class="form-group">
- <input type="password" placeholder="Password" class="form-control">
- </div>
- <button type="submit" class="btn btn-success">Sign in</button>
- </form>
- </div><!--/.navbar-collapse -->
- </div>
- </div>
- <!-- Main jumbotron for a primary marketing message or call to action -->
- <div class="jumbotron">
- <div class="container">
- <div class="rows">
- <div class="col-xs-6">
- <h3>Philsocial helps you connected and share with
- the other people in your life</h3>
- </div>
- <div class="col-xs-6">
- <form action="upload_photos.php" enctype="multipart/form-data" class="form-horizontal well" method="post">
- <fieldset>
- <!---This will display some messages about the status of the uploaded photo
- and it is either successfully uploaded or not--->
- <?php echo output_message($message);?>
- <legend>Upload Photo</legend>
- <div class="form-group">
- <div class="rows">
- <div class="col-md-12">
- <div class="rows">
- <div class="col-md-8">
- <input type="hidden" name="MAX_FILE_SIZE" value="1000000">
- <input type="file" id="uploadphoto" name="uploadphoto">
- </div>
- <div class="col-md-4">
- </div>
- </div>
- </div>
- </div>
- </div>
- <div class="form-group">
- <div class="rows">
- <div class="col-md-12">
- <div class="rows">
- <div class="col-md-8">
- <p>Caption<input type="text" name="caption" class="form-control input-lg"></p>
- </div>
- </div>
- </div>
- </div>
- </div>
- <div class="form-group">
- <div class="rows">
- <div class="col-md-12">
- <div class="rows">
- <div class="col-md-2">
- <input type="submit" name="submit" class="btn btn-success btn-lg" value="Upload">
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </fieldset>
- </form>
- </div>
- </div><!--rows-->
- </div><!--container-->
- </div><!--jumbotron-->
- <hr>
- <footer>
- <p align="center">© Philsocial 2013</p>
- </footer>
- </div> <!-- /container -->
- <!-- Bootstrap core JavaScript
- ================================================== -->
- <!-- Placed at the end of the document so the pages load faster -->
- <script src="assets/js/jquery.js"></script>
- <script src="js/bootstrap.min.js"></script>
- </body>
- </html>
- CREATE TABLE IF NOT EXISTS `photos` (
- `id` INT(11) NOT NULL AUTO_INCREMENT,
- `filename` VARCHAR(255) NOT NULL,
- `type` VARCHAR(100) NOT NULL,
- `size` INT(11) NOT NULL,
- `caption` VARCHAR(255) NOT NULL,
- `member_id` INT(11) NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=27 ;
Add new comment
- 239 views