Search Results

so far empty...

Loading

How To Create A Video Streaming App With PHP Video Streaming Script

  • 7 Minutes
  • 0 Comments
live streaming apps
How To Create A Video Streaming App With PHP Video Streaming Script
By admin June 30, 2022
  • Views: 477
  • Add +

App With PHP Video Streaming Script


Are you looking forward to building a video streaming server with ReactPHP or PHP? If your answer is yes, then you are at the right place as in this guide, we will show you how to build a video streaming server with the help of ReactPHP.


But, if you are looking forward to achieving top-notch outcomes, then it would be a good idea to hire a professional on demand best video streaming app development company. They have the skills and expertise to carry out this job effectively.


On-demand video streaming platform solutions tend to offer a comprehensive range of live video streaming application development solutions. It promises high-end capabilities for streaming live sports, web series, TV, and other interactive content with the help of some robust media tools.

It is evident from a recent report that more than 20 percent of enterprise-level social posts are known to be videos or images. So, you can seek the assistance of a video streaming application development agency that will focus on developing OTT app solutions for worldwide media streaming service providers to offer high-quality content to the end-users.


Understanding ReactPHP In Detail


ReactPHP is considered to be a set of independent components with the help of which you would be able to build an asynchronous app in PHP. Again, the ReactPHP HTTP offers a straightforward asynchronous interface for processing HTTP requests as well as effectively handling incoming connections.

The event loop is the core of almost every ReactPHP app. This event loop operates in a single thread and aids in setting up the asynchronous operations. Thus, the most of the ReactPHP apps tend to have this structure as follows:

  •         Init of the loop
  •         Setting up the world and configuration of the other components which are involved in utilizing the loop
  •         Running the loop

While running in the loop, the apps start to execute the asynchronous operations. There is constant running of the execution until it is stopped by $loop->stop() or else, the script needs to terminate itself.

The 2nd step of this process involves:  

  •         Creating a server for processing the incoming requests.
  •         Creating a socket to initiate listening for especially the incoming connections.

In the beginning, let’s focus on creating a straightforward server to gain a better understanding of the way it works out.

<?php

 

use React\Http\Server;

use React\Http\Response;

use React\EventLoop\Factory;

use Psr\Http\Message\ServerRequestInterface;

 

// init the event loop

$loop = Factory::create();

 

// set up the components

$server = new Server(function (ServerRequestInterface $request) {

return new Response(200, [‘Content-Type’ => ‘text/plain’],  “Hello world\n”);

});

 

$socket = new \React\Socket\Server(‘127.0.0.1:8000’, $loop);

$server->listen($socket);

echo ‘Listening on ‘ . str_replace(‘tcp:’, ‘http:’, $socket->getAddress()) . “\n”;

// run the application

$loop->run();

Once executed, this script will run continuously. The server is in a working condition. Now by opening the 127.0.0.1:8000 mainly in the browser, it will display a Hello world response.


Video Streaming


For instance, it is possible to make use of the Filesystem component as well as open file bunny.mp4. Consider opening this in reading mode and after that, you need to support its stream as particularly a response body.

<?php

$filesystem = \React\Filesystem\Filesystem::create($loop);

$server = new Server(function (ServerRequestInterface $request) use ($filesystem) {

$file = $filesystem->file(‘media/bunny.mp4’);

return $file->open(‘r’)->then(

     function (\React\Filesystem\Stream\ReadableStream $stream) {

         return new Response(200, [‘Content-Type’ => ‘video/mp4’], $stream);

     }

);

});

Now, to inform your browser that you are sending out a video, particularly the response, you should consider changing the Content-Type header to video/mp4. In this case, you do not need to make use of a specify a Content-Length header as the ReactPHP at the back of the scenes will inevitably make use of chunked transfer encoding and ultimately send out the corresponding header Transfer-Encoding: chunked.

The next step is to restore the browser and watch the streaming video.

Now, you get a streaming video server with many lines of code.


Improvements


Now, find the code, if you want to make any improvements:

<?php

 

$server = new Server(function (ServerRequestInterface $request) use ($filesystem) {

$params = $request->getQueryParams();

$fileName = $params[‘video’] ?? null;

 

if ($fileName === null) {

     return new Response(200, [‘Content-Type’ => ‘text/plain’], ‘Video streaming server’);

}

 

$filePath = __DIR__ . DIRECTORY_SEPARATOR . ‘media’ . DIRECTORY_SEPARATOR . $fileName;

$file = $filesystem->file($filePath);

 

return $file->open(‘r’)->then(

     function (ReadableStreamInterface $stream) {

         return new Response(200, [‘Content-Type’ => ‘video/mp4’], $stream);

     }

   );

});


Full Code Of The VideoStreaming Class


To make things easy for you, below, we have given a full code of the VideoStreaming class:

<?php

use React\Filesystem\Filesystem;

use React\Filesystem\FilesystemInterface;

use React\Filesystem\Stream\ReadableStream;

use React\Http\Server;

use React\Http\Response;

use React\EventLoop\Factory;

use React\Promise\PromiseInterface;

use Psr\Http\Message\ServerRequestInterface;

use function \React\Promise\Stream\unwrapReadable;

 

final class VideoStreaming

{

private $filesystem;

 

public function __construct(FilesystemInterface $filesystem)

{

     $this->filesystem = $filesystem;

}

 

/**

  * @param ServerRequestInterface $request

  * @return Response|PromiseInterface

  */

function __invoke(ServerRequestInterface $request)

{

     $file = $this->getFilePath($request);

     if ($file === null) {

         return new Response(200, [‘Content-Type’ => ‘text/plain’], ‘Video streaming server’);

     }

 

     return $this->makeResponseFromFile($file);

}

 

/**

  * @param string $filePath

  * @return PromiseInterface

  */

private function makeResponseFromFile($filePath)

{

    $file = $this->filesystem->file($filePath);

 

     return $file->exists()

         ->then(

             function () use ($file) {

                 return new Response(200, [‘Content-Type’ => ‘video/mp4’], unwrapReadable($file->open(‘r’)));

             },

             function () {

                 return new Response(404, [‘Content-Type’ => ‘text/plain’], “This video doesn’t exist on server.”);

             }

       );

}

 

/**

  * @param ServerRequestInterface $request

  * @return string|null

  */

private function getFilePath(ServerRequestInterface $request)

{

     $file = $request->getQueryParams()[‘file’] ?? null;

     if ($file === null) {

         return null;

     }

     return __DIR__ . DIRECTORY_SEPARATOR . ‘media’ . DIRECTORY_SEPARATOR . basename($file);

}

}

Now, there is 3 times more code, instead of a straightforward request handler callback. However, if this particular code is going to be altered in the time to come, it will be simpler to make these adjustments.


In A Nutshell


We hope, after reading this detailed guide, you can create a video streaming application with a PHP video streaming script. To get the top-notch outcomes, all that you need is to opt for the assistance of a reliable on demand best video streaming app development company. All in all, video streaming solutions can profit your business. You would be able to relish a lot of benefits by opting for these solutions.