使用php将视频文件加载到html5播放器

时间:2015-09-30 16:01:33

标签: javascript php html5 video

我对视频没什么问题。我刚创建了用户将在每个页面上看到的服务,只为我们的应用程序提供一个帮助视频。

状况

当他点击视频图标时,弹出窗口将会打开 - 此操作:

 var getVideoModal = function (video) {
  var path = '/application/files/help/tutorial_videos/'+video;
  $('div#modal-video').modal('show');
  $("#modal-video").draggable({
    handle: ".modal-header"
  });
  $('h3#modal-header-video').html(video);
  console.log(path);
  $("#video-help").find("#videoPath").attr("src", path);
  centerModal();
}

当弹出窗口打开时,弹出体中有<video> html5元素

  <video id="video-help" width="530" controls>
    <source id="videoPath" src="" type="video/mp4">
  </video>

弹出工作,但视频没有。

问题:

我遇到问题,因为我的视频存储在&#34; / application / help / videos &#34;中。禁止使用此路径,您无法在浏览器中调用此URL。如何使用PHP(可通过文件系统访问)将视频从此受限区域加载到我的视频播放器

我需要类似的东西:

  <video id="video-help" width="530" controls>
        <source id="videoPath" src="whatever.php?video=loaded.mp4" type="video/mp4">
  </video>    

这可能吗?

3 个答案:

答案 0 :(得分:1)

您可以有效地使用PHP从受限制的文件夹访问中发送视频数据。打开,读取文件并发送数据。

如果用户通过按范围发送数据来移动播放器时间轴,您也可以使其正常工作。下面的代码可以做到:

    $my_video_basename = //filter to have a trust filename

    $file = "/application/help/videos" . $my_video_basename;

    if(!file_exists($file)) return; 

    $fp = @fopen($file, 'rb');      
    $size   = filesize($file); // File size 
    $length = $size;           // Content length
    $start  = 0;               // Start byte
    $end    = $size - 1;       // End byte  
    header('Content-type: video/mp4');
    header("Accept-Ranges: 0-$length");
    header("Accept-Ranges: bytes"); 
    if (isset($_SERVER['HTTP_RANGE'])) {
        $c_start = $start;              
        $c_end   = $end;                
        list(, $range) = explode('=', $_SERVER['HTTP_RANGE'], 2);
        if (strpos($range, ',') !== false) {
            header('HTTP/1.1 416 Requested Range Not Satisfiable');
            header("Content-Range: bytes $start-$end/$size");
            exit;      
        }              
        if ($range == '-') {            
            $c_start = $size - substr($range, 1);
        }else{         
            $range  = explode('-', $range); 
            $c_start = $range[0];           
            $c_end   = (isset($range[1]) && is_numeric($range[1])) ? $range[1] : $size;
        }
        $c_end = ($c_end > $end) ? $end : $c_end;
        if ($c_start > $c_end || $c_start > $size - 1 || $c_end >= $size) { 
            header('HTTP/1.1 416 Requested Range Not Satisfiable');
            header("Content-Range: bytes $start-$end/$size");
            exit;      
        }
        $start  = $c_start;             
        $end    = $c_end;               
        $length = $end - $start + 1;    
        fseek($fp, $start);             
        header('HTTP/1.1 206 Partial Content');
    }                  
    header("Content-Range: bytes $start-$end/$size");
    header("Content-Length: ".$length);
    $buffer = 1024 * 8;
    while(!feof($fp) && ($p = ftell($fp)) <= $end) { 
        if ($p + $buffer > $end) {      
            $buffer = $end - $p + 1;        
        }              
        set_time_limit(0);              
        echo fread($fp, $buffer);       
        ob_flush();    
    }
    fclose($fp);       
    exit();

答案 1 :(得分:1)

好的,我找到了解决方案(PHP)。

这是PHP中用于视频流的优秀PHP类:

http://codesamplez.com/programming/php-html5-video-streaming-tutorial

这就是我需要拥有的一切。

注意:您需要支持HTML5格式的视频 - 我正在使用OGG - &gt; sample.ogv

答案 2 :(得分:0)

为前端用户播放/停止视频的后端控制器仪表板

 <?php 
include 'conf.php';


    $sql="SELECT * FROM videos";
    $result=mysqli_query($conn,$sql);
    $file=mysqli_fetch_all($result,MYSQLI_ASSOC);



    $sqlnew="SELECT * FROM videos where Vid_is_active='Yes'";
    $resultnew=mysqli_query($conn,$sqlnew);
    $filenew=mysqli_fetch_all($resultnew,MYSQLI_ASSOC);

?>  
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>


<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>



<script type="application/javascript">

var existData = '<?php echo @$filenew[0]['Vid_is_active']; ?>'; 
var existId = '<?php echo @$filenew[0]['Vid_id']; ?>';
$(document).ready(function () {   
    $(document).on('click', ".table .btn", function (e) {       
        $('#bsModal2').modal('show');
        e.preventDefault();
        id = $(this).attr('id')
        valu = $(this).val()

        if(valu==='Yes'){
        $(".stp_" + id).show();
        $(".btn-str").hide();
        }
        if(valu==='No'){
        $(".btn-str").show();
        $(".stp_" + id).hide();
        window.location.reload();
        //return false;
        }

    //return false; 
    if(existData==valu){
        $('#bsModal').modal('show');
        return false;

    }else{
        $.ajax({  
                url: 'http://localhost:8080/Ashish/VD/update.php',  
                type: 'POST',  
                dataType: 'json',  
                data: {"id": id,"value":valu},
                success: function (resultData) {  
                    console.log(resultData);
                    //update duration   
                    //window.location.reload();
                    if(valu=='Yes') {               
                     duartionupdat(id,valu);
                    }
                     //window.location.reload();

                }, 
                error: function (xhr, textStatus, errorThrown) {  
                    console.log('Error in Operation');  
                }  
            }); 
    }

    });


    function duartionupdat(id,valu){
        //alert(valu);
        var counter = 0;
            setInterval(function(){     
        counter++;          
                $.ajax({  
                url: 'http://localhost:8080/Ashish/VD/updateduration.php',  
                type: 'POST',  
                dataType: 'json',  
                data: {"id": id,"value":counter},
                success: function (resultData) {  
                }, 
                error: function (xhr, textStatus, errorThrown) {  
                    console.log('Error in Operation');  
                }  
            });     
        }, 1000);
    }

});

</script>   
                <div class="example" style="width: 221px;  background-color: #2faede;    margin: 2px 1202px 0;">
                <h3 class="txt" style="margin: 3px 65px -34px; color: white;">Shuffle</h3>
                <input id="toggle-event" type="checkbox" data-toggle="toggle" data-onstyle="success" data-offstyle="danger">
                <!--<div id="console-event"></div>-->
                <script>
                    $(function() {
                        $('#toggle-event').change(function() {
                        var t =$(this).prop('checked');
                        alert(t);
                        if(t==true){    
                        $(".example").css('background-color','green')
                        $(".txt").css('color','white')
                        }else{
                            $(".example").css('background-color','red')
                            $(".txt").css('color','white')
                        }


                            //$('#console-event').html('Toggle: ' + $(this).prop('checked'))
                        })
                    })
                </script>
            </div>          



 <div class="modal fade" id="bsModal2" tabindex="-1" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content" style="background-color: #e0fde0;">
            <div class="modal-header" style="margin: 10px 10px 11px;">
                <button type="button"  style="margin: -47px -43px 0px;"  class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4  style="margin: 0px 24px 15px;" class="modal-title" id="myModalLabel">Video Started!! Do not Refresh the page after play video!</h4>
            </div>   
        </div>
    </div>
</div>
<table class="table">
  <thead>
    <tr>
      <th scope="col">Sr.No.</th>
      <th scope="col">Video</th>
      <th scope="col">Name</th>
      <!--<th scope="col">Path</th>-->
      <th scope="col">Action</th>
    </tr>
  </thead>
  <tbody>
    <?php 
  $i=1;
  foreach($file as $files){  
  $video = $files['Vid_path']. $files['Vid_name'];

  ?>
    <tr>
      <th scope="row"><?php echo $i;  ?></th>
      <td><video style="background-color: #2faede;" id="myVideo" width='100' height='50'  ><source id="source_video" src="<?php echo $video  ?>" type="video/mp4"></video>

      </td>
      <td><?php echo $files['Vid_name'];  ?></td>
      <!--<td><?php echo $files['Vid_path'];  ?></td>-->
      <td>
        <button type="button" value="Yes" id="<?php echo $files['Vid_id'];  ?>"
          class="btn btn-str btn-success str_<?php echo $files['Vid_id']; ?>">Start</button>


        <button value="No" style="display:none;" id="<?php echo $files['Vid_id'];  ?>" type="button"
          class="btn btn-stp btn-danger stp_<?php echo $files['Vid_id']; ?>">Stop</button>
      </td>
    </tr>
    <?php
$i++;
} 

 ?>
  </tbody>
</table>

端视频播放器

<?php 
    include 'conf.php';

    $sql="SELECT * FROM videos where  Vid_is_active='Yes'";
    $result=mysqli_query($conn,$sql);
    $file=mysqli_fetch_all($result,MYSQLI_ASSOC);
    $filename= @$file[0]['Vid_name'];

?>  

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script type="application/javascript">
      window.onload = function() {    
        setInterval(function(){ 
                $.ajax({  
                    url: 'http://localhost:8080/Ashish/VD/api.php',  
                    type: 'POST',  
                    dataType: 'json',  
                    data: 'Yes',  
                    success: function (resultData) {  
                        console.log(resultData); 
                        var path  =resultData[0]['Path'];
                        var vName = resultData[0]['videoName'];
                        var duration  =resultData[0]['duration'];
                        console.log(resultData);
                        if(resultData[0]['Status']==false){
                            //alert('Stoped');
                            window.location.reload();
                        }else{
                        $("#myVideo").html('<source id="source_video" src="'+path+vName+'" type="video/mp4">');

                        document.getElementById("myVideo").currentTime = duration;
                        //window.location.reload();

                        }

                    }, 
                    error: function (xhr, textStatus, errorThrown) {  
                        console.log('Error in Operation');  
                    }  
                });  

            }, 2000);

    }  
    </script>

                        <div class='row'>
                            <div class='column'>
                                <div class='card'>                          
                                    <video id="myVideo" width='1410' height='710'  autoplay ></video>
                                </div>
                            </div>
                        </div>

API.php

    include 'conf.php';
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
    header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With');
    header('Access-Control-Allow-Credentials: true'); 


        $query='Select * from videos  where Vid_is_active="Yes"';
        $result=mysqli_query($conn,$query);
        $file=mysqli_fetch_all($result,MYSQLI_ASSOC);
        $result=array();

        if(!empty($file)){
        //echo $sql;die;
        $result[] = array('duration'=>$file[0]["duration"],'id'=>$file[0]["Vid_id"],'Status'=>$file[0]["Vid_status"],'Path'=>$file[0]["Vid_path"],'videoName'=>$file[0]["Vid_name"] ,'message' => 'Video List');
        }else{

        $result[]=array('Status'=>false, 'message'=>'No vidoes are Active');    
        }
        echo json_encode($result);

Update.php

    include 'conf.php';
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With');
header('Access-Control-Allow-Credentials: true'); 





    $sql="SELECT * FROM videos where Vid_is_active='Yes'";
        $result=mysqli_query($conn,$sql);
        $file=mysqli_fetch_all($result,MYSQLI_ASSOC);

    if($_POST['value']=='Yes'){


           $query='UPDATE videos SET Vid_status = "Started" , Vid_is_active="'.$_POST["value"].'" WHERE Vid_id ='.$_POST["id"].''; 
        }else{
         $query='UPDATE videos SET Vid_status = "Stop" , duration=0, Vid_is_active="'.$_POST["value"].'" WHERE Vid_id ='.$_POST["id"].'';
        }
        //echo $query;die;

        $result=mysqli_query($conn,$query);
        $results=array();
        $results[] = array('id'=>$_POST["id"],'Message'=>'Updated');

        echo json_encode($results);

Updateduration.php

    include 'conf.php';
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, Accept, Authorization, X-Request-With');
header('Access-Control-Allow-Credentials: true'); 

    $query='UPDATE videos SET duration ='.$_POST["value"].'  WHERE Vid_id ='.$_POST["id"].'';
    $result=mysqli_query($conn,$query);
    $results=array();
    $results[] = array('id'=>$_POST["id"],'Message'=>'Duration Updated');
    echo json_encode($results);