Showing posts with label PHP File upload. Show all posts
Showing posts with label PHP File upload. Show all posts

Friday, 26 June 2015

PHP: File Upload and View With PHP and MySQL

First of all here i'll show you that how you can upload files using simple html form that sends file to the database through PHP script.

In this tutorial i am going to store file name, file type, and file size.
import the following sql code in your phpmyadmin. Database crediantials.
CREATE DATABASE `dbtuts` ;
CREATE TABLE `dbtuts`.`tbl_uploads` (
`id` INT( 10 ) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`file` VARCHAR( 100 ) NOT NULL ,
`type` VARCHAR( 10 ) NOT NULL ,
`size` INT NOT NULL
) ENGINE = MYISAM ;

Database configuration.
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "dbtuts";
mysql_connect($dbhost,$dbuser,$dbpass) or die('cannot connect to the server'); 
mysql_select_db($dbname) or die('database selection problem');

The HTML Form.

index.php
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Upload and view With PHP and MySql</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit" name="btn-upload">upload</button>
</form>
</body>
</html>

above html form sends the data to the following PHP script and joining this html and php script you can easily upload files to the database .
upload.php
<?php
if(isset($_POST['btn-upload']))
{    
     
 $file = rand(1000,100000)."-".$_FILES['file']['name'];
    $file_loc = $_FILES['file']['tmp_name'];
 $file_size = $_FILES['file']['size'];
 $file_type = $_FILES['file']['type'];
 $folder="uploads/";
 
 move_uploaded_file($file_loc,$folder.$file);
 $sql="INSERT INTO tbl_uploads(file,type,size) VALUES('$file','$file_type','$file_size')";
 mysql_query($sql); 
}
?>

Display files from MySql.

Now we are going to fetch uploaded files from MySql Database, data selecting from mysql database i hope you know that...
view.php
<table width="80%" border="1">
    <tr>
    <td>File Name</td>
    <td>File Type</td>
    <td>File Size(KB)</td>
    <td>View</td>
    </tr>
    <?php
 $sql="SELECT * FROM tbl_uploads";
 $result_set=mysql_query($sql);
 while($row=mysql_fetch_array($result_set))
 {
  ?>
        <tr>
        <td><?php echo $row['file'] ?></td>
        <td><?php echo $row['type'] ?></td>
        <td><?php echo $row['size'] ?></td>
        <td><a href="uploads/<?php echo $row['file'] ?>" target="_blank">view file</a></td>
        </tr>
        <?php
 }
 ?>
</table>

that's it
Complete script.
dbconfig.php
?<php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "dbtuts";
mysql_connect($dbhost,$dbuser,$dbpass) or die('cannot connect to the server'); 
mysql_select_db($dbname) or die('database selection problem');
?>

index.php
First file with Html form which select the file from client to be upload.
<?php
include_once 'dbconfig.php';
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Uploading With PHP and MySql</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="header">
<label>File Uploading With PHP and MySql</label>
</div>
<div id="body">
 <form action="upload.php" method="post" enctype="multipart/form-data">
 <input type="file" name="file" />
 <button type="submit" name="btn-upload">upload</button>
 </form>
    <br /><br />
    <?php
 if(isset($_GET['success']))
 {
  ?>
        <label>File Uploaded Successfully...  <a href="view.php">click here to view file.</a></label>
        <?php
 }
 else if(isset($_GET['fail']))
 {
  ?>
        <label>Problem While File Uploading !</label>
        <?php
 }
 else
 {
  ?>
        <label>Try to upload any files(PDF, DOC, EXE, VIDEO, MP3, ZIP,etc...)</label>
        <?php
 }
 ?>
</div>
<div id="footer">
<label>By <a href="http://cleartuts.blogspot.com">cleartuts.blogspot.com</a></label>
</div>
</body>
</html>

upload.php this is the main PHP Script of this tutorial which uploads the file to the server.
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-upload']))
{    
     
 $file = rand(1000,100000)."-".$_FILES['file']['name'];
    $file_loc = $_FILES['file']['tmp_name'];
 $file_size = $_FILES['file']['size'];
 $file_type = $_FILES['file']['type'];
 $folder="uploads/";
 
 // new file size in KB
 $new_size = $file_size/1024;  
 // new file size in KB
 
 // make file name in lower case
 $new_file_name = strtolower($file);
 // make file name in lower case
 
 $final_file=str_replace(' ','-',$new_file_name);
 
 if(move_uploaded_file($file_loc,$folder.$final_file))
 {
  $sql="INSERT INTO tbl_uploads(file,type,size) VALUES('$final_file','$file_type','$new_size')";
  mysql_query($sql);
  ?>
  <script>
  alert('successfully uploaded');
        window.location.href='index.php?success';
        </script>
  <?php
 }
 else
 {
  ?>
  <script>
  alert('error while uploading file');
        window.location.href='index.php?fail';
        </script>
  <?php
 }
}
?>

view.php
this file shows the uploaded file from the database.
<?php
include_once 'dbconfig.php';
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>File Uploading With PHP and MySql</title>
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<div id="header">
<label>File Uploading With PHP and MySql</label>
</div>
<div id="body">
 <table width="80%" border="1">
    <tr>
    <th colspan="4">your uploads...<label><a href="index.php">upload new files...</a></label></th>
    </tr>
    <tr>
    <td>File Name</td>
    <td>File Type</td>
    <td>File Size(KB)</td>
    <td>View</td>
    </tr>
    <?php
 $sql="SELECT * FROM tbl_uploads";
 $result_set=mysql_query($sql);
 while($row=mysql_fetch_array($result_set))
 {
  ?>
        <tr>
        <td><?php echo $row['file'] ?></td>
        <td><?php echo $row['type'] ?></td>
        <td><?php echo $row['size'] ?></td>
        <td><a href="uploads/<?php echo $row['file'] ?>" target="_blank">view file</a></td>
        </tr>
        <?php
 }
 ?>
    </table>
    
</div>
</body>
</html>

style.css
and last but not the least stylesheet that makes beautify all the pages.
@charset "utf-8";
/* CSS Document */

*
{
 padding:0;
 margin:0;
}
body
{
 background:#fff;
 font-family:Georgia, "Times New Roman", Times, serif;
 text-align:center;
}
#header
{
 background:#00a2d1;
 width:100%;
 height:50px;
 color:#fff;
 font-size:36px;
 font-family:Verdana, Geneva, sans-serif;
}
#body
{
 margin-top:100px;
}
#body table
{
 margin:0 auto;
 position:relative;
 bottom:50px;
}
table td,th
{
 padding:20px;
 border: solid #9fa8b0 1px;
 border-collapse:collapse;
}
#footer
{
 text-align:center;
 position:absolute;
 left:0;
 right:0;
 margin:0 auto;
 bottom:50px;
}

PHP : Upload Class - Simple and Flexible Script

This is a very userful php upload script in the form of flexible, simple and powerful PHP upload class. This class is meant to validate and manage files uploaded via Web forms.

It is the ideal class to quickly integrate file upload and manipulation in your site. This script will allow you to upload files from your browser to your hosting, using PHP.

Features

    Uploads any image / file
    File name extension validation to accept only files with a given list of extensions
    Check whether the files exceeds the given size limit
    Safely renames the file – removes spaces, special characters etc
    Options to overwrite or make unique
    File extension validation
    Flexible error reporting system
    Check if a directory and/or file exist
    Chip PHP upload class allows you to select and upload multiple files at once rather than having to select and upload each file individually.

Requirements

    PHP5 or higher

Learning and handling of PHP upload class by TutorialChip is very easy and flexible. I have also given a complete demo and usage in the download archive for your understanding, and i am going to explain the installation of this class step by step online as well.
Client Side Tutorial: File Upload HTML Form

It is the very important step to prepare the form for uploading files.

    First important thing is to set "enctype" attribute in the form tag. i.e enctype="multipart/form-data"
    PHP Upload Class is very powerful as it can handle "Single/Multiple" uploads easily, So you have to define the file input as an array i.e upload_file[]. You can view in the given code snippet.

File Upload Form: Single File Example

   
<form method="post" action="" enctype="multipart/form-data">
<p>Upload File: <input name="upload_file[]" id="upload_file[]" type="file" class="inputtext" /></p>
<input type="submit" name="submit" value="Upload File" />
</form>
File Upload Form: Multiple File Example

   
<form method="post" action="" enctype="multipart/form-data">
<p>Upload File 1: <input name="upload_file[]" id="upload_file[]" type="file" class="inputtext" /></p>
<p>Upload File 2: <input name="upload_file[]" id="upload_file[]" type="file" class="inputtext" /></p>
<p>Upload File 3: <input name="upload_file[]" id="upload_file[]" type="file" class="inputtext" /></p>
<p>Upload File 4: <input name="upload_file[]" id="upload_file[]" type="file" class="inputtext" /></p>
<p>Upload File 5: <input name="upload_file[]" id="upload_file[]" type="file" class="inputtext" /></p>
<input type="submit" name="submit" value="Upload File" />
</form>
Server Side Tutorial

As we have already prepared our form to send data to the PHP server to upload files. Now it is time to learn PHP upload class handling to complete this process smoothly.Auto Detection of Script Directory

PHP Upload Class script will try to detect the her directory path automatically by built-in Magic Constant of PHP i.e __DIR__. However you can alter it according to your need.

   
/*
|-----------------
| Chip Constant Manipulation
|------------------
*/

define( "CHIP_DEMO_FSROOT",     __DIR__ . "/" );
Include "class.chip_upload.php"

You have to include PHP upload file in your file at the suitable position you think. I will recommend to include this class in your POST block. Don’t worry about POST block, you can easily understand it as the tutorial moves and from a descriptive demo in the download archive.

   
/*
|-----------------
| Chip Upload Class
|------------------
*/

require_once("class.chip_upload.php");
Upload Directory Path

Next step is to define upload directory path. This is the directory where you want to save your uploaded files. I have defined it "uploads", which is a directory in the download archive. Make sure that this directory should be writable.

   
/*
|-----------------
| Upload(s) Directory
|------------------
*/

$upload_directory = CHIP_DEMO_FSROOT . "uploads/";
Class Instance

It is time to make instance of PHP upload class now.
   
/*
|-----------------
| Class Instance
|------------------
*/

$object = new chip_upload();
$_FILES Manipulation

Our form will send files in the "upload_file" array which is packed in $_FILES. Our class is very powerful to handle Single and Multiple files efficiently, so we will pass this array to the "get_upload_var" method which will arrange this array for next processing professionally.
   
/*
|-----------------
| $_FILES Manipulation
|------------------
*/

$files = $object->get_upload_var( $_FILES['upload_file'] );
Powerful Upload Loop

Now we will start loop to upload files one by one. Let’s dissect this loop part by part. We are going to provide "$files" array to this loop.

   
/*
|-----------------
| Upload File
|------------------
*/

foreach( $files as $file ) {
Powerful Upload Loop

It is time to prepare inputs for class operation. Chip Upload class will take two parameters,
Array: $args

    upload_file (Array): It will hold uploaded file array. You have to simply pass $file to this array as we are dissecting foreach loop on $file variable.
    upload_directory (String – Correct Absolute Path): You have to provide a correct absolute path to this variable. We have already calculated this variable as $upload_directory
    allowed_size (Integer – In Bytes): You have to provide maximum upload size to this part. You have to given size in bytes. 1Kb = 1024 bytes
    extension_check (Boolean – TRUE | FALSE): This part will allow you to control over specific files to upload.
    upload_overwrite (Boolean – TRUE | FALSE): This part will allow you to control for over-writing existing file or not. If set False, PHP upload class will automatically determine new name that will be based on your assigned name or uploaded file name.

Array: $allowed_extensions

If you have set "extension_check" TRUE, in the $args array, than you can modify default list to allow or disallow in the following format.

   
/*
|---------------------------
| Upload Inputs
|---------------------------
*/

$args = array(
  'upload_file'     =>   $file,
  'upload_directory'    =>   $upload_directory,
  'allowed_size'        =>   512000,
  'extension_check' =>   TRUE,
  'upload_overwrite'    =>   FALSE,
 );

$allowed_extensions = array(
  'pdf' => FALSE,
);
Upload Hook

Upload Hook is very powerful feature of Chip PHP upload class. This hook will provide you a detail analysis of uploaded data after processing but before moving file to the directory, So you have a flexibility to do anything before processing the file to the upload directory. A sample code and output of this hook will be like,

   
/*
|---------------------------
| Upload Hook
|---------------------------
*/

$upload_hook = $object->get_upload( $args, $allowed_extensions );

Array
(
    [upload_directory] => Valid - E:\wamp\www\tutorialchip\chip_upload/uploads/
    [upload_directory_writable] => Valid - Directory is writable
    [upload_file_extension] => Valid - Extension is allowed
    [upload_file_size] => Valid - Size 97854 bytes
    [upload_process] => 4
    [upload_move] => 1
    [upload_overwrite] =>
    [upload_file] => Array
        (
            [name] => nature.jpg
            [type] => image/jpeg
            [tmp_name] => E:\wamp\tmp\phpAA65.tmp
            <div class="error"><div class="box-content">Content</div><div class="clear"></div></div> => 0
            [error_status] => All OK
            [size] => 97854
            [directory] => E:\wamp\www\passive\tutorialchip\library\chip_upload/uploads/
            [nameonly] => nature
            [extension] => jpg
        )
)
Move File

You have take your time and decision by using the power of "$upload_hook" with class built-in method "get_upload". You can track any error by getting print of $upload_hook. Now it is time to move the file to the destination directory.

   
/*
|---------------------------
| Move File
|---------------------------
*/

if( $upload_hook['upload_move'] == TRUE ) {

/*
|---------------------------
| Any Logic by User
|---------------------------
*/

/*
|---------------------------
| Move File
|---------------------------
*/

$upload_output[] = $object->get_upload_move();

} else {

/*
|---------------------------
| Any Logic by User
|---------------------------
*/

}
Complete Tutorial – PHP File Upload Class / Script Example

   
/*
|-----------------
| Chip Constant Manipulation
|------------------
*/

define( "CHIP_DEMO_FSROOT",     __DIR__ . "/" );

/*
|-----------------
| POST
|------------------
*/

if( $_POST ) {

    /*
    |-----------------
    | Chip Upload Class
    |------------------
    */

    require_once("class.chip_upload.php");

    /*
    |-----------------
    | Upload(s) Directory
    |------------------
    */

    $upload_directory = CHIP_DEMO_FSROOT . "uploads/";

    /*
    |-----------------
    | Class Instance
    |------------------
    */

    $object = new chip_upload();

    /*
    |-----------------
    | $_FILES Manipulation
    |------------------
    */

    $files = $object->get_upload_var( $_FILES['upload_file'] );

    /*
    |-----------------
    | Upload File
    |------------------
    */

    foreach( $files as $file ) {

        /*
        |---------------------------
        | Upload Inputs
        |---------------------------
        */

        $args = array(
              'upload_file'         =>   $file,
              'upload_directory'    =>   $upload_directory,
              'allowed_size'        =>   512000,
              'extension_check'     =>   TRUE,
              'upload_overwrite'    =>   FALSE,
          );

        $allowed_extensions = array(
            'pdf'   => FALSE,
        );

        /*
        |---------------------------
        | Upload Hook
        |---------------------------
        */

        $upload_hook = $object->get_upload( $args, $allowed_extensions );

        /*
        |---------------------------
        | Move File
        |---------------------------
        */

        if( $upload_hook['upload_move'] == TRUE ) {

            /*
            |---------------------------
            | Any Logic by User
            |---------------------------
            */

            /*
            |---------------------------
            | Move File
            |---------------------------
            */

            $upload_output[] = $object->get_upload_move();
            //$object->chip_print( $upload_output );

        } else {

            /*$temp['uploaded_status'] = FALSE;
            $temp['uploaded_file'] = $upload_hook['upload_file']['name'] ;

            $upload_output[] = $temp;*/

        }

    } // foreach( $files as $file )

} // if( $_POST )

Tuesday, 2 June 2015

PHP ffmpeg Upload Script

 
   // size input prevents buffer overrun exploits.
   function sizeinput($input, $len){
        (int)$len;
    (string)$input;
    $n = substr($input, 0,$len);
  $ret = trim($n);
   $out = htmlentities($ret, ENT_QUOTES);
   return $out;
}
 //Check the file is of correct format.  function checkfile($input){
    $ext = array('mpg', 'wma', 'mov', 'flv', 'mp4', 'avi', 'qt', 'wmv', 'rm');
    $extfile = substr($input['name'],-4); 
    $extfile = explode('.',$extfile);
    $good = array();
    $extfile = $extfile[1];
    if(in_array($extfile, $ext)){
          $good['safe'] = true;
    $good['ext'] = $extfile;
    }else{
          $good['safe'] = false;
   }
     return $good;
 }
  $user_id = $_SESSION['table_id'];
 // if the form was submitted process request if there is a file for uploading
 if($_POST && array_key_exists("vid_file", $_FILES)){
                           //$uploaddir is for videos before conversion
                          $uploaddir = 'uploads/videos/';
                           //$live_dir is for videos after converted to flv
   $live_dir = 'uploads/live/';
                            //$live_img is for the first frame thumbs.
   $live_img = 'uploads/images/';  
                           $seed = rand(1,2009) * rand(1,10);   
   $upload = $seed. basename($_FILES['vid_file']['name']);
   $uploadfile = $uploaddir .$upload;        
   $vid_title = sizeinput($_POST['vid_title'], 50);
  $vid_desc = sizeinput($_POST['vid_description'], 200);
                           $vid_cat = (int)$_POST['vid_cat'];
   $vid_usr_ip = $_SERVER['REMOTE_ADDR'];
                      $safe_file = checkfile($_FILES['vid_file']);
   if($safe_file['safe'] == 1){
                                if (move_uploaded_file($_FILES['vid_file']['tmp_name'], $uploadfile)) {
                                       echo "File is valid, and was successfully uploaded.<br/>";
      $base = basename($uploadfile, $safe_file['ext']);
      $new_file = $base.'flv';
     $new_image = $base.'jpg';
      $new_image_path = $live_img.$new_image;
      $new_flv = $live_dir.$new_file;
      //ececute ffmpeg generate flv
                      exec('ffmpeg -i '.$uploadfile.' -f flv -s 320x240 '.$new_flv.'');
                       //execute ffmpeg and create thumb
   exec('ffmpeg  -i '.$uploadfile.' -f mjpeg -vframes 1 -s 150x150 -an '.$new_image_path.'');
   echo 'Thank You For Your Video!<br>';
                       //create query to store video

   $sql = 'INSERT INTO videos (vid_cat_id, vid_user, vid_title, vid_desc, vid_file_name, image_file, vid_usr_ip) VALUES(\''.$vid_cat.'\', \''.$user_id.'\', \''.$vid_title.'\', \''.$vid_desc.'\', \''.$new_file.'\', \''.$new_image.'\', \''.$vid_usr_ip.'\')';
      $mysql = new mysqli('localhost', 'user', 'Pass&d', 'databasename');
     echo '<img src="'.$new_image_path.'" /><br/>            <h3>'.$vid_title.'</h3>';         mysqli_query($mysql, $sql) or die(mysqli_error($mysql));
             } else {
                    echo "Possible file upload attack!\n";
           print_r($_FILES);
             }
 
    }else{
  
       echo 'Invalid File Type Please Try Again. You file must be of type      .mpg, .wma, .mov, .flv, .mp4, .avi, .qt, .wmv, .rm';   
   }
 }
 ?>
 <form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
  <p align="left">Please upload Your video.  Thumbnails of your videos are based on the first frame of your video. <br /><h3>Please allow up to a minute for your video to upload. </h3>
   </p>
  <table width="600" border="0" align="center" cellpadding="2" cellspacing="2">
  <tr>
    <td width="260" align="left" colspan="3"><div align="center">
      <h3>Upload your Video ! </h3>
    </div></td>
   </tr>
    <tr>
      <td width="260"  align="left"> </td>
      <td width="326" align="left"> </td>
    </tr>
    <tr>
      <td align="left">Title Of Video : </td>
      <td align="left"><input name="vid_title" type="text" id="vid_title" /></td>
   </tr>
   <tr>
     <td align="left">File: .mov, .avi, .wma , .mpeg : </td>
     <td align="left"><input name="vid_file" type="file" id="vid_file" /></td>
  </tr>
   <tr>
     <td align="left">Description:</td>
    <td align="left"><textarea name="vid_description" id="vid_description"></textarea></td>
  </tr>
   <tr>
     <td align="left">Category:</td>
    <td align="left"><select name="vid_cat">
       <option value="1" selected="selected">Video</option>
       <option value="2">Cat1</option>
      <option value="3">Cat2</option>
      <option value="4">Cat3</option>
      <option value="5">Cat4</option>
    </select>
     </td>
  </tr>
  <tr>
    <td> </td>
     <td><input type="submit" name="Submit" value="Upload Video" /></td>
  </tr>
 </table>
 
</form>
 
I have not fully tested this script, it's good to learn from, you can see how ffmpeg is being used from php and you can see below mysql is used to insert thumb and encoded video. this script should work, on most Linux operating systems, with little change to the code to reflect your system.