Stream videos to HTML5 video container using HTTP & PHP

Sometimes we need to feed videos dynamically from the server-side. If you’re feeding the video to a HTML5 <video> element, you may find that the video progress controls freezes and users cannot move it in any ways. (Thought this situation only happens in some browsers like Chrome and Firefox, the user experience hurts a lot.)

With a bit of investigation, I found out that Chrome requested the video with an HTTP range request which, the server-side handle it incorrectly and Chrome falls back to progressive downloading the video. With the little PHP script I wrote below, the server-side can now handle the HTTP range requests normally and the progress controls no longer freezes! (There’s one more benefit: fast forward and backward works much smoother in large video files.)

Create real-time updates using Server-sent Events and libSSE

When I first learn node.js, I learned how to use socket.io, a node.js module for real-time communication between the client and server. However, when I’m going back coding PHP for a while, I started to figure out only few PHP libraries offered this functions and the techniques they uses are old (AJAX Streaming, Forever <iframe>, etc.). One day I found a new technique called Server-sent Events and it’s pretty easy to implant. I have an idea of creating an interface for Server-sent Events in order to speed up development and make it easier to use. libSSE is the library I’ve create just for this and it’s event-based which means data is sent only when an event happens. It also has some utility classes for communicate with other PHP scripts.

Here’s the library: https://github.com/licson0729/libSSE-php

It’s pretty easy to use. Here’s an example.

On the client-side you need to set up an EventSource object to listen event from server.

Remember that Server-sent Events is still a new standard and not all browsers supports it. However, polyfills are available for them. Hope you like it and find it useful.

Encrypt files in PHP

Have you ever think of encrypting your secret files yourself? If you dunno how to do it yourself, here’s the rescue! In this article, I’ll teach you how to encrypt/decrypt files entirely in PHP!

First, please make sure Mcrypt is with your PHP bundle. If you don’t have this extension, please install it first as we need this to encrypt/decrypt files.

Then, it’s time to code! The code is pretty short as it uses the Mcrypt stream filter which also brings a huge performance increase when handling large files.

This is the code that encrypt contents written into the files. Isn’t this pretty short? But, how can I make the contents readable again? Here’s the way to decrypt the files:

Now we have a nice and easy solution to keep things secret in PHP. (Just to make sure, you need to change $passphrase into your very own password and keep it secret.)