Login   Register  
PHP Classes
elePHPant
Icontem

How to Use a Webcam to take Pictures in PHP Application - PHP Classes blog

Recommend this page to a friend!
Stumble It! Stumble It! Bookmark in del.icio.us Bookmark in del.icio.us
  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog How to Use a Webcam t...   Post a comment Post a comment   See comments See comments (18)   Trackbacks (0)  
<< Previous: The Debate About All ...>> Next: The Security of Futur...

Author: Vivek moyal

Posted on:

Categories: PHP Tutorials

If you want to take a picture of a user to be used in a PHP Web site, you can do it with a little help of a JavaScript and a Flash library.

This article is a tutorial that explains how to take picture snapshots using a Webcam to be uploaded to a PHP application.




Picture of Vivek moyal
By Vivek moyal India
<email contact>

Contents

Requirements

Capturing Pictures from the Webcam

Create the Uploads Database

Saving the Image to the Database

Saving the Person Name in the Snap Image Record

Conclusion

Requirements

The first thing you need is your PHP editor or IDE, a Webcam, MySQL and a cup of coffee. The PHP editor is of course for coding your PHP scripts, Webcam to take the image, MySQL for savingit in a database and Coffee is for your refreshment. :-)

In this article we will discuss how to capture the webcam image from our PHP and jQuery and save it to the database. It will use the Flash for the webcam screen. So you need JavaScript and Flash files that you can download from the bottom of this page.

Capturing Pictures from the Webcam

To create our capturing applications we need to create three files:

  1. Web page for showing the webcam
  2. Script to handle the image upload
  3. Script to access to the database

1. 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"; } } ?>

Conclusion

We created the index.php script file to show the webcam screen to save the image in our project directory.

When the user clicks the button to take snap image it will upload the image to the test.php script which in turn saves the image in the images directory.

When the image name is saved to the database the connection.php script establishes the database connection. A database table record is created with the image name.

The last inserted record identifier is stored in a session variable, so it is possible to update the table later with the person name and other details you may want to add in the submission form.

In this tutorial we use the JpegCam Library. The whole list of used files consists of: webcam.js, shutter.mp3, webcam.swf, test.php, index.php and connection.php.

If you liked this article or have questions, please post a comment here so it encourages me to write more useful articles.


You need to be a registered user or login to post a comment

1,273,838 PHP developers registered to the PHP Classes site.
Be One of Us!

Login Immediately with your account on:

Facebook ConnectGmail or other Google Account
Hotmail or Microsoft Windows LiveStackOverflow
GitHubYahoo


Comments:

9. How to make it work - Rajesh S (2014-06-14 04:37)
help me... - 1 reply
Read the whole comment and replies

8. Get Image and its details taken from web cam using PHP - Sai Varadula (2014-05-19 06:57)
How to get Image details taken from Web Cam Using PHP... - 1 reply
Read the whole comment and replies

6. only 1 screen needed. - vishesh kaul (2014-04-15 07:17)
help required urgently !!!... - 1 reply
Read the whole comment and replies

7. How to Use a webcam using PHP - Sunil Meshram (2014-04-14 19:14)
Must Test... - 0 replies
Read the whole comment and replies

4. thanks - missprogrammer (2014-02-28 05:38)
good... - 1 reply
Read the whole comment and replies

1. How to use webcam to upload to take picture in php application - raj lath (2014-02-28 05:38)
check for web cam availabilty... - 1 reply
Read the whole comment and replies

2. Flash? - Frankie P (2014-02-28 05:37)
Flash?... - 3 replies
Read the whole comment and replies

3. Use html5; forget about flash - Jeffrey Kurtock (2014-02-28 04:31)
jpegcam not supported since 2010... - 1 reply
Read the whole comment and replies

5. How to Use a Webcam to take Pictures in PHP Application - Igala Encyclopedia (2014-02-27 19:38)
Cool tutorial... - 0 replies
Read the whole comment and replies


<< Previous: The Debate About All ...>> Next: The Security of Futur...

  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog How to Use a Webcam t...   Post a comment Post a comment   See comments See comments (18)   Trackbacks (0)