PHP - Stream Mp4 Files To Html5 <video>
Evening Everyone,
Been working on this problem for a couple of days and I am stumped. I have a single php file to handle download and streaming of files. It works great with music files, I can download and stream to an <audio> html 5 element just fine. When it comes to my movies, I can download fine but it fails on streaming to a <video> html 5 element. I have done some logging and it looks like after a very short time it just quits.
log when streaming music:
/path/to/music/124 - Mouth Techno -1.mp3 size: 1508731 ctype: audio/mpeg range: 0-1508730/1508731 write chunk: 8192-1508731 write chunk: 16384-1508731 .... write chunk: 1507328-1508731 write chunk: 1515520-1508731 completedlog when streaming movie - this is the complete output, it just stops: Log Started /path/to/movies/AVP_REQUIEM_UNRATED.Title1.DVDRip.mp4 size: 889628920 ctype: video/mp4 range: 0-889628919/889628920 write chunk: 8192-889628920 write chunk: 16384-889628920 write chunk: 24576-889628920 write chunk: 32768-889628920 write chunk: 40960-889628920 write chunk: 49152-889628920 write chunk: 57344-889628920 write chunk: 65536-889628920Here is how I am downloading and streaming the files. Music files work just fine with <audio>, movie files I can only download but want to stream with <video>. This is a hack from multiple sources on the net. <?php // sanitize the file request, keep just the name and extension $filename = $filefix = str_replace('%20', ' ', $_GET["name"]); $file_path = $filename; $path_parts = pathinfo($file_path); $file_dir = $path_parts['dirname']; $file_name = $path_parts['basename']; $file_ext = $path_parts['extension']; $path_default = "/path/to/music/"; $path_types = array( "mp3" => "/path/to/music/", "mpg" => "/path/to/movies/", "avi" => "/path/to/movies/", "mp4" => "/path/to/movies/", ); $path = isset($path_types[$file_ext]) ? $path_types[$file_ext] : $path_default; $file_path = "$path"."$filename"; clearLog(); startLog(); writeLog("$file_path\n"); // allow a file to be streamed instead of sent as an attachment $is_attachment = isset($_GET["play"]) ? false : true; // make sure the file exists if (is_file("$file_path")){ $file_size = filesize($file_path); $file = @fopen($file_path,"rb"); writeLog("size: $file_size\n"); if ($file){ header("Expires: -1"); header("Cache-Control: public, must-revalidate, post-check=0, pre-check=0"); // set appropriate headers for attachment or streamed file if ($is_attachment){ header("Content-Disposition: attachment; filename=\"$file_name\""); }else{ header('Content-Disposition: inline;'); } // set the mime type based on extension. $ctype_default = "application/octet-stream"; $content_types = array( "exe" => "application/octet-stream", "zip" => "application/zip", "mp3" => "audio/mpeg", "mpg" => "video/mpeg", "avi" => "video/x-msvideo", "mp4" => "video/mp4", ); $ctype = isset($content_types[$file_ext]) ? $content_types[$file_ext] : $ctype_default; header("Content-Type: " . $ctype); writeLog("ctype: $ctype\n"); $end = ($file_size - 1); $start = 0; header("Content-Length: $file_size"); header('Accept-Ranges: bytes'); header("Content-Range: bytes $start-$end/$file_size"); writeLog("range: $start-$end/$file_size\n"); $a=0; while(!feof($file)) { $chunk = (1024*8); echo fread($file, $chunk); //ob_flush(); flush(); $a=$a+$chunk; writeLog("write chunk: $a-$file_size\n"); if (connection_status()!=0){ writeLog("failed\n"); fclose($file); exit; } } // file save was a success writeLog("completed\n"); fclose($file); exit; }else{ // file couldn't be opened header("HTTP/1.0 500 Internal Server Error"); exit; } }else{ // file does not exist header("HTTP/1.0 404 Not Found"); exit; } function startLog(){ $myfile = fopen("newfile.txt", "w"); fwrite($myfile, "Log Started\n"); fclose($myfile); } function writeLog($pstr) { $myfile = fopen("newfile.txt", "a"); fwrite($myfile, $pstr); fclose($myfile); } function clearLog() { //fclose("newfile.txt"); unlink("newfile.txt"); } ?>incase it helps, code calling download.php <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <link rel="stylesheet" type="text/css" href="movies.css"> </head> <body> <a href="javascript:history.back()"><img src="pics/back.png" style=\"height:50px; width=50px;\"/></a> <a href="index.html"><img src="pics/home.png" style="height:50px; width=50px;display: in-line;"/></a> <div id="searchContainer" style="height: 40px; width = 700px; display: block; padding: 10px;"> <input type="text" id="SearchString" placeholder="Enter Search Address" style="vertical-align: top;padding: 10px;" class="valid"> <button name="btnSearch" id="btnSearch" type="button"></button> </div> <div id="Mainbox" > <div id="ItemList"> <ol id="List"> <?php $dir = '/path/to/movies/'; $dirlist = array_diff(scandir($dir), array('..', '.','Thumbs.db')); asort($dirlist); $a=0; foreach ($dirlist as $file) { $size = round(filesize('/path/to/movies/'.$file)/1048576); $filefix = str_replace(' ', '%20', $file); echo "<li><div class=\"item\" id=\"$a\">"; //title echo "<div id=\"title\">$file</div>"; echo "<div id=\"mb\">$size MB</div>"; echo "<div id=\"dl\"><a href=\"download.php?name=$filefix\"><img src=\"pics/download.png\" style=\"height:25px; width=25px;\"/></a></div>"; if ($size < 1500){ $url = 'download.php?name='.$filefix.'&play=true'; echo "<div id=\"play\" data-value=\"$url\"><a href=\"javascript:void(0)\" onClick=\"updateSource(this);\"><img src=\"pics/play.png\" style=\"height:25px; width=25px;\"/></a></div>"; } echo "</div></li>"; $a++; } ?> </ol> </div> </div> <div id="videocontainer"> <video id="video" controls> <source id="mp4movie" type="video/mp4"> <source src="movie.ogg" type="video/ogg" codecs="avc1.64001E, mp4a.40.2"> Your browser does not support the video tag. </video> </div> <script type="text/javascript"> function updateSource(element) { var dvalue = element.parentElement.getAttribute('data-value'); var video = document.getElementById('video'); var source = document.getElementById('mp4movie'); source.src=dvalue; video.load(); //call this to just preload the audio without playing video.play(); //call this to play the song right away } </script> </body> </html>Thanks for any help! Edited by AdrianHoffman, 27 September 2014 - 11:51 PM. Similar TutorialsI can search for videos by keyword and can fetch videos list from youtube using its api in php. I can fetch video title, description, thumbnail etc. but how can i fetch video url not like this -> youtube.com/watch?id=xyz...
Example: ytpak[dot]com
edited: please note all wmv files are not more than 10 or 20 seconds long. also their size is no more than 500kb. I have this following code that works for photos, but wish to alter this slightly so it will work for video files (wmv) getFtpImage.php Code: [Select] <? header('Content-Type: image/jpg'); $imgdir = '/home/mysite/ftpfolder'; readfile($imgdir . '/' . $_GET['file']); ?> index.php Code: [Select] $imgdir = '/home/mysite/ftpfolder'; // the directory, where your images are stored $allowed_types = array('png','jpg','jpeg','gif'); // list of filetypes you want to show $dimg = opendir($imgdir); while($imgfile = readdir($dimg)) { if(in_array(strtolower(substr($imgfile,-3)),$allowed_types)) { $a_img[] = $imgfile; sort($a_img); reset ($a_img); } } $totimg = count($a_img); // total image number for($x=0; $x < $totimg; $x++) { $size = getimagesize($imgdir.'/'.$a_img[$x]); // do whatever $halfwidth = ceil($size[0]/2); $halfheight = ceil($size[1]/2); ?><img src="getFtpImage.php?file=<? echo ($a_img[$x]); ?>" height="180"><? // echo 'name: '.$a_img[$x].' width: '.$size[0].' height: '.$size[1].'<br />'; } i have the images show to fill the screen and wish for the video page to do the same and with the videos you click the [play] in the center of the video image to play it like most videos play, not like the flash. i try this code. Code: [Select] <video width="320" height="240" controls="controls" autobuffer="autobuffer"> <source src="data:video/mp4;base64,AAAA<?php echo chunk_split(base64_encode(trim(file_get_contents('kecak.mp4')))); ?>" type="video/mp4" /> Your browser does not support the video tag. </video> it's work when i play in Notebook(safari, firefox) but not work when i play on IPAD2(safari) or Samsung Galaxy(Opera). i think the problem is in Code: [Select] src="data:video/mp4;base64,AAAA<?php echo chunk_split(base64_encode(trim(file_get_contents('kecak.mp4')))); ?>because when i replace with Code: [Select] src="kecak.mp4"it's work at all device and browser. i must use base64_encode(trim(file_get_contents('kecak.mp4'))) because in real my case it's come from response from RESTFul to delivery video via http. string response from http same with base64_encode(trim(file_get_contents('kecak.mp4'))). thanks u for help :-) We have a site that uses archived Realmedia video files, but we would like to have a automated way of converting those uploaded videos into seperate podcats for user download. Is there a way using PHP to do this? I have just started learning PHP and have no idea if this is even possible. The following will create a PHP stream. $response = $this->guzzleHttp->get($url); $stream = \GuzzleHttp\Psr7\StreamWrapper::getResource($response->getBody()); How can I return a stream using just PHP's native cURL library? Hi ! I'm trying to understand how php://input works. I've read the manual ( http://php.net/manual/en/wrappers.php.php ) and I have an example of a file upload receiving the file with php://input instead of $_FILES. But I can't understand it, does somebody a good tutorial about php://input ? What is the data inside it? is always the same that $HTTP_RAW_POST_DATA ? How can we send a file to PHP and receive it with php://input ? I'm trying to see what's inside php://input with this code: Code: [Select] $in = fopen("php://input", "rb"); echo Debug::vars($in); if ($in) { while ($buff = fread($in, 4096)) { echo $buff . EOL; // fwrite($out, $buff); } } but I get always blank output (Debug is a Kohana class and it returns: Quote resource(stream) php://input Thanks !! I am creating a stream for my website similar to facebook's news feed where users can post to, add photos too ect. When a user uploads a photo it gets added to the photos table and a new row to the stream Code: [Select] mysql_query("INSERT INTO photos VALUES ('','$id','$username','$photo','$time')"); mysql_query("INSERT INTO stream VALUES ('','$id','$username','$time','No comment','$photo','')"); Which displays the image on the stream fine but what i am looking to do is if the user uploads more images one after another instead of adding a new post to the stream for every picture i want to show all of the new pictures in one post like what Facebook does. I can't figure out how i would do this. Hi everybody, I'd like to protect a rtsp stream coming from a videoserver using a php page. Is this possible? The rtsp stream is a live h.264 stream with it's own local ip address. Currently i can access the stream by entering rtsp://192.168.1.3 in the browser and quicktime starts up. I have apache running on a different machine (192.168.1.2), which I want to use to pass on the stream. I'd like the rtsp stream to be accessed by entering rtsp://192.168.1.2/?password=changes-a-lot I've been using headers and readfile a lot to protect files. But the live stream seems to work differently. I've seen a lot of posts on how to access media using rtsp, but none of these work with a live stream. Does anybody have any ideas on how to get this to work? The other day I noticed someone had post something like this, well this was actually the solution to the problem. But it got me thinking about a project of mine that I am working on and the need to pump out a downloadable file. We are storing most of the files in a database using base64 encoding the 2 key types of files we are storing are images and PDF's mostly pdf's anyway where I am wanting to go with this is, is there anyway to take the base64 encoded file and get it to download through this, or am I tackling the idea in the wrong way? <?php $filename = 'somename.txt'; //this would obviously be changed according to the file type we would output $data =<<<DATA I know my data would go here for the given file once decoded. DATA; header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=' . $filename); header('Content-Transfer-Encoding: binary'); header('Expires: 0'); header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); header('Pragma: public'); header('Content-Length: ' . strlen($data)); echo $data; ?> I am trying to display an image stream from my pond cam... The stream generated by my ip video server is a jpeg stream without boundaries. Causeur of this the normal mime replace isn't working. I need php to read a picture from the stream, and display the picture in the browser while reading the next picture in the background. I've got to the point that I am able to connect to the stream, read the first image, and display it in the browser as can be seen in the link below (cam is only on from 09:00 until 16:00) http://cam.xsiteit.nl/readstream_test.php From this point I need to read the second image and replace the image in the browser with the new one. This process has to continu until the browser is closed. Any help would be great! Regards, Peter How can I decode the following contents?
Thanks a lot.
<html><head><meta http-equiv="Pragma" content="no-cache"/> <meta http-equiv="Expires" content="-1"/> I have my IP camera with the streaming URL :
http://x.x.x.x:81/li...user=admin&pwd=
Now i want to record the streaming using PHP . Now please anyone help how to do this ?
Any help would be appreciated .
Edited by ZohaibKhalid1, 17 October 2014 - 08:41 AM. Hi! I am having trouble reading a stream of data being sent to my PC via PHP5. It seems that my code stops when it gets to the read section and just sits there indefinately. I am somewhat new to PHP so a solution and explanation would be great! Code: [Select] <?php $host = "129.000.00.01"; // host IP address $port = 40000; // port to listen to // sets script execution limit set_time_limit(30); // 0 means unlimited execution time (constant running) // create UDP socket $socket = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP) or die("Could not create UDP socket!\n"); // reset socket for binding if(!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) { echo "Failed to reset socket!\n"; } else echo "Reset socket successfully!\n"; // bind socket socket_bind($socket, $host, $port); // connect if (!socket_connect($socket, $host, $port)) { echo "Failed to connect to port!\n"; } else echo "Connected to port successfully!\n"; while (1) { echo socket_read($socket, 1024, PHP_NORMAL_READ)."\n"; } // close sockets socket_close($socket); echo "\nDone"; I am trying to install a wordpress plugin called CiviCRM. I am using the GoDaddy wordpress dashboard to do this. I am getting this error (which is just the first error in a list of several that are appearing): Warning: require(/home/NAME/public_html/wordpress.SITE.com/wp-content/plugins/civicrm/civicrm/vendor/composer/../symfony/polyfill-ctype/bootstrap.php): failed to open stream: No such file or directory in /home/NAME/public_html/wordpress.SITE.com/wp-content/plugins/civicrm/civicrm/vendor/composer/autoload_real.php on line 70 I am looking at the code in file "autoload_real.php" and line 70 reads: require $file; nowhere else in this file is $file defined. the directory "/home/NAME/public_html/wordpress.SITE.com/wp-content/plugins/civicrm/civicrm/vendor/composer/" DOES exist, but the rest of the line "../symfony/polyfill-ctype/bootstrap.php" does not. there are also 3 other errors in eclipse that are indicated and all of those errors are "syntax error: unexpected 'Autoload()'. The 3 different lines of code that throw this error a 1) self::$loader = $loader = new \Composer\Autoload\ClassLoader(); 2) call_user_func(\Composer\Autoload\ComposerStaticInitdb2000479593e65ef23454e56d74a73f::getInitializer($loader)); 3) $includeFiles = Composer\Autoload\ComposerStaticInitdb2000479593e65ef23454e56d74a73f::$files; I'm not really sure what the issue is, as I'm not experienced enough. Any help from the experts here? GoDaddy claims the problem is with the plugin file's coding. Edited October 24, 2019 by ajetrumpetHere is my code, below. It is gathering the $url with the corret images. But poduces and error on line 50. Failed to open stream. No such file or directory. By this line: readfile($file_name); What Am I missing, beyond strong programmer mind set. Code: [Select] $merch_map = "http://spot_map"; $dir = "/opt/digistrive/tmp/media/current"; class merch_imgs { public function __construct() { $this->merch_imgs1(); } public function __call($method, $_) { $count = str_replace('merch_imgs', '', $method); echo "$count "; $this->{"merch_imgs" . ++$count}(); } } class thousand_printer extends merch_imgs { public function merch_imgs1000() {} } //03-2012. Location of merchant, if no image use place holder $thumbnails = implode(',', range(1, 10000)); $ext = ".png"; for($thumbnails = 0; $thumbnails < 10000; $thumbnails++) { $url = $merch_map.'/'.$thumbnails.''.$ext; echo $url . '<br>'; //echo '<img src='.$url.' border=0/>'; downloader($url, $dir); } function downloader($url){ $file_name = basename($url); $generated_files = geturl($url, $url); //file_put_contents($file_name); file_put_contents($url, $url = var_export($file_name,true)); $size=strlen($generated_files); if($size==0){exit(0);("<b>Error:</b>not found!");} //header('Content-type: application/force-download'); //header('Content-Disposition: attachment; filename=' . $file_name); //header('Content-Transfer-Encoding: binary'); //header('Expires: Sat, 26 Jul 1997 05:00:00 GMT'); //header('Cache-Control: must-revalidate, post-check=0, pre-check=0'); //header('Pragma: public'); //header('Content-Length: ' . $size); readfile($file_name); unlink($file_name); } function geturl($url, $referer) { $headers[] = 'Accept: image/png'; $headers[] = 'Connection: Keep-Alive'; $headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8'; $user_agent = 'ONLY_MY_HOST'; //$useragent = $url; $process = curl_init($url); curl_setopt($process, CURLOPT_HTTPHEADER, $headers); curl_setopt($process, CURLOPT_HEADER, 0); curl_setopt($process, CURLOPT_USERAGENT, $user_agent); curl_setopt($process, CURLOPT_REFERER, $referer); curl_setopt($process, CURLOPT_TIMEOUT, 30); curl_setopt($process, CURLOPT_RETURNTRANSFER, 1); curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1); $return = curl_exec($process); curl_close($process); return $return; } //downloader($dir, $url); //Merchant Images if($url && $user_agent){ file_get_contents($url); die(); } I am trying to use the google maps to geocode a location but I get this error: Warning: file_get_contents(http://maps.google.com/maps/api/geocode/json?address=New London,+Connecticut,+United States&sensor=false): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request Code: [Select] $location_request = "http://maps.google.com/maps/api/geocode/json?address={$city},+{$real_state},+{$real_country}&sensor=false"; $geocode = file_get_contents($location_request); What am I doing wrong? I tried URL encoding the location request but that also didn't work. Hi there, I'm a .net developer and I've inherited a partially complete php project. I'm trying get part of it running on my pc and am running into some issues due to my fairly limited knowledge with php/apache web server. I'm using Windows Vista, I have Apache HTTP server 2.2 running and am using PHP 5.2.17. The aim is to send some data to the web server. I'm using this function below - public static function push_data($data) { $data = base64_encode(gzdeflate(ot::encrypt(serialize($data), otCRYPT_KEY), 9)); $data = http_build_query(array(otDATA_KEY => $data)); $opts = array ( 'http' => array ( 'method' => 'POST', 'header'=> "Content-type: application/x-www-form-urlencoded\r\n" . "Content-Length: " . strlen($data) . "\r\n", 'content' => $data ) ); $ctx = stream_context_create($opts); return file_get_contents(otDATA_URL, 0, $ctx); } And am getting this message back - PHP Warning: file_get_contents(http://localhost/Epointment/ot/backend/data.php): failed to open stream: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host failed to respond. I've echoed $ctx and get Resource ID #15 and echoed otDATA_URL and get http://localhost/Epointment/ot/backend/data.php, which is correct. I've run a test php script actually on the web server and it works, so at least I know the server is running and PHP works on it. I'm not sure if this is an issue with the Apache settings or the PHP script or php.ini settings thanks for any help, Hi Guys! I'm new here at PHPFreaks, I have this problem using simplexml_load_file function. I am retrieving an XML from another sub-domain of my project, it's working fine on my local server (win xp, php 5.2.14) but when I try to execute it on our testing server (linux, php 5.2.14) it returns an error something like this.. Warning: simplexml_load_file([url of the script]) [function.simplexml-load-file]: failed to open stream: Connection timed out in [absolute path of the script] on line 3 i have tried cURL and file_get_contents, still get no luck. please note that the XML is validated via w3c.org and works really fine on my local server.. Thanks in advanced! Hello there. I used this code so many times long ago, but I still don't remeber and don't know what I'm doing wrong. http://circus.ka-blooey.net/ If I try to click on any link below the post, I got the error: Code: [Select] Warning: include(.php) [function.include]: failed to open stream: No such file or directory in /home/kablooey/public_html/circus/index.php on line 5 Warning: include(.php) [function.include]: failed to open stream: No such file or directory in /home/kablooey/public_html/circus/index.php on line 5 Warning: include() [function.include]: Failed opening '.php' for inclusion (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/kablooey/public_html/circus/index.php on line 5 -----------------------x My index is: Code: [Select] <?php include("header.php"); ?> <? if (empty($_GET["boo"])) {$boo="news/show_news";} include "$boo.php"; ?> <?php include("footer.php"); ?> and the footer, where the links are is: Code: [Select] <br /> <div id="menu"><center><a href="http://circus.ka-blooey.net">clear</a> ---x--- <a href="?boo=out">links out</a> ---x--- <a href="?boo=credits">credits</a></center></div><br /> <br /> <br /> <div id="footer"><img src="http://circus.ka-blooey.net/layout/circus_footer.jpg" /></div> </div> </div> </div> </body> </html> Help please? =/ |