Powered By Blogger

Monday, November 17, 2014

How to Use a Webcam to take Pictures in PHP Application

website link :    http://www.phpclasses.org/blog/post/228-How-to-Use-a-Webcam-to-take-Pictures-in-PHP-Application.html

Web Page for Showing the Webcam

With this file we will show our Webcam screen on our PHP page.
index.php
Here we will use the webcam.js file for the webcam functions to take the snap and save it.
 <script type=”"text/javascript”" src="”webcam.js"”></script>

We will make a form with the one text field and one button.
 <form action="<?php echo HtmlSpecialChars($_SERVER['PHP_SELF']);?>"
  method="post">
 <input type="text" name="myname" id="myname">
 <input type="submit" name="send" id="send">
 </form>

Below the form we will put our webcam window to show the webcam screen.
 <script type="text/javascript"><!--
  document.write( webcam.get_html(320, 240) );
 // --></script>

Now below the webcam screen we will use the buttons for configure webcam and take snapshot.
 <form>
  <input type="button" value="Configure..." onClick="webcam.configure()">
  <input type="button" value="Take Snapshot" onClick="take_snapshot()">
 </form>

In the code above we show the screen and get the image from webcam. But still we have to save it somewhere so lets go to save this image in our folder.

2. Script to Handle the Image Upload

After showing the Webcam screen in PHP page we take the snap from clicking the button. Then it the image needs to be saved to a server directory of our project.
For this we need to create a new script file named for instance test.php to save the snap image and return success.
test.php
 <?php

  $image = file_get_contents('php://input');
  if(!$image)
  {
   print "ERROR: Failed to read the uploaded image data.\n";
   exit();
  }

  $name = date('YmdHis');
  $newname= ” 'images/'”.$name.'”.jpg'”;
  $file = file_put_contents($newname, $image);
  if(!$file)
  {
   print "ERROR: Failed to write data to $filename, check permissions.\n";
   exit();
  }

  $url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['REQUEST_URI']).
   ‘'/'’.$newname;
  print "$url\n";

 ?>

In the code above $name will take the current date. $newname defines the image path for the uploaded image in the images directory.
$file is set to the success of the image saving operation. If there is any error the condition code will show the error. Otherwise the script will return the success message.
Now it's time to process the image snap. Add this code to index.php.
 <script type="text/javascript"><!--

  webcam.set_api_url( 'test.php' );
  webcam.set_quality( 90 ); // JPEG quality (1 - 100)
  webcam.set_shutter_sound( true ); // play shutter click sound
  webcam.set_hook( 'onComplete', ‘my_completion_handler' );

  function take_snapshot()
  {
   // take snapshot and upload to server
   document.getElementById('upload_results').innerHTML =
    '<h1>Uploading...</h1>';
   webcam.snap();
  }

  function my_completion_handler(msg)
  {
   // extract URL out of PHP output
   if (msg.match(/(http\:\/\/\S+)/))
   {
    // show JPEG image in page
    document.getElementById('upload_results').innerHTML =
     '<h1>Upload Successful!</h1>';
    // reset camera for another shot
    webcam.reset();
   }
   else
    alert('PHP Error: ' + msg);
  }

 // --></script>

Now we have the success message and we will show it in div.
 <div id="”upload_results”" style style="background-color: #eee;"”></div>

Create the Uploads Database

So now we have the code for taking the snapshot image and saving it to our images directory, but it is still not in database. Now we will update the code for saving the image and saving the name in database.
First create a database with the name “webcam” with a table named entry with three fields:
  1. “id” with auto-increment
  2. “name” column for denoting the person
  3. “image” name
First lets setup the database connection script.
connection.php
 <?php

  $host = '”localhost'”;
  $user = ”'some user';
  $password = 'some password';
  $databasename = '”webcam”';
  $con = mysqli_connect($host, $user, $password, $databasename);

 ?>

In the above code we create a connection string with the database.

Saving the Image to the Database

Now lets back to our save image script.
test.php
Include the connection.php script file for establishing the database connection.
 require('connection.php');

Then we have the code for saving the image in our database.
 $sql = 'INSERT INTO entry(images) values('.
  mysqli_real_escape_string($con, $newname).')';
 $result = mysqli_query($con, $sql) or die(“'Error in query'”);

So we have our insert code with us. Now our test.php will look like this.
 <?php
  session_start();
  require ‘'connection.php'’;
  $image = file_get_contents('php://input');
  if(!$image)
  {
   print "ERROR: Failed to read the uploaded image data.\n";
   exit();
  }

  $name = date('YmdHis');
  $newname=”images/”'.$name.'”.jpg'”;
  $file = file_put_contents($newname, $image);
  if(!$file)
  {
   print "ERROR: Failed to write data to $filename, check permissions.\n";
   exit();
  }
  else
  {
   $sql = 'INSERT INTO entry(images) values('.
    mysqli_real_escape_string($con, $newname).')';
   $result = mysqli_query($con, $sql) or die('“Error in query'”);
   $value = mysqli_insert_id($con);
   $_SESSION["myvalue"] = $value;
  }
  $url = ‘'http://'.$_SERVER['HTTP_HOST'].
   dirname($_SERVER['REQUEST_URI']).'‘/'.$newname;
  print “"$url\n”;"

?>

You may be wondering why am I using a session variable and retrieving the last inserted table identifier. That is because in our table we have three columns: the first is the record identifier, the second is for saving the person name, and the third is for image name.
from the above code we save the webcam image from php and jquery code in our database but now we want to save the person name on the same image. So we are taking the last id from database with the code and sending the value to the Session
 $value = mysqli_insert_id($con);
 $_SESSION["myvalue"] = $value;

Saving the Person Name in the Snap Image Record

Now we have the identifier of the record to which our image is saved. In the next step we save the person name in the database on the same record.
Edit the index.php page script and put some PHP code to save the person name taken from the text field parameter.
Add this code so the script saves the person name to the image database table record.
index.php
 <?php
  session_start();
  if(isset($_POST['send']))
  {
   $getname = $_POST['myname'];
   require('connection.php');
   $idvalue = $_SESSION['myvalue'];
   $sql = "UPDATE entry SET name = '.
    mysqli_real_escape_string($con, $getname).
    ' where id='.intval($idvalue);
   $result = mysqli_query($con,$sql) or die('error in query');
   if($result)
   {
    echo 'Updated '.$_SESSION['myvalue'];
   }
   else
   {
    echo "Error nahi hua";
   }
  }

?>

No comments:

Post a Comment