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

Javascript 使用php将视频文件加载到html5播放器,javascript,php,html,video,Javascript,Php,Html,Video,我对视频没什么问题。我刚刚创建了一个服务,用户可以在每个页面上看到,我们的应用程序只有一个帮助视频 形势 当他点击视频图标时,弹出窗口将打开-此操作: var getVideoModal = function (video) { var path = '/application/files/help/tutorial_videos/'+video; $('div#modal-video').modal('show'); $("#modal-video").draggable({

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

形势

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

 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();
}
当弹出窗口打开时,(在弹出窗口主体中)有
html5元素

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

弹出窗口正在工作,但视频不工作

问题:

我有问题,因为我的视频存储在“/应用程序/帮助/视频”中。此路径被禁止,您无法在浏览器中调用此URL。如何使用PHP(通过文件系统可以访问)将此受限区域的视频加载到视频播放器

我需要像这样的东西:

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


这可能吗

您可以有效地使用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();
$my\u video\u basename=//筛选以获得信任文件名
$file=“/application/help/videos”$我的视频基本名称;
如果(!file_存在($file))返回;
$fp=@fopen($file,'rb');
$size=filesize($file);//文件大小
$length=$size;//内容长度
$start=0;//起始字节
$end=$size-1;//结束字节
标题(“内容类型:视频/mp4”);
标题(“接受范围:0-$length”);
标题(“接受范围:字节”);
如果(isset($\u服务器['HTTP\u范围]])){
$c_start=$start;
$c_end=$end;
列表(,$range)=分解('=',$服务器['HTTP\u range'],2);
if(strpos($range,,')!==false){
标头(“HTTP/1.1 416请求的范围不可满足”);
标题(“内容范围:字节$start-$end/$size”);
出口
}              
如果($range='-'){
$c_start=$size-substr($range,1);
}否则{
$range=分解('-',$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;
如果($c|u start>$c|u end |$c|u start>$size-1 |$c|u end>=$size){
标头(“HTTP/1.1 416请求的范围不可满足”);
标题(“内容范围:字节$start-$end/$size”);
出口
}
$start=$c_start;
$end=$c_end;
$length=$end-$start+1;
fseek($fp,$start);
标题(“HTTP/1.1 206部分内容”);
}                  
标题(“内容范围:字节$start-$end/$size”);
标题(“内容长度:.$Length”);
$buffer=1024*8;
而(!feof($fp)&($p=ftell($fp))$end){
$buffer=$end-$p+1;
}              
设置时间限制(0);
echo-fread($fp,$buffer);
ob_flush();
}
fclose($fp);
退出();

好了,伙计们,我找到了soloution(PHP)

下面是一个很棒的PHP类,用于PHP中的视频流:

这就是我所需要的


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

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

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


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

你的路径是
/application/files/help/tutorial\u videos/
application/help/videos
?这不重要-是受限制的,这很重要。也许这就是你想要的?然后进行相应修改,以授予对其他视频的访问权限…此方法是否适用于HTML5播放器(视频标签)?在处理大文件时,此方法非常适合我(对于大于2GB的文件,必须运行x64系统,否则fopen+f***功能将失败)。
设置时间限制()花两天时间寻找这个,效果非常好
    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);