Back to Top
The nuts and bolts for
Creative web development

Create Dynamic Directories And Default Pages

Do you have a community based site with lots and lots of users? Do they post comments, upload pictures or documents, or maybe send in video or audio? Would you like to build one?

It’s easy enough, when you do have your site built, to have a page that displays that user’s info based on their UserID or any other variable you choose to use. Like: awebsite.com/a_page.php?UserID=something.

Let’s take it further and dynamically create a directory and place a default start page for each user based on their name so they have their own personal URL and space on your site. Like: awebsite.com/username.

This is completely done in DW8 with very little hand coding at all. You’re gonna find it opens many doors for you and your users. It took me years to figure this out and make it work this way. Now you can in minutes.

 

Lets start!

First you’ll need to have 777 directory permissions on your site, and more specifically, in the directory you wish to create dynamic directories in. This system I put together uses a few scripts that I did not personally write. I’ll make notes of those areas in the codes of each page. You can view a demo and download all of the source files for this tutorial. Also…please keep in mind that I can’t really accept responsibility for security problems that are inherent in allowing write permissions in your site. You’ll have to re-work the files/tutorial for your site and come up with security precautions yourself. Don’t worry though…you’ll figure it out.

Let’s go through the files and talk about what they are and what they do. First thing you should do is run the included sql file to setup the table and fields used in this tutorial. Then you’ll need to alter the Connections/db_connection.php file to match your Mysql Information.

THE REGISTRATION FILE: (index.php)

 This file is a very basic registration form that’ll create a new record including First Name, Last Name, and a Random Number used as a UniqueID.

<?php require_once('Connections/db_connection.php'); ?>
<?php
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;
switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;   
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "user_folders_form")) {
  $insertSQL = sprintf("INSERT INTO user_folders (UniqueID, FirstName, LastName) VALUES (%s, %s, %s)",
                       GetSQLValueString($_POST['UniqueID'], "text"),
                       GetSQLValueString($_POST['FirstName'], "text"),
                       GetSQLValueString($_POST['LastName'], "text"));
mysql_select_db($database_db_connection, $db_connection);
  $Result1 = mysql_query($insertSQL, $db_connection) or die(mysql_error());
$insertGoTo = "process_db_information.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset="iso-8859-1"" />
<title>Dynamic User Folders with Startup Page</title>
<link href="css.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table width="650" border="0" align="center" cellpadding="2" cellspacing="2" class="spotlight_photo_border">
  <tr>
    <td><div align="center">
      <p>Be sure you ran the included SQL to setup the table for this example in your MYSQL DB before going forward.</p>
      <p>You'll also need to alter the connection file in the connection folder to match your DB and your site or folder where you wish to create dynamic user folders  must have 777 write permissions.</p>
      <p>Go to the Bindings Tab and Create 3 Form Variables: (FirstName) (LastName) (User_Folder) </p>
      </div></td>
  </tr>
  <tr>
    <td><form id="user_folders_form" name="user_folders_form" method="POST" action="<?php echo $editFormAction; ?>">
      <table width="100%" border="0" cellspacing="2" cellpadding="2">
        <tr>
          <td width="24%" valign="bottom"><div align="right">Enter Your First Name: </div></td>
          <td width="24%" valign="bottom"><label>
            <input name="FirstName" type="text" id="FirstName" />
          </label></td>
          <td width="22%" valign="bottom"><div align="right">Enter Your Last Name:</div></td>
          <td width="30%"><label>
            <input name="LastName" type="text" id="LastName" />
          </label></td>
        </tr>
        <tr>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
        </tr>
        <tr>
          <td>
            <strong><font color="#999999" size="1">
            <input name="UniqueID" type="hidden" id="UniqueID" value="<?php
//Creates A Random Number For A Unique User ID
function get_random_number_between($start, $end) {
srand((float)microtime()*1000000);
$random_number=rand($start,$end);
return $random_number;
};
echo get_random_number_between(1, 9999999999);
?>" />
            </font></strong></td>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
          <td>
            <div align="left">
              <table width="160" border="0" cellspacing="0" cellpadding="0">
                  <tr>
                    <td width="186"><div align="right">
                      <label>
                      <input type="submit" name="Submit" value="Submit" />
                      </label>
                    </div></td>
                  </tr>
                </table>
            </div></td>
        </tr>
      </table>
            <input type="hidden" name="MM_insert" value="user_folders_form">
    </form>
    </td>
  </tr>
  <tr>
    <td>&nbsp;</td>
  </tr>
</table>
</body>
</html>

 The Reg Form Processing Code: This code takes the First and Last names of the user and combines them like "firstnamelastname" to create the directory that reflects their name. It updates the record and inputs the user's new directory name. Take note of the Hidden field labeled "User_Folder". The script will populate it with the First and Last names of the user and will use the "strtolower" string to change both names to lowercase as to prevent issues with non-windows servers.

<?php require_once('Connections/db_connection.php'); ?>
<?php
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;
switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;   
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "process_folder_name")) {
  $updateSQL = sprintf("UPDATE user_folders SET user_folder="%s" WHERE uniqueid="%s"",
                       GetSQLValueString($_POST['User_Folder'], "text"),
                       GetSQLValueString($_POST['UniqueID'], "text"));
mysql_select_db($database_db_connection, $db_connection);
  $Result1 = mysql_query($updateSQL, $db_connection) or die(mysql_error());
$updateGoTo = "process_folder.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
    $updateGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $updateGoTo));
}
mysql_select_db($database_db_connection, $db_connection);
$query_rsUsers = "SELECT * FROM user_folders ORDER BY User_Added DESC";
$rsUsers = mysql_query($query_rsUsers, $db_connection) or die(mysql_error());
$row_rsUsers = mysql_fetch_assoc($rsUsers);
$totalRows_rsUsers = mysql_num_rows($rsUsers);
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset="iso-8859-1"" />
<title>Dynamic User Folders with Startup Page</title>
<link href="css.css" rel="stylesheet" type="text/css" />
</head>
<body /><form id="process_folder_name" name="process_folder_name" method="POST" action="<?php echo $editFormAction; ?>">
  <input name="UniqueID" type="hidden" id="UniqueID" value="<?php echo $row_rsUsers['UniqueID']; ?>" />
  <input name="User_Folder" type="hidden" id="User_Folder" value="<?php echo strtolower ($row_rsUsers['FirstName']); ?><?php echo strtolower ($row_rsUsers['LastName']); ?>" />
  <label>
  <input name="Submit" type="submit" class="white_button" value="Submit" />
  </label>
  <input type="hidden" name="MM_update" value="process_folder_name">
</form>
</body>
</html>
<?php
mysql_free_result($rsUsers);
?>

The Directory Creation Process: This code is what creates the new directory based on the user's name. It will also copy a default start page (index.php) from a folder and place it into the newly created directory. The new start page in the new directory has a recordset in it to show information based on a user's ID. The script by Ilya Nemihin will replace the UserID variable in the page to reflect the User's and then resave the file in the new directory.

<?php require_once('Connections/db_connection.php'); ?>
<?php
mysql_select_db($database_db_connection, $db_connection);
$query_rsUsers = "SELECT * FROM user_folders ORDER BY User_Added DESC";
$rsUsers = mysql_query($query_rsUsers, $db_connection) or die(mysql_error());
$row_rsUsers = mysql_fetch_assoc($rsUsers);
$totalRows_rsUsers = mysql_num_rows($rsUsers);
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset="iso-8859-1"" />
<title>Dynamic User Folders with Startup Page</title>
<link href="css.css" rel="stylesheet" type="text/css" />
<meta http-equiv="Refresh" content="3;URL=<?php echo $row_rsUsers['User_Folder']; ?>" />
</head>
<body>
<?php
//This is where the new directory gets created.
mkdir ("".$row_rsUsers['User_Folder']."", 0777);?>
<?php
$file = 'start_page_to_copy/index.php'; //This is the file that will become the default start page in the new directory
$newfile = "".$row_rsUsers['User_Folder']."/index.php";
if (!copy($file, $newfile)) {
    echo "failed to copy $file...\n";
}
?>
//Here is where the sub-directories are created.
<?php mkdir ("".$row_rsUsers['User_Folder']."/resume", 0777);
mkdir ("".$row_rsUsers['User_Folder']."/photos", 0777);
mkdir ("".$row_rsUsers['User_Folder']."/photos/thumbs", 0777);
mkdir ("".$row_rsUsers['User_Folder']."/media", 0777);
mkdir ("".$row_rsUsers['User_Folder']."/media/audio", 0777);
mkdir ("".$row_rsUsers['User_Folder']."/media/video", 0777);
?>
<?php
//This is where the script by Ilya Nemihin kicks in. 
require_once('FileScopeReplacer/FileScopeReplacer.php');
$params = array();
//--------------- configuration --------------

// directory where file will be searched to replace
$params['dir'] = $row_rsUsers['User_Folder'];
// set to 1 if you want to proceed also nested directories
$params['include_nested'] = 0;
// this is string of what you are looking for
$params['search_what'] = 'replace';
$params['replace_to'] = $row_rsUsers['UniqueID'];
// setting for filtering, set '' if no filtering,
// otherwise thi is regexp expression like: '/your_regexp/flags',
// see http://www.php.net/manual/en/pcre.pattern.syntax.php
$params['file_name_match'] = '';  // <-- this mean beginning from 'test'
//--------------- end configuration --------------
$replacer = new FileScopeReplacer( $params );
$replacer->doWork();
?>
</body>
</html>
<?php
mysql_free_result($rsUsers);
?>

Download The Source Files. Enjoy!

Bobby Edgar

Bobby EdgarI can't say I studied design, programming,or coding in a school. I can say that I do remember how to...or do I really?...make a stick look like a jumping jack on my Vic20.

I took up web design because I was bored. Yes...it's true. I have been touring around the world with Broadway Shows for many years now as the Technical Director and wanted a hobby that was portable. I picked up some extremely thick and heavy books (there goes portable, right?) and off I went.

Let me send a quick thanks to Google and all of the folks who share their knowledge and tips. You all have saved my back from the burden of carrying those darn books...

See All Postings From Bobby Edgar >>

Share this Article