phpmysqliwebcamwebcam-capturewebcam.js

Uploading image in folder creating file path using php


Using Photo Booth by vamapaull i am trying to capture image in folder.with my sql it was working fine but changing it to mysqli not able to upload.webcam takes snap but does not store image folder.(on wamp).Looking for slide show in output from stored images ID wise.

 Table name  uploadimages ::   ID   Name    image   user_id 
    veiw.php
============================
<script type="text/javascript">
    hs.graphicsDir = 'graphics/';
    hs.align = 'center';
    hs.transitions = ['expand', 'crossfade'];
    hs.wrapperClassName = 'dark borderless floating-caption';
    hs.fadeInOut = true;
    hs.dimmingOpacity = .75;

    // Add the controlbar
    if (hs.addSlideshow) hs.addSlideshow({
        //slideshowGroup: 'group1',
        interval: 5000,
        repeat: false,
        useControls: true,
        fixedControls: 'fit',
        overlayOptions: {
            opacity: .6,
            position: 'bottom center',
            hideOnMouseOut: true
        }
    });
</script>
<script src="swfobject.js" language="javascript"></script>
        <script type="text/javascript">
            var flashvars = {};

            var parameters = {};
            parameters.scale = "noscale";
            parameters.wmode = "window";
            parameters.allowFullScreen = "true";
            parameters.allowScriptAccess = "always";

            var attributes = {};

            swfobject.embedSWF("take_picture.swf", "main", "700", "400", "9", 
                    "expressInstall.swf", flashvars, parameters, attributes);
        </script>

        <script type="text/javascript">
            var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
            document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
        </script>

        <script type="text/javascript">
            var pageTracker = _gat._getTracker("UA-3097820-1");
            pageTracker._trackPageview();
        </script>
        <script type="text/javascript">
    var mainswf = new SWFObject("take_picture.swf", "main", "600", "400", "9", "#ffffff");
    mainswf.addParam("scale", "noscale");
    mainswf.addParam("wmode", "window");
    mainswf.addParam("allowFullScreen", "true");
    //mainswf.addVariable("requireLogin", "false");
    mainswf.write("flashArea");

 </script>

php code

<?php
    session_start();
    //This project is done by vamapaull: http://blog.vamapaull.com/
    include_once('db.php');
    if(isset($GLOBALS["HTTP_RAW_POST_DATA"])){
        $jpg = addslashes($GLOBALS["HTTP_RAW_POST_DATA"]);
        $img = addslashes($_GET["img"]);
        //$id= $_GET["id"];
        $vid=$_SESSION['vid'];
        //$image =addslashes(file_get_contents($_FILES["img"]["tmp_name"]));
        //$image_name = addslashes($_FILES["image"]["name"]);
        $filename = "images/poza_". mktime(). ".jpg";
        file_put_contents($filename, $jpg);
        mysqli_query($db  ,"INSERT INTO uploadimages (Name,image,user_id) VALUES ('$filename','$jpg','$vid')")or die(mysqli_error($db));
        } else{
        echo "Encoded JPEG information not received.";
    }
    ?>

 -------------------------
 Other files can be seen at link given 
http://vamapaull.com/photo-booth-flash-webcam-image-capture/  This how directory looks like.image attached.

Directory looks like this


Solution

  • Rather than rely upon an outdated and soon to be forgotten technology such as Flash you might consider using some of the new(?) HTML5 methods - there are plenty of web apis now in Javascript core that make working with multimedia devices relatively straightforward and have fairly good cross-browser support.

    The following two scripts ( could be rolled into one ) should give an idea how you could accomplish your mission using said technologies - and the portion that saves the data to the database uses a prepared statement so there should be no significant risk of sql injection as was possible with your original, failing, code.

    <!--
        html5_snapshot.php
        ------------------
    -->
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset='utf-8'>
            <title>Webcam snapshots</title>
            <style>
                body{
                    padding:3em;    
                }
                #media,
                #buttons,
                #results{
                    box-sizing:border-box;
                    width:80%;
                    margin:1rem auto;
                    float:none;
                    text-align:center;
                }
                video,canvas{
                    margin:2rem auto;
                    border:1px solid black;
                    border-radius:10px;
                    display:inline-block;
                    position:relative;
                    float:none;
                    clear:none;
                    width:320px;
                    height:240px;
                }
                h1{
                    text-shadow: 1px 1px 2px black, 0 0 1em blue, 0 0 0.2em blue;
                    color: white;
                    width:80%;
                    margin:0 auto 0 auto!important;
                    float:none;
                    font: 1.5em verdana;
                    text-align:center;
                }
                #results{
                    font-size:0.7rem;
                }
            </style>
            <script>
                window.addEventListener('DOMContentLoaded', function(e) {
                    ( function() {
                        /* edit path to suit */
                        var handler='html5_snapshot_handler.php';
                        /* establish main variables */
                        var streaming   =   false,
                          oSave         =   document.getElementById('save'),
                          oClear        =   document.getElementById('clear'),
                          oGrab         =   document.getElementById('grab'),
                          video         =   document.getElementById('video'),
                          canvas        =   document.getElementById('canvas'),
                          width = 640,
                          height = 480;
    
                        var basicOptions={
                            video: true,
                            audio: false
                        };
                        /* callback for previous method-no longer used
                        function gotvideo(stream){
                            if( navigator.mozGetUserMedia ) {
                                video.mozSrcObject = stream;
                            } else {
                                var vendorURL = window.URL || window.webkitURL;
                                video.src = vendorURL.createObjectURL( stream );
                            }
                            video.play();
                        }
                        */
                        function report( msg ){
                            var ctx=canvas.getContext('2d');
                                ctx.font='2em verdana';
                                ctx.fillStyle='red';
                                ctx.textAlign='center'; 
                                ctx.textBaseline='middle';
                                ctx.fillText( msg, Math.abs( canvas.width * 0.5 ), Math.abs( canvas.height * 0.5 ) );
                            console.warn( msg );
                        }
                        function setproperties(e){
                            if( !streaming ) {
                                video.width=width;
                                video.height=height;
                                canvas.width=width;
                                canvas.height=height;
                                streaming = true;
                            }
                        }
                        function takepicture(e) {
                            e.preventDefault();
                            var ctx=canvas.getContext('2d');
                                ctx.drawImage( video, 0, 0, width, height );
                        }
                        function cbsaveimage( evt ){
                            /*
                                The ajax callback function - currently only shows 
                                the returned json data but could do something 
                                much more useful
                            */
                            document.getElementById('results').innerHTML=( this.status == 200 ) ? this.response : 'error: '+this.status;    
                        }
                        function saveimage(e){
                            var el=e.target;
                            var data=canvas.toDataURL('image/png').replace(/^data:image\/(png|jpg);base64,/, '');
    
    
                            if( !isBlankCanvas( canvas ) ){
                                var fd=new FormData();
                                    fd.append( 'data', data );
    
                                var req = new XMLHttpRequest();
                                    req.addEventListener('load', cbsaveimage, false );
                                    req.open( 'POST', handler, true );
                                    req.send( fd );
    
                            } else {
                                var bttns=[ oSave, oGrab, oClear ];
    
                                bttns.forEach( function(e,i,a){
                                    e.disabled=true;
                                });
                                setTimeout( function(){
                                    bttns.forEach( function(e,i,a){
                                        e.disabled=false;
                                    });
                                    canvas.getContext('2d').clearRect( 0,0, width, height );
                                },2500 );
    
                                report( 'Nothing to upload' );
                            }
                        }
                        function clearcanvas(evt){
                            canvas.getContext('2d').clearRect( 0,0, width, height );
                        }
                        function isBlankCanvas( canvas ) {
                            var blank=document.getElementById('empty');
                                blank.width=canvas.width;
                                blank.height=canvas.height;
                            return canvas.toDataURL() == blank.toDataURL();
                        }
    
    
                        /* Listeners */
                        oSave.addEventListener( 'click', saveimage, false );
                        oClear.addEventListener( 'click', clearcanvas, false );
                        oGrab.addEventListener( 'click', takepicture, false );
                        video.addEventListener( 'canplay', setproperties, false );
    
                        /*
                            navigator.getMedia = ( navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia );
                            navigator.getMedia( basicOptions, gotvideo, report );
    
                            The above method is deprecated ( still works in certain browsers however )
                            but neither the above or the newer method below will work in Internet Exploder
                            The below should work in Firefox,Chrome & Opera.
    
                        */
    
                        try{
                            navigator.mediaDevices.getUserMedia( basicOptions ) .then( function( stream ) {
                                video.srcObject = stream;
                                video.onloadedmetadata = function(e) {
                                    video.play();
                                };
                            }).catch( function( err ) { console.log( err.name + ": " + err.message ); } );
                        }catch( error ){
                            console.log( error );
                        }
    
                    })();
                },false );
            </script>
        </head>
        <body>
            <h1>Webcam snapshots</h1>
            <div id='media'>
                <video id='video'></video>
                <canvas id='canvas'></canvas>
                <canvas id='empty' style='display:none' width=100 height=100></canvas>
            </div>
            <div id='buttons'>
                <input type='button' id='grab' value='Take snapshot' />
                <input type='button' id='save' value='Save Snapshot' />
                <input type='button' id='clear' value='Clear canvas' />
            </div>
            <pre id='results'></pre>
        </body>
    </html>
    
    
    <?php
        /*
    
            html5_snapshot_handler.php
            --------------------------
        */
    
        session_start();
    
        if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['data'] ) ) {
            /* variable to register if db call is successful or not */
            $result=false;
    
            /* As the image does not have a name, create a name of some sort */
            $filename=uniqid('snapshot').'_'.time().'.png';
    
            /* The path on the server where the upload is to be stored. */
            $uploadpath='c:/temp/fileuploads/2/';
    
            /* Final path for uploaded image */
            $filepath=$uploadpath . $filename;
    
            /* Get the file "data" */
            $data = filter_input( INPUT_POST, 'data', FILTER_SANITIZE_SPECIAL_CHARS );
    
            /* write to a new file */
            $bytes = file_put_contents( $filepath, base64_decode( $data ) );
    
            /* Save to database */
            $dbhost =   'localhost';
            $dbuser =   'root'; 
            $dbpwd  =   'xxx'; 
            $dbname =   'stack';
    
            $db =   new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
            $sql='insert into `uploadimages` (`name`,`image`,`user_id`) values (?,?,?);';
            $stmt=$db->prepare( $sql );
            if( $stmt ){
                $stmt->bind_param('ssi', $name, $image, $uid );
                /*
                    It would be wise to store just the path to the image
                    as the file is being uploaded anyway so you do not need
                    to store a BLOB - over time it would take up a huge 
                    amount of diskspace on the database server
                */
                $name=$filename;
                $image=$filepath;
                $uid=$_SESSION['vid'];
    
                $result = $stmt->execute();
                $stmt->free_result();
                $stmt->close();
                $db->close();
            }
    
            /* send something back to the client - callback */
            header( 'Content-Type: application/json' );
            exit( json_encode( array(
                'filename'  =>  $filename,
                'filepath'  =>  $filepath,
                'filesize'  =>  $bytes,
                'status'    =>  realpath( $filepath ) ? 1 : 0,
                'db'        =>  $result
            ) ) );
        }
    
    
        /* If the request is other than POST - report an error */
        exit( header( 'HTTP/1.1 404 Not Found', true, 404 ) );
    
    ?>
    

    Time to admit defeat - I have not been able to get the above working with IE11 ( though I believe there are polyfills available on Github, webRTC4all or Temasys WebRTC but I have tried none of those. I'm sure there will be other polyfills elsewhere.

    Back in the early 90's when Internet Explorer held the dominant position in the browser market we used to love coding for IE and always found that Netscape Navigator threw all sorts of errors - now though it is a role reversal.