【问题标题】:Load video file to html5 player with php使用 php 将视频文件加载到 html5 播放器
【发布时间】:2015-09-30 16:01:32
【问题描述】:

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

情况

当他点击视频图标时,弹出窗口将会打开——这个动作:

 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>

弹出窗口可以工作,但视频不行。

问题:

我遇到了问题,因为我将视频存储在“/application/help/videos”中。此路径被禁止,您不能在浏览器中调用此 URL。如何使用 PHP(可以通过文件系统访问)从这个受限区域加载视频到我的视频播放器

我需要类似的东西:

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

这可能吗?

【问题讨论】:

  • 你的路径是/application/files/help/tutorial_videos/application/help/videos ?
  • 没关系——有限制,很重要。
  • 也许this 是你想要的?然后进行相应修改以授予对其他视频的访问权限...

标签: javascript php html video


【解决方案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();

【讨论】:

  • 此方法是否适用于 HTML5 播放器(视频标签)?
  • 这在处理大文件时非常适合我(对于大于 2GB 的文件,您必须运行 x64 系统,否则 fopen + f*** 函数会失败)。 set_time_limit() 应该放在循环之外 ;)
  • 花了两天时间寻找这个,效果很好
【解决方案2】:

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

这是用于 PHP 视频流的很棒的 PHP 类:

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

这就是我所需要的。

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-04-05
      • 2017-04-18
      • 2020-07-24
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-21
      • 1970-01-01
      相关资源
      最近更新 更多