使用 php 在创建文件路径的文件夹中上传图像

Uploading image in folder creating file path using php

使用Photo Booth by vamapaull 我正在尝试在 folder.with 中捕获图像,我的 sql 它工作正常但将其更改为我的 sql 我无法 upload.webcam 拍摄快照但不存储图像文件夹。 (在 wamp 上)。正在从存储的图像 ID 明智的输出中寻找幻灯片放映。

 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.

与其依赖过时且很快就会被遗忘的技术,例如 Flash,您可以考虑使用一些新的(?)HTML5 方法 - 现在有大量的网络 API Javascript 使多媒体设备的使用相对简单并且具有相当好的跨浏览器支持的核心。

以下两个脚本(可以合并为一个)应该让您了解如何使用上述技术完成您的任务 - 将数据保存到数据库的部分使用 prepared statement,因此应该sql 注入的风险并不像您的原始失败代码那样大。

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

?>

是时候承认失败了——我无法在 IE11 上使用上述方法(尽管我相信 Github, webRTC4all or Temasys WebRTC 上有可用的 polyfill,但我已经尝试了其中的 none。我'我确定其他地方会有其他 polyfill。

早在 90 年代早期,当 Internet Explorer 在浏览器市场占据主导地位时,我们曾经喜欢为 IE 编写代码,并且总是发现 Netscape Navigator 会抛出各种错误 - 现在虽然它是角色转换。