In this Tutorial I am going to explain you about How to build a simple web services or Rest api to upload file to server database using php, Mysql and json .

1. Create a Database Test :

At First create a Database name it as Test then create a table inside it and named it as file and having 3 columns in it .

As you know in our last tutorial we discussed you about How to create a Registration and Login  web services / Rest api using Php,Mysql and Json .

2. Now we configure or define the database attributes inside config.php file :

Config.php


// database configuration
<?php
//databse details
define('hostname','localhost');
define('user','root');
define('password','root');
define('db_name','Test');
?>

Here our database user name is root and password is also root and database name is Test.

3. Now we Create connection file to Connect  our Mysql database with php :

conn.php

// create connection with database

<?php
require_once 'Config.php';
class DB_Connection{
  private $connect;
  function __construct(){
    $this->connect=mysqli_connect(hostname,user,password,db_name) or die("DB Connection error.");
  }
  public function get_connection()
  {
    return $this->connect;
  }
}
 ?>

4. After this we are going create an another file named as upload.php :

Before that Inside your server’s root directory create a new folder named as upload where our files are save after uploading .

upload.php

<?php
// database details
include('conn.php');

class Upload
{
  private $db;
  private $connection;
	
  //Upload Url or address
//   $upload_url = SITE_URL . '/' . $upload_path; //
//   $upload_url = $server_ip . '/' . $upload_path;

  function __construct()
        {
            //constructor call    
            $this->db = new DB_Connection();
            $this->connection=$this->db->get_connection();
        }
   public function upload_file($file_url)
        {         
            $response = array();
            //set default time zone
            date_default_timezone_set("Asia/Calcutta");   
            //India time (GMT+5:30)
            // get date and time
             $uploaded_at = date('Y-m-d H:i:s');
	    try{
	        //saving the file 
    		$query = "INSERT INTO file (file,uploaded_at) VALUES('$file_url','$uploaded_at')";
            $is_uploaded = mysqli_query($this->connection,$query);
    		//adding the path and name to database 
    		if($is_uploaded){
    		    $query1 = "SELECT * FROM file WHERE file = '$file_url' ";
                        $result1=mysqli_query($this->connection,$query1);
                        if(mysqli_num_rows($result1)>0)
                	    {
    			//filling response array with values 
    		        $row= mysqli_fetch_array($result1);
    		        $data = array(
    		                    'file_id'=>$row['file_id'],
    		                    'file'=>$row['file'],
    		                    'uploaded_at'=>$row['uploaded_at']);
    	    	        $response['status'] = 200;
    		        $response['message'] = 'uploaded Successfully';
    		        $response['user'] = $data;
    		     }
                }
		    else{
                    $response['status'] = 400;
                    $response['message'] = 'Invalid Operation';
            }		

		 }
	     catch(Exception $e){
	 	  $response['status']=100;
		  $response['message']=$e->getMessage();
		 } 
            
        echo json_encode($response);
        mysqli_close($this->connection);
            
    }
}
    
    $load_file = new Upload();
    
    if(is_array($_FILES)) { 
        if(is_uploaded_file($_FILES['file']['tmp_name'])){
            $sourcePath = $_FILES['file']['tmp_name'];
            $targetPath = SITE_URL . '/' . "upload/".$_FILES['file']['name'];        
        if(move_uploaded_file($sourcePath,$targetPath)){
            $load_file-> upload_file($targetPath);
        }
        else{
            $response2 = array();
            $response2['status'] =401;
            $response2['message']='You must upload a valid file ';
            echo json_encode($response2);
        }
    }
}

?>

Now we can test it in Postman or in any other Rest client with the given keyname file .

%d bloggers like this: