Webcam in PHP – How to Use Webcam in PHP

By | August 17, 2012


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

  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.

249 thoughts on “Webcam in PHP – How to Use Webcam in PHP

  1. Aashu

    Dear Sir,

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

    Reply
    1. Vivek Moyal Post author

      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

      Reply
  2. Aashu

    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.

    Reply
  3. Aashu

    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

    Reply
  4. Aashu

    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:

    Reply
  5. Aashu

    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.!!

    Reply
  6. Deal seeking mom

    Heya i’m for the first time here. I found this board and I find
    It really useful & it helped me out a lot. I hope to give something back and help others like you aided me.

    Reply
  7. praveen kumar

    ThaNks For your Script Bro :) Its so nice and much more helpfull myself

    Reply
  8. RJ Chaudhary

    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.

    Reply
    1. Vivek Moyal Post author

      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

      Reply
      1. RJ Chaudhary

        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

        Reply
  9. Jaspreet

    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

    Reply
  10. Arun Chaudhary

    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

    Reply
  11. Arun Chaudhary09

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

    Reply
  12. Arun Chaudhary

    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

    Reply
  13. Dave Listen

    Hi Sir Vivek Moyal,

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

    regards,
    dave

    Reply
  14. Dave Listen

    Hi sir Vivek Moyal,

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

    thanks,
    Dave

    Reply
        1. Dave Listen

          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

          Reply
        2. Vivek Moyal Post author

          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.

          Reply
  15. Cemile

    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.

    Reply
    1. Vivek Moyal Post author

      Please check i think you should set the permission for your folder it will help you to run this code

      Reply
  16. isaac

    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.

    Reply
    1. Vivek Moyal Post author

      If you check than you will find that in myvalue we are taking the last inserted id. and myvalue is a session variable only.

      Reply
  17. isaac

    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

    Reply
  18. Vaibhav

    Yes sir.All files are same(not altered). btw where to check the myvalue is session variable or not. 

    Reply
  19. Vaibhav

    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

    Reply
  20. kiran

    “pkirankumar” is our skype, please add us into your contact list, its quite urgent stuff vivek.

    Reply
    1. Vivek Moyal Post author

      Your webcam is now working and try to work on jquery and it will do your further work. If still you face any issue let me know

      Reply
  21. Lokesh

    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

    Reply
  22. vivek jain

    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:

    Reply
  23. Lokesh

    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.

    Reply
    1. Vivek Moyal Post author

      When you save the image did you get the image name with proper extension if not than that is the issue….

      Reply
  24. Lohith

    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..

    Reply
  25. Lohith

    Hi i am getting this error. ERROR: Movie is not loaded yet after clicking configure. Please help out..

    Reply
  26. Fazal

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

    Reply
  27. wutdy

    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

    Reply
  28. Van

    Is there a way to upgrade the script to rec a video from webcam and save it to the server ?

    Thanks!

    Reply
  29. deepak

    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

    Reply
  30. boypeace

    please send me work source code, I can’t not use it, why to configure to database??

    Reply
  31. rupi

    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

    Reply
  32. dsr

    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.

    Reply
  33. Supriya

    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.

    Reply
  34. nikhil

    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

    Reply
  35. Dan

    Hi Vivek,

    What about webcams with zoom capability? Is there a way to zoom in and out?

    Thanks,
    Dan

    Reply
  36. Pratik

    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

    Reply
  37. yael

    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

    Reply
  38. yael

    hi i really need this for my capstone project can you help me .. can i have the copy of the working code

    Reply
  39. Francis Parent-Valiquette

    Vivek,

    Thanks for this tutorial it’s really appreciated. I can’t see the link to download the swf/js script “Index File for Webcam”. Is this informations is up to date? Can you provide me the link to download?

    Regards

    Reply
  40. Sunny

    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.

    Reply
    1. Vivek Moyal Post author

      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

      Reply
  41. neha

    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 .

    Reply
    1. Vivek Moyal Post author

      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.

      Reply
  42. neha

    sir this is very good but can u guide in showing that how can i create a webcam in online voting system project

    Reply
  43. Chunming

    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?

    Reply
  44. Deepak

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

    Thanks once more

    Reply
  45. Dhiraj

    Thanks for help
    great work

    just one } remaining in source code . plz look over that

    Reply
  46. ryan

    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!

    Reply
    1. Vivek Moyal Post author

      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

      Reply
  47. Mahesh

    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….

    Reply
  48. ken

    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.

    Reply
  49. Elbahja

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

    Reply
  50. Lawrence

    Vivek,
    Is there a way to zoom out, so the person’s picture and background is covered.

    Reply
  51. reno

    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…

    Reply
      1. reno

        i’m using IP camera, can this script run like in webcam device????

        Reply
  52. Mani

    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.

    Reply
  53. Harminder Singh

    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.

    Reply
    1. Vivek Moyal Post author

      I dont get that what is Desktop …… and code is running without any problems. Could you send me the screenshot of error

      Reply
      1. Harminder Singh

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

        Reply
        1. Vivek Moyal Post author

          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

          Reply
          1. Harminder Singh

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

            Reply
            1. Vivek Moyal Post author

              I think you still missing some files please check it again because there is no any problem with the code as you can see the above comments too.

              Reply
              1. Harminder Singh

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

                Reply
                1. krish

                  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

                  Reply
  54. Harminder Singh

    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.

    Reply
  55. Ali

    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

    Reply
    1. Vivek Moyal Post author

      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

      Reply
      1. Ali

        Do you mind if I send you my code and you check it. I will be massively thankful.

        Reply
          1. Ali

            Thank you very much. I sent the zip file to ur Facebook inbox ,,, thanks again

            Reply
  56. ohio moving company

    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!

    Reply
  57. lucas coelho

    hello Vivek Moyal,… I from Brazil, please you can help me?I’m in trouble for saving.Your script is very nice!! Thanks so much.

    Reply
  58. alfan

    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?

    Reply
  59. Lawrence

    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

    Reply
  60. Lawrence

    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

    Reply
      1. Lawrence

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

        Reply
  61. yago_meitzen

    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

    Reply
    1. Vivek Moyal Post author

      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

      Reply
      1. yago_meitzen

        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

        Reply
        1. Vivek Moyal Post author

          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

          Reply
          1. yago_meitzen

            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 ^^

            Reply
            1. yago_meitzen

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

              Reply
              1. Vivek Moyal Post author

                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

                Reply
  62. Lawrence

    ok Vivek. , do I use the same function snap() in webcam.js to capture videos as well.

    Reply
  63. Lawrence

    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

    Reply
    1. Vivek Moyal Post author

      Yes you can use it but before using it just try to understand the code and its working so if you got any error than can handle it

      Reply
  64. sanjeev

    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’) );

    Reply
    1. Vivek Moyal Post author

      Under path only put the folder path not the whole computer folder path. It will just your image folder path nothing else.

      Reply
  65. Lawrence

    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.

    Reply
    1. Vivek Moyal Post author

      You have to take the permission first otherwise you cannot turn on the cam. After turning it on your snapshop function can work with settimeout

      Reply
  66. Lawrence

    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.

    Reply
    1. Vivek Moyal Post author

      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);

      Reply
  67. santhosh.G

    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 ?

    Reply
  68. swetha

    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.

    Reply
    1. Vivek Moyal Post author

      Hows it possible ??? It works on both and i also own Linux server and it works without any problem.

      Reply
  69. tryer

    Hi sir…how about the image element for the table entry? is it in BLOB format?

    Reply
  70. Hsin-Ju Chen

    I have a IP camera ,
    How to use IP address from same files.
    Many Thanks !!

    Reply
    1. Vivek Moyal Post author

      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

      Reply
      1. molay

        i chose the last one but, finally i solve it if you want can i share the code with the authors

        Reply
    1. Vivek Moyal Post author

      You are right if it will work it will be more easier for others try it bro i know you can do it.

      Reply
        1. Vivek Moyal Post author

          hahahahaha….. try it i will also try if i will succeed i will put the code here other wise you put. I know you will put first

          Reply
          1. molay

            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

            Reply
            1. Vivek Moyal Post author

              It is because you forgot to write the ID in your input field. As you are calling the getElementByID. But you forgot to denote the ID

              Reply
              1. molay

                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);
                });
                }

                Reply
                1. Vivek Moyal Post author

                  <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

                  Reply
                  1. molay

                    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);
                    });
                    }

                    Reply
                    1. Vivek Moyal Post author

                      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. Vivek Moyal Post author

      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

      Reply
      1. molay

        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

        Reply
        1. Vivek Moyal Post author

          Welcome…… If you get anything easier than this please let me know also so that others will get benefit also

          Reply
          1. molay

            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();
            }

            })

            }

            Reply
  71. sonu

    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!

    Reply
      1. stathis

        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!

        Reply
        1. Vivek Moyal Post author

          Hows it possible. It sows the error first time. Ok check your folder permissions are they have the permission to write or not

          Reply
          1. stathis

            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!

            Reply
                1. Vladimir

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

                  Reply
  72. molay

    if i want to to send teh value with jquery how can i do??

    Reply
    1. Vivek Moyal Post author

      Try to work over your code first than ask this if you get any error. Than i will help you to sort out the problem

      Reply
  73. molay

    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

    Reply
    1. Vivek Moyal Post author

      ya …. this value is for getting the ID so that we will enter the Image and form fields on the same Id

      Reply
      1. molay

        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

        Reply
        1. Vivek Moyal Post author

          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

          Reply
          1. molay

            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 );

            Reply
                  1. molay

                    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

                    Reply
                    1. Vivek Moyal Post author

                      If you want the name over the image than i dont have any idea about it. I thought you need to save the name in the database.

    2. Vivek Moyal Post author

      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

      Reply
  74. Bhavya

    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.

    Reply
    1. Vivek Moyal Post author

      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


        

      Reply
      1. Bhavya

        How to store the images of both the web cam in the database??

        Reply
        1. Vivek Moyal Post author

          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

          Reply
              1. Bhavya

                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??

                Reply
                1. Vivek Moyal Post author

                  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

                  Reply
                  1. Bhavya

                    I want to store it in 2 tables. How to do it???
                    It is not updating the first webcam photo.

                    Reply
                    1. Vivek Moyal Post author

                      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. Soumyarka Mondal

    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…

    Reply
    1. Vivek Moyal Post author

      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.

      Reply
  76. Vivek Moyal Post author

    My value is a session variable.please check that you have included the php file esle you will get the error

    Reply
  77. Asmat

    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 …..

    Reply
  78. Vivek Moyal Post author

    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.

    Reply
  79. Sekhar

    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

    Reply
  80. Sekhar

    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.

    Reply
  81. suma

    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

    Reply
    1. Vivek Moyal Post author

      My value is the value which is passed as session. Please check that your code is making the session or not

      Reply
  82. jigar

    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

    Reply
    1. Vivek Moyal Post author

      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

      Reply
      1. jigar

        thanku sir for ur response…….i work over it again….thanku again

        Reply
  83. Niko

    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
    “?

    Reply
  84. sumeet

    Hi vivek

    i want to attach multiple cams on one laptop using PHP can you please help me in that.

    Reply
    1. Vivek Moyal Post author

      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.

      Reply
  85. rehan

    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

    Reply
  86. take

    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..

    Reply
  87. Jestin V J

    Hi Vivek,
    Really good work…. Keep on scripting…. Good luck….

    Reply
  88. Vishwas

    Hi,
    Nice script….
    Please help me i want to make video and uploaded it on server. it’s possible with this script.

    Reply
  89. H.L Hanner

    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.

    Reply
    1. Vivek Moyal Post author

      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.

      Reply
      1. H.L Hanner

        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.

        Reply
          1. H.L Hanner

            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?

            Reply
            1. Vivek Moyal Post author

              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.

              Reply
              1. H.L.Hanner

                Thanks a lot. Now everything works great. I can also successfully implement it in my project.

                Reply
        1. govind

          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

          Reply
      2. chuks peterson

        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

        Reply
      3. Jitender

        Hi Vivek Sir,

        Please mail me the code. As I am not able to download here.

        Thanks sir.

        Regards,
        Jitender

        Reply
    2. andre

      Hi Vivek
      Thanks for the tutorial i am having getting a NetworkError: 500 Internal Server Error
      when submitting to the test.php

      Reply
      1. Vivek Moyal Post author

        For this you have top check your server ….. if localhost than check your xampp or wampp setting. I never got this kind of error in the script

        Reply

Leave a Reply

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