Jump to content

Need help creating a simple video file server


Go to solution Solved by Ch0cu3r,

Recommended Posts

Hi. I am trying to create a simple video file server. I finished the skeleton of it but when it came to creating the multitude of pages I realized that there could be an easier way to do it.

 

I started out basically getting the folder names in the server then printing them on the page.

<?php
$dirs = glob("*", GLOB_ONLYDIR);
echo '<ul>';
foreach($dirs as $dir)
{
	$forbidden_folders = array("not4u", "ignore", Styles);
	$filename = str_replace($forbidden_folders, '', $dir);
	if (!empty($filename))
	{
    echo '<li><a href="'.$dir.'">'.$dir.'</a></li>';
	}
}
echo '</ul>'
?>

Then I created in each of the folders with files a php file with this code:

<?php

function date_sort_desc($a, $b)
{
  preg_match('/\w+ \d{4}/', $a, $matches_a);
  preg_match('/\w+ \d{4}/', $b, $matches_b);
  $timestamp_a = strtotime($matches_a[0]);
  $timestamp_b = strtotime($matches_b[0]);
  if ($timestamp_a == $timestamp_b) return 0;
  return $timestamp_a < $timestamp_b;
}

$files = array();
$dir = opendir('.');
while(false != ($file = readdir($dir))) {
        if(($file != ".") and ($file != "..") and ($file != "index.php")) {
                $files[] = $file;
        }   
}

natsort($files);

$i = 0;
foreach($files as $file) {
$i++;
$string = str_replace("TV Show Name S1 E$i - ", '' , $file);
        echo '<div><a href="../Discriptions/'.$file.'.php">'.basename($string, '.m4v').'</a></div><br>';
}
?>

This opens up a php file with the same file name as the file to be played containing the episode's thumbnail and description. That file then contains a link pointing back to the real file. The problem here is that I'd have to make a new php file for every file in my collection. I'm wondering if there's somehow a way to simplify all of this.

Edited by chrisyroid
  • Solution

You do not need to create a new php file every folder and video file.

 

To be able to browse the files in the directories you only need one PHP file. You start by listing the directories, as your first block of code suggests. But instead of physically linking to the directory you'd link back the php file and pass the directory as a query string parameter (eg browse.php?dir=TheSimpons)  This will then list all folders listed in yoursite.com/TheSimpsons.

 

To get the directory from the query string you'd use $_GET['dir']

$dir = isset($_GET['dir']) ? $_GET['dir'] : '';

Next we need to protect ourself from malicious users from trying to navigate our file system

// protect from directory recursion
$path = preg_replace('~(\.\.[\\/])+~', '', $path) . DIRECTORY_SEPARATOR;

And then make sure the directory we are listing exists within the current folder (where the php script is running)

if(file_exists(getcwd() . DIRECTORY_SEPARATOR . $path))
{
    // list folders for $path
}
else
{
    echo "Folder $path does not exist";
}

To list folders, add the following after  // list folders for $path

    echo "<p>listing directories in  $path";

    $path = ltrim($path, '\\/') . '*';
    $dirs = glob($path, GLOB_ONLYDIR);
    echo '<ul>';
    foreach($dirs as $dir)
    {
        echo '<li><a href="?dir='.$dir.'">'.$dir.'</a></li>';
    }
    echo '</ul>';

    // list all videos

Now you should be able to traverse through the directories under your video folder.

 

 

To list the videos you do something similar, add the following after // list all videos   

    $dir = rtrim($path, '\\/*');

    echo "<hr /><p>listing video files in $dir";

    // list all files under current directory ($_GET['dir'])
    $files = glob($path.'.*');

    echo '<ul>';
    foreach($files as $file)
    {
        $filename = basename($file);
        echo '<li><a href="?dir='.$dir.'&file='.$filename.'">'.$filename.'</a></li>';
    }

To prevent access to certain directories change   if(file_exists(getcwd() . DIRECTORY_SEPARATOR . $path))   to

// folders to forbid access to
$forbidden_folders = array("not4u", "ignore", 'Styles');

// check that the folder is not forbidden and directory does exist
if(!in_array(basename($path), $forbidden_folders) && file_exists(getcwd() . DIRECTORY_SEPARATOR . $path))

Also change  echo '<li><a href="?dir='.$dir.'">'.$dir.'</a></li>';   to prevent listing forbidden folders

        // do not list forbidden folders
        if(!in_array(basename($dir), $forbidden_folders))
        {
            echo '<li><a href="?dir='.$dir.'">'.$dir.'</a></li>';
        }

Similarly if you only want to list certain videos, eg mp4, wmv, mpv file etc add the following after the $forbidden_folders array

// only files with these extensions will be listed
$file_extensions = array('mp4', 'mpv', 'mpeg', 'wmv', 'ogv');

And then change   $files = glob($path.'.*);   to

// find all files limited to $file_extensions
$files = glob($dir.'/*.{'.implode(',', $file_extensions).'}',GLOB_BRACE);
Edited by Ch0cu3r

The file and folder listing works good but I'm having a problem with the query string. When I click on: "myfile.mkv" the url changes to: "http://localhost/test.php?dir=&file=myfile.mkv" and the page refreshes instead of opening up the file. Same goes for the directories. Also I might not have made it clear in my last post. I also want an easier way to show another page for each file containing a thumbnail and short description. This is how it goes.

 

Main Directory

--> Videos

---->TV Show

-------->Episode.mkv <-- Links to php file.

---------->Episode.mkv.php <-- Page containing description and thumbnail. When user clicks "play" episode plays.

 

This is what I have coded in "Episode.mkv.php"

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>Episode 1</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <link href="../../../Styles/style.css" rel="stylesheet" type="text/css" media="all"/>
</head>

<body class="single">
  <div class="wrap">
    <header>
    	<div class="logo">
    		<a href="index.html">
	    <img src="Thumbnails/ep1_snap.png" style="border: max-width: 320px; max-height: 240px;" /></a> </div>   
    </header>
    <div class="content">
    	<article>
    		<section class="head">
				<h3>Description</h3>
			</section>
			<section>
<center><b>Episode title</b></center>
<br>
Episode description goes here.
<br><br>
Original air date: September 13, 1986
<br><br>
<nav class="vertical menu">
<center><a href="../Season 1/episode.mkv">Play Episode</a></center>
</nav>
<br>
<a href="../Season 1/">Back to main menu</a>
			</section>
		</article>
   </body>
</html>
Edited by chrisyroid

 

 

When I click on: "myfile.mkv" the url changes to: "http://localhost/tes...file=myfile.mkv" and the page refreshes instead of opening up the file. 

Yea, that's intentional for the moment because I didn't know what you wanted to happen when some clicks on the filename.

 

 

 Also I might not have made it clear in my last post. I also want an easier way to show another page for each file containing a thumbnail and short description. This is how it goes.

 

Main Directory

--> Videos

---->TV Show

-------->Episode.mkv <-- Links to php file.

---------->Episode.mkv.php <-- Page containing description and thumbnail. When user clicks "play" episode plays.

 

This is what I have coded in "Episode.mkv.php"

Again you dont need separate php files for each video. You only need one. Could you explain how you are getting the information for each episode/video? Is it from a database?

Edited by Ch0cu3r

It's not from a database unfortunately. It's hand written and coded into each page. I planed to have php generate them via some kind of template or text file since I HATE working with SQL. I guess if I don't have a choice I'd do it that way but I have only minimal understanding of how that would all work.

You hate working with sql?  Sounds like a problem to me.  If you're going to create appls that use data, the ONLY viable way of managing the data going into the apps is to use sql.  Get over your phobia and do a little reading and join the 21st century.

 

Just my $.02

You can hand code them if you want, but its pointless having them as PHP files, just leave them as plain HTML file. This is awkward as you'll have many HTML files to edit for making changes the page layout etc.

 

But yes if all the information is in a database (doesn't have to be SQL, you could do a flat file database in csv or xml format) then you could dynamically render the page using PHP by searching the database by filename (if unique) or full filepath. Which means you only need to edit one file in order add/update/remove information about a video. This still is not ideal though as one mistake in the flat file will most likely cause corruption/errors. A relational database such as MySQL will be ideal.

 

Any way to change  the file link, You need to do is edit this line (the href attribute)

echo '<li><a href="?dir='.$dir.'&file='.$filename.'">'.$filename.'</a></li>';

So if you have a html file named as the same as the movie file you'd change it to this

echo '<li><a href="'.$dir . '/' . $filename.'.html">'.$filename.'</a></li>';

But yea you should consider moving your video information to be stored in an SQL database.

Edited by Ch0cu3r

It is better that you read up on using databases and how to organize your data fields into the proper table structures (normalization) and then how to write simple queries and try them out.  Really - learning it yourself is always better than being spoon-fed and not having a clue why it works.

How does one give you an example of a database?  Let's see - a database is a collection of tables, generally closely related to an application or to a collection of data.  It may also contain sets of disjoint data that for one reason or another it makes sense to the designer to lump into a single database.  (In a perfect environment (ie, one which you control) this last possibility would be minimized since you would have an unlimited number of databases.)

 

How's that?

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.