Using PHP to Read the Contents of a Folder

  • S07E12
  • December 17, 2013

Robbie starts the development of a PHP tool to read all MIDI files from a folder and play them.

This video is provided free of charge. If you enjoy what we do, please consider becoming a Patron so we can continue offering more great content.
Support This Free Content

Topics Covered:

  • {play 4:07}Prize Giveaway: $25 prepaid Visa card from ESET.
  • {play 5:48}Happy birthday wishes.
  • Watch O Holy Night with Robbie and Carrie Webb, accompanied by Eric Kidd and Christina Skala.
  • {play 9:15}Thank you to all who have supported the show. Announcing our new crowdfunding campaign where you get a gift card of your choice in the same monetary value of your donation.
  • {play 11:35}Eric signs Robgor's 8x10.
  • {play 16:03}Featured Viewer Question: I have a Raspberry Pi controlling my Christmas lights, synchronized to music. I'd like to be able to control which MIDI file is playing from any computer on my network with a PHP script. How can this be done?
    • First, we need the php5 package installed via apt-get, which gives us PHP and a running Apache server.
    • Using PHP's opendir() along with readdir() to load a list of files from our MIDI storage folder.
    • Determining which ports you can use for aplaymidi.
    • Playing midi files on Linux using aplaymidi.
    • Assigning the song names to an array for security reasons.
    • Piping all output to /dev/null and returning control to our script to avoid it hanging up while a song plays.
    • Creating a form which allows us to select and play any MIDI file in our MIDI storage folder.
    • Note: We did not get any playback because of a PulseAudio issue. The script works as is! All we had to do was run this command (where Apache is running as the www-data user:
      sudo usermod -a -G pulse-access www-data
    • The final, working script (as written on the show):
      <?php
        ///////////////////////////////////////////////////////////////////////////
        // This script was written live on Category5 Technology TV episode 326.  //
        // Check out the episode at http://www.category5.tv/episodes/326.php     //
        // Note: While live on the air, we couldn't get it to play--turns out    //
        //       it was a pulseaudio issue, fixed with the following command...  //
        //       Assuming your apache (like ours) is running as www-data user,   //
        //       and that your system is using PulseAudio, make it go with:      //
        //       sudo usermod -a -G pulse-access www-data                        //
        //       MAY BE A GOOD IDEA TO REBOOT at that point, just to be sure...  //
        ///////////////////////////////////////////////////////////////////////////
        
        $folder = './mid';
        if ($handle = opendir($folder)) {
          while (false !== ($entry = readdir($handle))) {
            if (stristr($entry, '.mid')) {
              $songs[] = $entry;
            }
          }
        }
      
        if (is_array($songs)) {
          foreach ($songs as $id => $song) {
            if ($_POST['song'] == $id) {
              exec('killall -9 aplaymidi');
              exec('aplaymidi -p 128 "' . $folder . '/' . $song . '" > /dev/null 2>/dev/null &');
            }
          }
      
          echo '<form method="post">';
          echo '<select name="song">';
          foreach ($songs as $id => $song) {
           echo '<option value="' . $id . '"> ' . $song . ' </option>' . PHP_EOL;
          }
          echo '</select>';
          echo '<input type="submit" value="Play" />';
          echo '</form>';
        }
      ?>
    • While adding the user to the pulse-access group makes the above script work, Robbie also described an alternative playback option: bypass the Apache user by instead outputting a script (/tmp/midi.sh) and running it by a cronjob. Here is an example of how that may be done, based on the above script. Only use this version if you truly cannot get the above script working.
      <?php
        ///////////////////////////////////////////////////////////////////////////
        // This script is a cronjob alternative as described on Category5        //
        // Technology TV episode 326 and based on the script created then.       //
        // Check out the episode at http://www.category5.tv/episodes/326.php     //
        // Note: this is built to be run alongside a cronjob as follows:         //
        //       */1 * * * * /tmp/midi.sh                                        //
        // midi.sh won't exist until you press play (it's automatically created) //
        // Due to the nature of cron, the song will start playing as late as     //
        // one minute after clicking "play".                                     //
        ///////////////////////////////////////////////////////////////////////////
        
        $folder = '/var/www/mid';
        if ($handle = opendir($folder)) {
          while (false !== ($entry = readdir($handle))) {
            if (stristr($entry, '.mid')) {
              $songs[] = $entry;
            }
          }
        } 
      
        $command = '#!/bin/bash' . PHP_EOL;
        if (is_array($songs)) {
          foreach ($songs as $id => $song) {
            if ($_POST['song'] == $id) {
              $command .= '/usr/bin/killall -9 aplaymidi' . PHP_EOL;
              $command .= '/usr/bin/aplaymidi -p 128:0 "' . $folder . '/' . $song . '" > /dev/null 2>/dev/null &' . PHP_EOL;
            }
          }
      
          $filename = '/tmp/midi.sh';
          $command .= 'rm -f ' . $filename;
          file_put_contents($filename, $command);
          exec('chmod +x ' . $filename);
          
          echo '<form method="post">';
          echo '<select name="song">';
          foreach ($songs as $id => $song) {
           echo '<option value="' . $id . '"> ' . $song . ' </option>' . PHP_EOL;
          }
          echo '</select>';
          echo '<input type="submit" value="Play" />';
          echo '</form>';
      }
      ?>
  • {play 51:18}Top Stories from the Category5.TV Newsroom
    • A Bitcoin startup has raised $25m in venture capital funding.
    • Game developers say they want YouTube to leave gameplay videos online even though they “technically” breach copyright.
    • A green supercomputer has been built at Cambridge University using just 1 Watt per 3,361 Mega-flops.
    • Xbox One key sequence to allow 360 games in fact bricks the console.
  • {play 57:51}SteamOS Beta has arrived! store.steampowered.com/steamos
  • {play 59:00}Giveaway: Yet another $25 preloaded Visa card from ESET.
  • {play 60:46}How to win a free copy of Telestream Wirecast 5 Pro.
  • {play 61:23}Greetings to our newly registered viewers!

Discussion

Twitter Posts

Login to Category5

Error message here!

Hide Error message here!

Forgot your password?

Register on Category5

Error message here!

Error message here!

Hide Error message here!

Lost your password? Please enter your email address. You will receive a link to create a new password.

Error message here!

Back to log-in

Close