Posted in: Jquery, PHP

Webcam in PHP – How to Use Webcam in PHP





Webcam in PHP, How to show webcam in PHP, take image from Webcam in PHP read this article you will get all the details regarding these questions. Hello friends i am Vivek Moyal today i am uploading the tutorial for showing the Webcam in PHP page and save that image in database. It will be a nice tutorial for you please comment for the tutorial so we will get motivated. First of all what we need is your PHP IDE, a Webcam, Mysql and a cup of coffee.

PHP IDE is for coding the program, Webcam to take the image, MySql for database and Coffee is for your refreshment…. lol.

In this article we will discuss How to capture the webcam image from our PHP Jquery and save it to the database. It will use the Flash for the webcam screen

In this article we will make 3 Files

  1. Index file for showing the webcam.
  2. Script to upload.
  3. Connection Script for database.

First of all download some files from bottom of the post. Lets start…………..

1. Index File for Webcam . Download link files from here

In this file we will show our Webcam screen on our PHP page. For this download the package from above and link the jquery and swf.

index.php

In the above code 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 for Saving the webcam image

Now after showing the Webcam Screen in PHP page we took the snap from clicking the button. Now we will save it to the folder in our project.

For this we will make a new separate file ….. named …. test.php. But we have to save the snap and call the function for taking the snap and save it and return the success. So first we will make our script to save the image in folder but keep in mind that it will not work because it is just to save it but still we dont have the snap with us.

test.php

Let me explain the above code In this code $name will take the current time and data. In $newname we will put our image in images folder along with the image so we provide the full path with the image.

$file will save the image. If there is any error than our if condition will show the error otherwise our script will return the success message.

Now time to take the snap.

add this code in our index.php

Now we have the success message and we will show it in div.

So now we have the code for taking the snap and saving it to our images folder. But still it is not in database now we will update the code for saving the image and saving the name in database.


Create database.

Create database with any name here i am using the “webcam” table name is ‘entry’ with 3 fields.

  1. “id” with auto number
  2. “name” column here i am using it for denoting the person
  3. “image” name.

connection.php

In the above code we create a connection string with the database. Now lets back to our save image script

test.php

we will include the connection file for establishing the connection.

include ‘connection.php’;

now we will write the code for saving the image in our database.

So we have our insert code with us. Now our test.php will look like this.

Now you were thinking that why i am using the session here and why i am taking the id of last insert. It is because in out table we are using the 3 column 1 is id 2nd is for saving the person name 3 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

Now we have the id on which our image is saved. In next step we will save the person name in the database on the same id.

Come to the index page here will put some php code and we already have the textfield and button to save the details of the image

index.php

Add this above PHP code in our index file so we will save the details of the person with his webcam image in the database.

So in brief………… We make a index file in which we show the Webcam Screen to save the image in our project. By clicking the take snap button it will take snap and by using the test.php we save the image in our folder. Now when we save it our database we just updated the save code and made a connection file. Through getting the last Id and saving it to the session we have the id of the image. In index.php we make the code for saving the extra details of the image by filling the form and submit the form.

In this tutorial we use the JpegCam Library. In this we use following files

PHP Webcam (96.4 KiB, 20378 downloads)
  1. JPEGCam Library
    1. Webcam.js
    2. shutter.mp3
    3. webcam.swf
  2. Test.php
  3. Index.php
  4. Connection.php

Thanks for reading the tutorial how do you find please comment.

PHP Webcam
PHP Webcam
camtest.rar
96.4 KiB
20378 Downloads
Details...

Comments (311) on "Webcam in PHP – How to Use Webcam in PHP"

  1. Hi thank your for your code it’s really awesome.

    When i try this i got this error
    Can you help me,
    Failed to write data to webcamImage/20191128062103.jpg, check permissions

  2. Hey, I just want to know, why is it that the “Take Snapshot” button in index.php isn’t working for me? Thanks for the response!

  3. Hi. Thank you for this code, it works very well on my laptop.
    I would like to it on cell phones but I always get this error message: “webcam.js error: could not access webcam. NotSupportrdError: Only secure origins are allowed”. Do you know how to fix this issue? I think by having a SSL certificate (https) I can do it but I am asking myself if there is an easier way.

    1. Yes if you are running the code over the live server than you have to use HTTPS due to the browser terms and conditions.

  4. hello vivek,
    I used your code its working fine but when i add one more camera option to take and upload image then its showing error in webcame.js that is
    Uncaught TypeError: this.get_movie(…)._snap is not a function
    please help i stucked in this probelm.

      1. can i use same code on same page for multiple camera, because i was trying but it was not working. please help me out to solve this issue.

  5. Hi, thanks for the very useful tutorial, im getting an error, like the Linda error, when i click take snapn shot nothing seems to happen, and when i click submit i get this error: Undefined index: myvalue in C:\wamp\www\webcam\index.php on line 90, thanks in advance.

  6. sir , snapshot is not working and when i press submit it shows uploaded successfully, but i see nothing in database and image folder.

  7. Parse error:Syntax error,unexpected “”, expecting identifier (T_STRING) or variable (T_VARIABLE)or number (T_NUM_STRING) in C:\xampp\htdocs\…\index.Php on line 24
    Please help sir,all the l appreciate your efforts to enrich us.

  8. I can’t take snapshot and save to database, when i click snapshot, camera not taking the picture and do nothing. when i click “submit query” there are error like this

    Notice: Undefined index: myvalue in C:\xampp\htdocs\camTest\index.php on line 7

    Notice: Undefined index: myvalue in C:\xampp\htdocs\camTest\index.php on line 13

  9. Hi sir ………. can you tell me can we record also video using this plugin ……..
    i saw i scriptcam but it to complicated ….

  10. Snapshot not run and I can’t upload image into database…. Please, Let me kno why…

    Webcam.snap( function(data_uri) {
    // display results in page
    document.getElementById(‘results’).innerHTML =
    ‘Here is your image:’ +
    ”;
    } );

  11. please tell me why the capture sound is not comming after clicking on the take snapshot and my images are inserting and also capturing but they can’t be open from images folder its writtern that image is curropted…

  12. Hello admin nice tutorial!! can you help on on this error??

    Im getting Undefined index: myvalue in C:\xampp\htdo

    Any idea

  13. Hello sir,

    i have downloaded your code but it showing error on console like this: Syntax Error: malformed hexadecimal character escape sequence.

    when i click on take snapshot these error are come but captured image is stored in images folder n image path is not stored in database….

    Plzzzz help me

  14. Dear friend , i am imran. not work take_snapshot function if click on taksnapshot button.
    2) i required video conferencing tutorial (video chat).other hand tale me any website which provide video Api .
    plz reply.(thanks).

  15. Thanks for the package. Really nice one. Have followed the procedure and having the following problems.
    After taking the snapshot and click on the submit query, i get this error messages:

    Notice: Undefined index: myvalue in C:\xampp\htdocs\myproject\index.php on line 13

    Notice: Undefined index: myvalue in C:\xampp\htdocs\myproject\index.php on line 25
    Updated re …..

    Also the images does not save in the images folder.
    Please is there a way the image can be saved in the database as blog?

    Thank you and hope to hear from you soon.

    1. first of all these are not the errors these are just the Notices. And it is working fine please check that you have given the images folder proper permission so that it will save the image in the folder.

    1. As if you see that we are using database here to save the name of the image for further use. You can do one thing after the snapshot just save the image and than using the jquery/ajax just call the last image which you have clicked recently

  16. Hi,
    i wann write class base coding in php. If you know can you guide me. It’s help to reduce the code.
    Reply as soon as possible to my Id or in this blog only.

    Thank You.

  17. Hi,
    Thanks for the tutorial .
    I click on Take Snapshot button when i click it nothing happens & searching from where u have called take_snapshot() and webcam.configure() functions and i searched both these functions but couldn’t find it so can u send me the code to my Id,
    Thank U

  18. Hello, Vivek
    I downloaded the code , and it works fine untill I click on Take Snapshot button when i click it nothing happens & searching from where u have called take_snapshot() and webcam.configure() functions and i searched both these functions but couldn’t find it so can u send me the code to my id— baburao.a.latthe@gmail.com

    I need it’s urgent , I hope u send me the code …… Thank U

  19. Dear Sir,

    THANKS
    FInally i have done it in php-4
    $file=fopen($newname,’a’);
    fwrite($file,file_get_contents(‘php://input’));
    fclose($file);

    1. Sorry for my late reply as i was on leave ….. thats great that you have done this at your end and you put the whole code here also….. it will help the other’s too.. thank you for your help

  20. Dear Sir,

    I think it does not support in php 4–$file = file_put_contents( $newname, file_get_contents(‘php://input’) );, file_put_contents so what should i use or if anything please let me know.

  21. Dear Sir,

    The set of instructions which you have posted i run it on php-5 using xamp is working gracefully but when i run it on php-4 it’s throwing an
    alert:
    PHP Error: unknown And Div Section Has uploading… And Image Just Stucked up.
    Please Let Me Know The Solution I Have To Run This Program Using PHP-4 …
    Please

  22. Dear Sir,

    How May I Run This Code In Php Version 4 .
    If I am running in Php 5 it’s working superbly.
    but when i run in php 4 —
    I get an alert : php error unknown and uploading ..in div and image just hold.
    thereafter nothing is happening.
    Please Sir:

  23. Dear Sir,

    I have installed xamp-which has (mysql-SELECT VERSION();–5.6.20) and (PHP Version 5.5.15).
    Now I have downloaded the code and paste it inside the htdocs and extract it.thereafter i check the connection.php it’s exactly the same configuration which i am running then i did not edit anything.
    thereafter i created a database -webcam and then table inside webcam database-
    CREATE TABLE `entry` (
    `id` bigint(10) NOT NULL AUTO_INCREMENT,
    `images` varchar(200) DEFAULT NULL,
    `name` varchar(200) DEFAULT NULL,
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=latin1
    Next i have mozilla firefox version-25.0.1.
    I opened and put the -http://localhost/camTest/
    Then i clicked on allow of 1st camera screen now my lapy web cam on and snap is seen.
    and clicked on take sanpshot -nothing happened.
    then i write simple upload script that is uploaded the image easily.
    <?php
    if($_POST['submit']=='Submit')
    {
    $allowedExts = array("gif", "jpeg", "jpg", "png");
    $temp = explode(".", $_FILES["file"]["name"]);
    $extension = end($temp);

    if ((($_FILES["file"]["type"] == "image/gif")
    || ($_FILES["file"]["type"] == "image/jpeg")
    || ($_FILES["file"]["type"] == "image/jpg")
    || ($_FILES["file"]["type"] == "image/pjpeg")
    || ($_FILES["file"]["type"] == "image/x-png")
    || ($_FILES["file"]["type"] == "image/png"))
    && ($_FILES["file"]["size"] 0) {
    echo “Return Code: ” . $_FILES[“file”][“error”] . “”;
    } else {
    echo “Upload: ” . $_FILES[“file”][“name”] . “”;
    echo “Type: ” . $_FILES[“file”][“type”] . “”;
    echo “Size: ” . ($_FILES[“file”][“size”] / 1024) . ” kB”;
    echo “Temp file: ” . $_FILES[“file”][“tmp_name”] . “”;
    if (file_exists(“upload/” . $_FILES[“file”][“name”])) {
    echo $_FILES[“file”][“name”] . ” already exists. “;
    } else {
    move_uploaded_file($_FILES[“file”][“tmp_name”],
    “images/” . $_FILES[“file”][“name”]);
    echo “Stored in: ” . “images/” . $_FILES[“file”][“name”];
    }
    }
    } else {
    echo “Invalid file”;
    }
    }
    ?>

    Filename:

    then i checked the webconsole in js there is showing an error–
    ReferenceError: take_snapshot is not defined

    Sir Please Let Me Know The Proper Solution.!!

  24. Dear Vivek Moyal Sir.
    I found best code for php webcam application from here and I downloaded all file and create “webcam” folder in “localweb” folder and make “images” folder in “webcam” folder after that I create database in mysql named “webcam” and table named “entry” and field id int(11) auto_increment, name varchar(100), image varchar(100)
    all instruction I followed in this page but after-all error occurred as bellow so please help me.
    When I type name in text box and click on submit button then below error showed me..
    Notice: Undefined index: myvalue in C:\Program Files\EasyPHP-DevServer-13.1VC9\data\localweb\webcam\index.php on line 7

    Notice: Undefined index: myvalue in C:\Program Files\EasyPHP-DevServer-13.1VC9\data\localweb\webcam\index.php on line 11
    Updated re …..

    So then I Click on Take Snapshot there are no capture voice and not image saved in images folder

    after I chacked http://127.0.0.1/Webcam/test.php, so there are also error ERROR: Failed to write data to 0, check permissions
    So please help, Thanking you.

    1. If you are getting the write error than please check the permission of the folder. It should be write enabled.

      Here myvalue is a session value and what you are getting is Notice. so dont consider it. Just turn off the notices it will go away

      1. Thank you for quick reply.
        I checked user permission and grant full access to everyone user.
        I used ATTRIB command ATTRIB -r -h -r /S C:\…..\lacalweb\webcam
        but same problem exist…. as my above post…
        So please help me how can access folder permission by appachi server on windows 7
        Thank you

  25. Hi Vivek

    Firstly, thanks for writing up such a nice script.

    I am facing up a lil problem in chrome. I guess it something with flash-player settings or some other thing.
    Its giving me this error in console.
    Uncaught Error: Error calling method on NPObject. on this line of webcam.js
    this.get_movie()._snap( this.api_url, this.quality, this.shutter_sound ? 1 : 0, this.stealth ? 1 : 0 );

    else on IE and firefox its working like a fly. If you can tell me about this than i will be grateful.
    And one more thing if i want to send some extra parameter on the php side(test.php) how can i do that without using session means sending the post request with the uri ??

    Regards
    Singh

  26. thanks for the reply sir, the below mentioned issue has been sort out , now i want to do that after opening the webcam in the div it ask for allow and deny .here i want this to be allow by default after submiting the name….can u please guide me….thanks in advance

  27. thanks for the wonderful explanation ….its nice but how can i allow the webcam to take click each time i open the api

  28. thanks it works fine for me …but i want to do something new i want to write a script that webcam click image after every 30 sec …can anyone pleaseguide me

  29. Hi Sir Vivek Moyal,

    how to check the permission and what is permission sorry newbie.

    regards,
    dave

  30. Hi sir Vivek Moyal,

    can you teach me how to check the permission. sorry im newbie web programmer.

    thanks,
    Dave

        1. here is the code
          <?php
          session_start();
          include 'connection.php';
          $name = date('YmdHis');
          $newname="images/".$name.".jpg";
          $file = file_put_contents( $newname, file_get_contents('php://input') );
          if (!$file) {
          print "ERROR: Failed to write data to $file, check permissions\n";
          exit();
          }
          ….

          Result: ERROR: Failed to write data to 0, check permissions

        2. You have to change the permission of your folder so that it will allow you to write content. If you are using FTP than you can set the permission from there too.

          You can specify the permissions when you create a directory using the -m option

          mkdir -m 777 dirname

          Or you can set the permissions recursively.

          chmod -R 777 /var/www

          Before using either of these, really consider if you want your filesystem to be so accessible.

  31. Hi,
    It is really great tutorial. But i have a problem.
    I am running it on localhost. I visit http://localhost/camTest site, when i click “Take Snapshot” button it does not give any response. I tried to go to http://localhost/camTest/test.php page and i get the following error: “ERROR: Failed to write data to , check permissions ” i cannot solve this.

    Plese reply as soon as possible.
    Thanks For the very helpful post.

  32. great work, Sir!

    but I have 2 errors when I clicked submit query: Undefined index: mywalue at line 7 and 13 of index.php.

    I think I have the same problem with ryan. Kindly help us solve these. thank you.

  33. great work! but when I clicked submit query, there were 2 errors: undefined index: myvalue in C:……. index.php in lines 7 and 13. I

  34. When i click on Take snapshot after that the below error appearsUndefined index: myvalue in C:\xampp\htdocs\camTest\index.php on line 7 error in query

  35. I got name and extension exactly but when open the image it is giving only 1kb image file with invalid image data.I checked ny keeping alerts in javascript it is not calling the function

  36. Hi vivek ,Hope you are doing well………It’s working fine at my local but facing issue on my server . Got error “Error in Actionscript”In this line got error:

  37. Hi Vivek, you have done excellent work. I am facing problem while storing image data it is capturing the image and store it database working fine but the image with 1KB only showing invalid image. please help me …reply me as early as possibleThanking you in advance.

  38. Sorry i am trying in localhost. But now i can able to run in chrome, but not in firefox..Thanks alot for such good code..

  39. you code is working fine over localhost.but it gives me an exception when hosted on free hosterror is-“content not loaded completely”.

  40. HiI’m able to see live camera in the window when I visit http://localhost/camTest site. But when I click on “Take Snapshot ” Button then it does not give any response. I tried to run it on firefox, chrome and IE but same problemAlso when I go to http://localhost/camTest/test.php I get the following error: ERROR: Failed to write data to , check permissions But it creates a ’0′ bytes jpg file.Please help!!!!Regards,wutdy

  41. i have create form using webcame how to capture image feed in my contact form show image in contact form and display image in contact form capture image show directly in contact form

  42. it is really great tutorial, I am making my dating site and I will use it there for enabling its members to upload picture from web cam.. Gr8

  43. hi
    i want webcam video record and recorded video stored in server and video name stored in mysql database
    Please help me

    Plese reply as soon as possible.

  44. Hi ,
    I have implemented the code by the way you have given.
    I am running it on localhost. When I click on “Take Snapshot Button”, I only see Uploading………. Why is it so. And do this system check whether a person is running his program in a machine in which camera is not connected.

    Plese reply as soon as possible.

    Thanks For the very helpful post.

  45. sir this is very good code.i am using this in my project.In localhost camera is working.but when hosting my project camera is not coming,only capture,settings buttons coming pleasce help me

  46. Hi Vivek ,
    Nice tutorial , is there a way through which we can capture image with time delay ?
    For example , once the capture button is pressed there should be a delay of 10 seconds for capturing the image and after 10 seconds , Image will be captured automatically

    Thanks in Advance

  47. please help i have error
    Parse error: syntax error, unexpected T_STRING in D:\xampp\htdocs\webcam\index.php on line 97 how can i do this

  48. sir this is very good code.i am using this in my project.it captures the image and storing in the database. but i want to know, is it possible that after capturing image the camera will move in sleep state for that stage only.means same image will be dis[played in the window until i will cancel it manually. bcoz i want to apply some effects on it.
    so please help me and give some solution for it.

    1. There you will find a function named

      webcam.reset(); If you will remove it it will not restart the cam. So you can do your work by removing it and after finishing just call this reset function

  49. to capture the image of voter for the purpose of verification. actually i make a project in which the question is arisen that how we identify that how the voter can cast their vote single time.we want to identify their face .

    1. Thats nice that your are thinking like that. But i think image verification is too much tough task and i wont demoralize you so If you need any help from me i am here to help you…. For your last question you do one thing create a camera session (default value = false) when a person open your vote page than let them choose whom they want to vote. Now the working starts from here….. Check session ex- If a person clicks on radio button or whatever you are taking than check your camera session. If your camera session returns true than save the vote else show him the alert “Your vote wont be calculated untill you wont click your image………” If they took the image than make your session true. It will work for you as authentication

      Now the tricky part…… If the person is not having the cam than what you will do ????? you will loose a vote.

  50. Could you modify webcam into “”set time camera””?
    for example, click button, after 10 seconds, take a snapshot

    or click button and take snapshot per 10 minutes?

  51. Thanks Vivek for very good script explanation and i am searching this code..
    finally i got here..
    Great Job

    Thanks once more

  52. When i click submit i get this message: “Notice: Undefined index: myvalue in C:\wamp\www\camTest\index.php on line 7”

    please help me to fix this, i’m new in php. Thanks!

    1. Please check the test.php as myvalue is a session variable and it is containing some value so try to manipulate that than use it…. if still you dont get let me know i will help you

  53. Very very nice….vivek
    i am so thankfull to you..
    I been searching for this code from past so many days…Finally i got here….

  54. I truly appreciate the explanation you gave about the JPEGcam. I really want to design a form whereby the webcam light wouldn’t be on anything someone gets to the form but till its called for capturing the image of the person filling the form and then return the captured image to the image-placeholder before the form will be submitted.
    thanks in anticipation for a positive answer.

  55. Hi Vivek,
    Can you help me do the same thing but using video recording instead of the photo.
    Thank you.

  56. nice post…i’ really thanksfull for that.But sir, can i get an example on how to do like your post but on the ip camera device?i’m really need that..because i have a project to control movement of the ip camera and also to get a snapshot and store it in the mysql database..please help me….thanks a lot…

  57. Hi Vivek,

    I have 2 questions:

    1. I am using webcam.freeze() method to capture the image. And i have some form input elements. I want to sent both the image as well as form data to the Save page. If i use Form Submit, only form data is getting saved. If i use webcam.upload(), only image is getting saved. How to send both of them?
    Or is it possible to capture the image and convert into Base64 encode data and pass it using form element?

    2. Is it possible to save the image into the database (not path, the actual image/Base64 encoded data) instead of storing in FileSystem?

    Thanks,

    Mani.

  58. Hello Sir,
    This is Harminder Singh .Sir when I run this script on my local server then it will not show any image on the window. When I click on the “allow” button then window will hide from my screen.So please help to solve this Problem.

      1. Sir ,when I run this script on my local host then after click on allow button it will not show any response to me….

        1. Please check that it is connecting to your main webcam properly. In setting you will see there is a dropdown from that dropdown try to change it if there is more than 1 value may be it work than

          1. Sir now it showing image in the window .But when I click on “Take Snapshot ” Button then it does not give any response.

              1. Sir now it is working in Mozila but not on other browsers.So how I can solve this problem.
                Thank You…

                1. Hi Vivek,
                  I’m able to see live camera in the window when I visit http://localhost/camTest site. But when I click on “Take Snapshot ” Button then it does not give any response. I tried to run it on firefox, chrome and IE but same problem

                  Also when I go to http://localhost/camTest/test.php I get the following error:
                  ERROR: Failed to write data to , check permissions
                  But it creates a ‘0’ bytes jpg file.

                  Greatly appreciate if you could send me all the files including the database/table creation script file also to krish.jagi@live.com.

                  Thanks,
                  Krish

  59. Hello SIr,
    This is Harminder Singh .Sir I have a problem when I run this code on my local server then it does not show my picture in the window.Even my web cam is working . This problem is only occur on the DESKTOP.

  60. Hi Vivek

    First thank you for your great work ,,, I could run it perfectly as a folder (I downloaded) in my localhost ,,, but when I use your code in a separate page I can connect to webcam but I cant take a snapshot while it works like a charm on your index.php ,,, Do you know how I solve this problem ?! thanx

    1. I dont think it will be a problem ….. try to check that you are using every link and code in your page and check you are calling all the jquery files. it will work perfectly you will get no issue

  61. Hi there, just became alert to your blog through Google, and found that it is really informative.
    I am going to watch out for brussels. I’ll appreciate if you continue this in future. Many people will be benefited from your writing. Cheers!

  62. how if wan’t to take take cam in other ip.
    maybe i want to access webcam from ip 192.168.2.69
    where must be change url?

  63. Vivek,
    When an image is captured using snap(), is it possible to include timestamp in right corner of image. I am trying to do some automation, and it helps to have timestamp.

    cheers
    Lawrence

  64. Vivek,
    I am trying to use jquery plugins to record webcam videos and upload them, without having to spend on expensive media servers. I came across http://www.scriptcam.com/.
    Just would like to know your thoughts on this, or if there are any alternatives.

    Thanks
    Lawrence

      1. yeah true. but.I think its onetime fee ~50 eur..maybe can give it a shot. Thanks for your quick response.

  65. i tried implementing this code, in my form… it is saving the image in the “images” folder correctly but isn’t inserting in the database i tried with my form and yours both gives me a “error in query” even though i didn’t modify anything.

    $name = date(‘YmdHis’);
    $newname=”images/”.$name.”.jpg”;
    $file = file_put_contents( $newname, file_get_contents(‘php://input’) );
    if (!$file) {
    print “ERROR: Failed to write data to $filename, check permissions\n”;
    exit();
    }
    else
    {
    $sql=”Insert into entry(images) values(‘$newname’)”;
    $result=mysqli_query($con,$sql)
    or die(“Error in query”);
    $value=mysqli_insert_id($con);
    $_SESSION[“myvalue”]=$value;
    }
    my “image” field data type is set as varchar

    1. Have you done with getting the $con

      or die(“Error in query”); replace it with or die(mysqli_error($con));

      It will show the exact error if still you are not able to sort out than let me know

      1. thanks for the quick reply ^^ the error was…
        >>>$sql=”Insert into entry(images) values(‘$newname’)”;
        it should be entry(“image”)
        it’s inserting into the database now

        i’try to submit the picture with the others form fields… is there a way to insert the image in the same table as the rest of the form?

        also how do i show the picture after i have selected it with a query?

        thanks a lot in advance

        1. Yes you can do that. there was a line $value=mysqli_insert_id($con);
          $_SESSION[“myvalue”]=$value;
          In this $_session[“myvalue] you have the image inserted id. Now if you want to submit values than just update the values in the database where id=$_session[“myvalue];

          When i am showing the …. “ho gaya re” Just show your image. You have to use the jquery here to get the image

          If still get any issue than let me know but i will reply you in morning as i am leaving for sleep. Good Night tc swt drm

          1. thanks again ^^ i figured out how to do it…but there’s a lot of values here to insert so will update later if everything goes right

            again thanks and good night ^^

            1. so everything went fine i’m but… is there a way to insert the actual snap in the database not just the URL?

              1. Ya it can be done but you have save the images in bits.. which is too much tough for anyone…………. so use just the URL which is easy and everywhere accessible

  66. HI Vivek,
    Can I use the same source code, to capture a video using webcam, save it in local or temp and then upload it online. Please share your thoughts, how this could be done.

    Thanks
    Lawrence

  67. sir , im clicking on takesnapshot button but images are not going in the specified folder….i think that button is not working….
    in test.php i specified the path as

    $newname=”C:/wamp/www/camTest/images/”.$name.”.jpg”;
    $file = file_put_contents( $newname, file_get_contents(‘php://input’) );

  68. hmm…my webpage though, will not have any mouse click event. Once page loads, webcam must get activated and start capturing images.
    I tried calling a temp function() from , which in turn calls timeout and snapshot().
    The body onload is not too predictable and fails too often.
    How can I call repeatedly without user initiation.

  69. Hi Vivek ,
    Firstly thanks for your blog. It has been very informative for beginners like me.
    Have a quick question.
    I want to take images in random intervals of time, using webcam, but these have to be triggered automatically, rather than by user click. How can I invoke the take_snapshot() automatically.

    1. Use this function and call the snapshot() and fix the time period
      setTimeout(function() { //calls click event after a certain time
      that.element.click();
      }, 10000);

  70. Hi,
    when the page load, allow and deny message is showing ,,,,,, I don’t want to show that message, i want direct capture option is it possible ?

  71. this coding is not working in my linux serverwhen i runing code in linux cam was not accessing.what is the solution for that.how a cam wrk in linu server.

    1. Tell me what you want to do. I am still confused. I will work over your problem today so tell me what you want.

      You want to show the name below the image.
      You want your name below the webcam.
      You want to save the image along with the name.

      Choose which one is correct or tell me if all are wrong

          1. i think i got something look
            this is my input

            <input type="text" name="mle_hide" value="” style=”display:inline;”>

            and this is the fonction

            function take_snapshot() {

            // take snapshot and upload to server
            document.getElementById(‘upload_results’).innerHTML = ‘Uploading…’;

            var mle = 81666;//document.getElementById(‘mle_hide’).value;
            webcam.set_api_url(‘test.php?id=’+ mle);

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

            webcam.snap();
            jQuery(“#flash”).css(“display”, “block”);
            jQuery(“#flash”).fadeOut(100, function () {
            jQuery(“#flash”).css(“opacity”, 1);
            });
            }

            look at var mle when i fixed the numbers it works but when i do “document.getElementById(‘mle_hide’).value;” doesn’t works if you have any comment or any help

              1. what do you think now still any error

                <input type="text" name="mle_hide" id="” style=”display:inline;”>

                function take_snapshot() {

                // take snapshot and upload to server
                document.getElementById(‘upload_results’).innerHTML = ‘Uploading…’;

                var mle = document.getElementById(‘mle_hide’).id;
                webcam.set_api_url(‘test.php?id=’+ mle);

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

                webcam.snap();
                jQuery(“#flash”).css(“display”, “block”);
                jQuery(“#flash”).fadeOut(100, function () {
                jQuery(“#flash”).css(“opacity”, 1);
                });
                }

                1. <input type="text" name="mle_hide" id="” style=”display:inline;”>

                  Use this for above code

                  var mle = document.getElementById(‘mle_hide’).id;

                  Use this for getting value

                  var mle=$(‘#mle_hide’).val();

                  Try this than let me know

                  1. do you means like that

                    function take_snapshot() {

                    // take snapshot and upload to server
                    document.getElementById(‘upload_results’).innerHTML = ‘Uploading…’;

                    var mle = document.getElementById(‘mle_hide’).id;
                    var mle=$(‘#mle_hide’).val();

                    //var mle = document.getElementById(‘mle_hide’).id;
                    webcam.set_api_url(‘test.php?id=’+mle);

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

                    webcam.snap();
                    jQuery(“#flash”).css(“display”, “block”);
                    jQuery(“#flash”).fadeOut(100, function () {
                    jQuery(“#flash”).css(“opacity”, 1);
                    });
                    }

                    1. do you means like that

                      function take_snapshot() {

                      // take snapshot and upload to server
                      document.getElementById(‘upload_results’).innerHTML = ‘Uploading…’;

                      var mle=$(‘#mle_hide’).val();

                      webcam.set_api_url(‘test.php?id=’+mle);

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

                      webcam.snap();
                      jQuery(“#flash”).css(“display”, “block”);
                      jQuery(“#flash”).fadeOut(100, function () {
                      jQuery(“#flash”).css(“opacity”, 1);
                      });
                      }

    1. You can do it. Just put a field in inside the form than click on take snapshot now you have 2 things 1 is your name and another is your image. Now when we are saving the entry of image in the database you just add code for the name also. It will save the name and when it shows the success call the saved name through the database. It will solve your problem

      1. really really thanks you but this not the right methods im looking for something like to send the name directly to test page not somthing like that its so complicated so many thanks man

          1. sure what about this one
            function take_snapshot() {
            // take snapshot and upload to server
            document.getElementById(‘upload_results’).innerHTML = ‘Uploading…’;
            $.ajax({
            type : “POST”,
            url : “test.php”,
            dataType: “json”,
            data :{
            cedula:$(“#cedulaingr”).val(),
            },
            success:function() {
            webcam.snap();
            }

            })

            }

  72. Hi! Vivek nice code..But i have a problem , i have downloaded your code on my localhost wamp server. I had created database as you have mentioned. And when i tried running the code it shows webcam but wen i click on snapshot its not store in database and its not going to test.php ..and a blank image is stored in images folder. If you could help me to figure out where i have gone wrong. And if you have any other code which tkes snapshot from webcam would be really grateful. Thank You!

      1. i have the same problem too. i downloaded the code in my wamp server.
        when i click on “Take Snapsot” it does nothing. so i checked test.php and
        when i run /localhost/test.php in my browser it displays this “20130522145203ERROR: Failed to write data to 0, check permissions”.
        so when i open 20130522145203.jpg says “can’t display this picture,file is empty.

        your help will be appreciated!
        thanks a lot!

          1. first of all thanks for the reply!

            the first problem i have to fix is,when i run index.php it displays two messages Notice: Undefined index: myvalue in C:\wamp\www\index.php on line 8 and Notice: Undefined index: myvalue in C:\wamp\www\index.php on line 14 which i can’t understand why,as soon as i have copy pasted your php script from your index.php in mine.

            the second is that when i click “take snapsot” nothing happens,which means it can’t communicate with test.php

            thanks!

                1. Hi, thanks for great tutorial.
                  I have the same problem, if you solved this, please let me know how.

  73. first i want to thank you about the great work really nice and useful but i have a question ,in the index page i have a dynamic value and i want when i klick to the snapchot sent this value to teste.php page can you give any help plz

      1. i think you don’t understand what is my problem i have ID for each person and i want when i click to snapshot send this ID to test page without write this id manual

        1. Than you do one thing when you click on the snapshot button also put the Id of the person than submit the form it will save the value in it, Or if you can than try to work with the jquery code and pass the value with the image

          1. how can i do it with jquery plz i try a lot of methods but still non result i try this

            Change: webcam.set_api_url( ‘test.php’ );

            to something like:

            var mle = document.getElementById(‘mle_hide’).value;

            webcam.set_api_url(‘test.php?id=’ + mle );

                  1. in the download linke you fixed the name of the image
                    $name = date(‘YmdHis’);
                    $newname=”images/”.$name.”.jpg”;
                    but me i want to send the name of the image on snapshot u told me try jquery i asq u how cani do it

    1. You should check your hosting than because my code is working over the Bigrock servers, my servers, and many other servers. You should check your server

  74. How to include the 2 web cams in the same file? I tried it for one its working fine but second one is not working.. Plz help me out.

    1. Use the below code twice it will work fine.

      //Now below the webcam screen we will use the buttons for configure webcam and take snapshot


        

        1. Same as for 1 cam. Just check your table and execute the query over the button click. For different different cam window use different form so it when you will click over it it will check for the code which is going to be execute and it will enter the details in your database

              1. In database only 2nd webcam photo is updating not the first webcam photo. I want to update both photos in database. How to do it Sir??

                1. Run your query 2 times, or create an array and add the images to it. When you finishes with your image click than save the values in the database. In second option you dont have to run the save script 2 times

                    1. Check your database script bro. because some where in that query your are making some mistake else it will work easily as it works for 1 cam

  75. Take Snapshot button is not giving any result… 2 windows of webcam are coming up in index.php… images are not being saved in the /images…. When I click Submit
    Notice: Undefined index: myvalue in C:\wamp\www\index.php on line 7
    Notice: Undefined index: myvalue in C:\wamp\www\index.php on line 13
    errors are coming up… Please help…

    1. Please check that myvalue is a session variable which is getting the value from filling the form and saving the value in the database.

      When you fill the form it will put the values in your database after that it will put the New Id in getvalue.

  76. hi
    i got some error please solve it

    Notice: Undefined index: myvalue in C:\Program Files\EasyPHP5.2.10\www\camTest\index.php on line 7

    Notice: Undefined index: myvalue in C:\Program Files\EasyPHP5.2.10\www\camTest\index.php on line 13
    Uploaded re …..

  77. Let me tell you how my code is working.

    When we took a snap it insert a row in database and get its id in session variable. Than it will move to the form than again when you click on the submit button it will just the row with the id of session variable. If you capture 2 time it will take the latest snap. So you have to change the ID from inserting the value according to your project.

  78. In one of my case
    I take one snap shot but not submitted the form. (let this be image1)
    after reloading the page i take one more snap shot (let this image2) and now i submitted the form. now the problem is it takes image1 is stored in the folder.
    If you can solve this problem please help me

  79. In my project i used this code.It works perfectly until i take a single snap shot for storing one record.
    but when i take two snap shots, first one is stored correctly in my folder but the second snap shot is stored some where and it applied to the next record. I tried in many ways to clear the stored images but failed.
    so please help me.

  80. i am a very beginner in PHP
    i got this error
    “Notice: Undefined index: myvalue in C:\wamp\www\camTest\index.php on line 7

    Notice: Undefined index: myvalue in C:\wamp\www\camTest\index.php on line 13
    Uploaded re …..” can you tell me why ?please

  81. sir i have problem while i take a snapshot the entry is not made in database and even the snapshot is also not taken and not saved in images folder.and every time i refresh the index.php page on localhost it give link for download a file with the name of shutter.mp3 .please help me out for my project.its my first project of life

    1. Hello Jigar

      You have to download all the files because shutter.mp3 is for music when you capture the image. You just download the file from download link than go through this tutorial you will understand everything if still you find any problem let me know i will help you over teamviewer

  82. Hi! I’m new in PHP. Why is it I am getting these error messages

    “Notice: Undefined index: myvalue in D:\xampp\htdocs\Webcam\camTest\index.php on line 7

    Notice: Undefined index: myvalue in D:\xampp\htdocs\Webcam\camTest\index.php on line 13
    “?

    1. Yes you can ………… just use the temporary data and show it in the div. But you have to click the image first than you can show it dont if i remember there is a text came up when we click the image and it show uploading at this point you can show the image just get the image and pass that image path to that div it will show the image at there.

  83. sir this is awesum but can u guide in showing that how can i create a preview before upload with confirmation button and i also want to align the webcam screen into my table is it possible

  84. I am really іnspiгed along with youг writіng talents as
    ωell as with the formаt іn уour blog.
    ӏs this а paid theme οг diԁ you mοԁifу
    it your self? Eitheг ωay κeeр up the excеllent quаlity ωriting, it’s rare to look a great weblog like this one nowadays..

  85. I really like this post. So I am testing in localhost.. I have come up with this error when I submit the name for the image…
    Warning: mysql_query() expects parameter 1 to be string, resource given in C:\xampp\htdocs\camTest\index.php on line 9
    error in quiery… I checked the code and changed mysqli to mysql and the problem is still the same.
    Also When I took snap…error message “error in query” came up, I solved this by changing mysqli to mysql… If you can give the solution to my problem, I would be very happy as I am planning to use this code for school management system…
    Thanks in advance.

    1. I think you are having the error in your database. Check your database query of submitting the value to your database may be somewhere you are missing somthing

      I have also sent your the mail with the project.

      1. Thanks a million for quick reply.
        The following is my mysql database table.

        CREATE TABLE IF NOT EXISTS `webcam` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `name` varchar(100) NOT NULL,
        `image` varchar(100) NOT NULL,
        PRIMARY KEY (`id`)
        ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
        If something is wrong, please tell me. And I did not get your mail. I would feel very much relief if you can send me all the project files with the sql file.

          1. Thank you very much…..I have got your mail…and upload all the files and folders to my htdocs,..changed connection in accordance with mine….and I also create my database with the one you have sent me…What I have got is: error in query…while capturing and pressing submit query button for saving the name of image….the image is saved in the image folder…but it does not submit into the database….I started thinking that my version of mysql and php may not support the query…I am using xampp-win32-1.7.3… PHP version is 5.3.1 and Client API library version for mysqli is 5.1.41 …Is there anything particular to change in php.ini? If you could help me solve this, how would I express my feeling?

            1. ok so your image is saved in the folder. Is image name is going into the database or not if not than check the entry for saving the image name and if it is working fine and saving the image name than check at last point of the query i am passing a variable in a session and make sure your session is allowed in your browser. If still you dont get the desired result than let me know i will be online on teamviewer.

        1. i can’t take the snap form this code…..after click on take snapshot button only “uploading….” is show and click on submit button message is show
          “error in query”
          i make database in zend “mysql” with u specified..
          plz hepl me…….as soon as possible

      2. hi vivek pls am new to PHP am having problems linking mine to PHP on a form, every thing is working fine can u pls help me create a form and a database with some few fields and send to my mail so i could better understand it pls

        thanks in anticipation i like your tutorials it is very great

Leave a Reply

Your email address will not be published. Required fields are marked *