Banner

Sponsor

Login


Welcome Back!
Guest
Guest

Register

Lost your password?

71 users online



In Depth Tutorials [May 30, 2004]

In Depth Tutorials [May 30, 2004]

Currently viewing this thread: 1 (0 members and 1 guests)


Thread closed

Closed by Noel on August 24th, 2005 03:41 PM

Not discussion.

Page 3 out of 4
Adam

Adam

Status: Offline!

How To Be A Good Member

Well, I lied a bit - this guide isn't for all. It really should read a guide for those intrested in and beginning PHP, as well as idiot savants, but that wouldn't fit. The purpose of this is to clear up a bunch of things that are asked day in and day out here, as well as things that annoy me.

Part 1: Reading and searching
The most important thing you will do with php/mysql is read. The PHP manual reads easier then the old latin and spanish one textbooks I have in my room. It will help you immensely. Allow me to clue you into a secret:

Say I wanted to know if there was a function for sorting arrays. The php manual is programmed (with PHP!) so that you can go to php.net/word and it will search for word. So lets go to php.net/sortArray

Results:

Quote:


Sorry, but the function sortarray is not in the online manual. Perhaps you misspelled it, or it is a relatively new function that hasn't made it into the online documentation yet. The following are the 20 functions which seem to be closest in spelling to sortarray (really good matches are in bold). Perhaps you were looking for one of these:

array
is_array
array_map
array_pad
array_pop
array_sum
asort
hw_objrec2array
in_array
ksort
msession_get_array
msession_set_array
msql_fetch_array
mysql_fetch_array
odbc_fetch_array
ora_error
rsort
sort
strtr
usort

If you want to search the entire PHP website for the string "sortarray", then click here.

For a quick overview over all documented PHP functions, click here.

OH SNAP, THATS A LOT OF FUNCTIONS. What a smart person might do is go look at the titles, make a logical guess, and click on it. I click on sort.

Quote:


sort
(PHP 3, PHP 4 )

sort -- Sort an array


That wasn't hard.

Let me give you another incredible application of searching. Say I spin magnets on my computer and then start getting this error:

Quote:


Call to undefined function: mysql_connect() in /home/httpd/html/sqltest.php on line 7


Now I'm like omg dood were screwed, but then I get a bright idea. I search google for "Call to undefined function: mysql_connect() " and hope other people might have had the same issue.

this is one of the results I get: link. A couple of posts in there it says

Quote:


I saw in your phpinfo files that you build php using '--without-mysql', that was the reason why you did not have mysql functions activacted.

.
Coincidently, the magnets changed my os to a *nix and reinstalled my php. I recompile, and BAM. MySQL works. Although this may not of been a realistic test, search google for errors. Chances you can find out why they happen and fix them.

But wait, theres another way to search! Say I want to learn PHP (I've been making crap up folks) from a book. So I search this forum for books. Look at these results!

Quote:


Any good PHP book recommendations?
What is the best PHP book?
PHP Question [About learning PHP]
Need help deciding on php books.
PHP Books
PHP Books - The Good Ones
Another book thread (!)

And thats just the first page of results. Say then after learning php from the most recommended book (prof php4 wrox press) we need to create a PHP highlighter. I decide to search, just in case its happened before.

If i search google, i get a TON of results.

SO SEARCH. FOR GODS SAKE SEARCH.

Part 2: For gods sake, name your threads better!
The title of this section pretty much sums it up.

Quote:


Annoyin error
ok, doods, mysql has me baffled.
Undefined things.......
plz help me with this!!
Anyone see why this does not work:
Need Alot Of Help
A Question For PHP Vets ?
n00b questions
Help me! a newbie in trouble here!
would this work?
unkown db error

Those are all bad. These are good:

Quote:


php_sockets.dll loaded but not being able to use the functions
Email script not sending
Outputting Readable HTML
populating text box with value from popup window
making replacements, like %%name%%, and using in html
Tutorial: page.php?page=blah / query strings / easy template tutorial (UPDATED)
Help with mysql_num_rows()

Part 3: Learn HTML before PHP
Fin.
Part 4: Read the stickys
More info then you can handle. Read them. They will teach you PHP.

A lot of this has been already said in the stickys, but it seems we need to push it more, so I post this thread. Possible soon to be tutorials-

currently playing in winamp
query optimization, if I can explain it in a good way
a look at secure authenticating with flat file.
arrays / references - you can do SO much with them

I also think I should get EG to do a XML/PHP one

___________________


Current Project: LivermoreMuscle.com
Sig Hosted by Motorspin

Last edited by Noel, May 7th, 2005 10:33 PM (Edited 1 times)

Adam

Adam

Status: Offline!

Handling File Upload

Uploading a file is very simple, all you really know how to do is use copy() and check for errors.

When you upload a file, certian things are stored in the variables. For instance you have had an input like

Code:


<input type="file" name="userfile">

$_FILES['userfile']['name']
The original name of the file on the client machine.

$_FILES['userfile']['type']
The mime type of the file, if the browser provided this information. An example would be "image/gif".

$_FILES['userfile']['size']
The size, in bytes, of the uploaded file.

$_FILES['userfile']['tmp_name']
The temporary filename of the file in which the uploaded file was stored on the server.

$_FILES['userfile']['error']
The error code associated with this file upload. ['error'] was added in PHP 4.2.0

These are php 4.2.0 variables names, and if you don't have it get it.

So now that you all the junk, we need to create a form. The only difference about this form is that we are passing more than just text, but files. So we need to add an attribute to the form tag. Take a look at this example form.

Code:


<form enctype="multipart/form-data" action="_URL_" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="1000">
Send this file: <input name="userfile" type="file">
<input type="submit" value="Send File">
</form>

Notice the hidden input named MAX_FILE_SIZE. This is the maxium size of the file in btyes. It cannot be over ridden. So if you are having problems uploading, check the size of the file first, so you don't get confused.

Now the next step before you upload the file is check the validity of the file and give some nice looking errors. Remember, if you are on unix, you will need to chmod the upload dir to give yourself proper permissions to upload the file. 777 or 755 will get the job done. Now take a look at this code and try to figure out what is happening. I'm going to assume that you are on version 4.2.0 in this example. If your not, deal with it! Grin

PHP:

<?php

$Dir 
'Upload';
if(!isset(
$_FILES['userfile'])) die('No File Submitted!');

if(
$_FILES['userfile']['size'] > $_POST['MAX_FILE_SIZE']) die('The file you submitted is to large!');

if(!
copy($_FILES['userfile']['tmp_name'], $Dir '/'$_FILES['userfile']['name'])) die($_FILES['userfile']['error'] . '<br>http://us3.php.net/manual/en/features.file-upload.errors.php for more details.');

echo 
'File Upload Succesfully!<br><a href="'.$Dir.'/'.$_FILES['userfile']['name'] .'"View File</a>';

?>

Now, time to learn about Handling multiple file uploads. The only difference is that now the files are stored in array, like $_FILES['usefile']['name'][]. This form shows you how to create multiple file uploads.

Code:


<form action="file-upload.php" method="POST" enctype="multipart/form-data">
Send these files:<br>
<input name="userfile[]" type="file"><br>
<input name="userfile[]" type="file"><br>
<input type="submit" value="Send files">
</form>

Now all we have do is build on the last example to loop through the all the files.

PHP:

<?php

$Dir 
'Upload';
if(!isset(
$_FILES['userfile'])) die('No File Submitted!');

for(
$K 0$K sizeof($_FILES); $K++){
    if(
$_FILES['userfile']['size'][$K] > $_POST['MAX_FILE_SIZE']) die('The file you submitted is to large!');

    if(!
copy($_FILES['userfile']['tmp_name'][$K], $Dir '/'$_FILES['userfile']['name'][$K])) die($_FILES['userfile']['error'][$K] . '<br>http://us3.php.net/manual/en/features.file-upload.errors.php for more details.');

    echo 
'File Upload Succesfully!<br><a href="'.$Dir.'/'.$_FILES['userfile']['name'][$K] .'"View File</a>';
}

?>

Simple Eh? Got it, if not the manual as a lot more than this.

Building on this example:
It's always good to check as much information as you can. For instance, you could check to see if the file as already been uploaded, or check the extension. You could save the file names in a table for easy access later. They're is alot more you can do, just think and try to push your boundarsy! Grin

___________________


Current Project: LivermoreMuscle.com
Sig Hosted by Motorspin

Adam

Adam

Status: Offline!

Handling Forms

This isn't really a tutorial, but it shows you how to deal with all possible form inputs in php. Here is the form:

Code:


<form action="view.php" method="post">
<p>
Name : <input type="Text" name="Name"><br>
Name : <input type="Text" name="LastName"><br>
Male <input type="radio" name="Gender" value="Nale" label="Male">
Female <input type="radio" name="Gender" value="Nale" label="Female"><br>
Age: <input type="text" name="Age"><br>
Hobbies (check all that apply):<br>
Computing <input type="checkbox" name="Computing" value="Yes">
Designing <input type="checkbox" name="Designing" value="Yes">
Programming <input type="checkbox" name="Programming" value="Yes"><br>
Favorite Webiste
<select name="Website">
<option value="TutorialForums">TF</option>
<option value="Devshed">DevShed</option>
<option value="Shadowness">Shadowness</option>
</select><br><br>
Biography <textarea name="Bio" cols="20" rows="4">Heres your biography!</textarea><br><br>
Favorite Forums: <select name="Forums[]" size="3" MULTIPLE>
<option value="Water Cooler">Water Cooler</option>
<option value="Beginners Corner">Beginners Corner</option>
<option value="Other Topics">Other Topics</option>
<option value="Photoshop">Photoshop</option>
</select><br>
<input type="submit">
</form>
</p>

Here is an example of what the data would look like. Look at it so you can figure out how to deal with the data from each input

Code:


Array
(
[Name] => Adam
[LastName] => Hawkins
[Gender] => Nale
[Age] => 17
[Computing] => Yes
[Designing] => Yes
[Programming] => Yes
[Website] => Devshed
[Bio] => I mod on TF
[Forums] => Array
(
[0] => Water Cooler
[1] => Beginners Corner
[2] => Other Topics
[3] => Photoshop
)

)

That should help you out when you are dealing with forms.

___________________


Current Project: LivermoreMuscle.com
Sig Hosted by Motorspin

Adam

Adam

Status: Offline!

Templating Engine

I think they're are two types of templating. There is the way vB does buy using {POST}, or just using variables like $User. Both of them are meant to achieve the same goal, to keep design out of programming. That is the best part about templating. You keep the hard html out of you programs, and thus enable you change the html easier without having to modify any of the actual code.

Now, the main things you'll need to know for the example that uses {VAR} is str_replace, its very simple. All you have to know what variables are in the templates. A Template File would look like this. Say this is a template on how to format a news story for you script.

Code:

<p>
{TITLE} - {DATE}
{NEWS}
<br>
- {AUTHOR}
</p>

Easy! There that is all the html you need to. They key concept is that the {VARS} will be replaced!. Now time to fix the template up. Say your information is coming from a DB. No matter where it comes from, you just need to set a variable with what is supposed to be replaced by. I find it easier if you give them names that correspond to their replacements.

PHP:

<?php

while($Record mysql_fetch_array($result)){
 
$Search['{TITLE}'] = $Record['Title'];
 
//continue with whatever more you need to add
}

?>

If you all you colum names where the names of the {VARS} you could do this way much faster:

PHP:

<?php

while($Record mysql_fetch_array($result)){
 foreach(
$Record as $Key => $Val){
   
$Search['{'.$Key.'}'] = $Val;
 }
}

?>

That example is a lot quicker then making the variables manually. Now that you have all the variables prepared you need to actually do the replacement. Here is the snippet:

PHP:

<?php

$fp 
fopen('templatefile.txt''r');
$Template fread($fpfilesize('templatefile.txt'));
fclose($fp);
foreach(
$Search as $Var => $Replace){
 
$Template str_replace($Var$Replace$Template);
}

?>

Now all you have to do is assemble all the snippets. If the results are coming from db, you are most likely using a while loop to go through all the results. So you want to get the contents of the template file first, and not have to do it every time in the loop. Then you want to set the replacement vars, then actually do the replacement. Don't forget to actually output the html! Here is the assembled version:

PHP:

<?php

$fp 
fopen('templatefile.txt''r');
$Template fread($fpfilesize('templatefile.txt'));
fclose($fp);

while(
$Record mysql_fetch_array($result)){
 foreach(
$Record as $Key => $Val){
   
$Search['{'.$Key.'}'] = $Val;
 }

 foreach(
$Search as $Var => $Replace){
   
$Template str_replace($Var$Replace$Template);
 }
 
 echo 
$Template;
}

?>

Now the other method. A template file might look like this:

Code:

$User - $Posts - $Link

The same logic applies. Execpt in this case, all you need to is come up with $User, $Posts, and $Link vars. Again, I'm going to assume data is coming from a DB in this example. Note that I'm going to assume that the colum names in the database are the same as the names in the template file.

PHP:

<?php

while($Record mysql_fetch_array($result)){
 
extract($Record);
 include(
'path/to/template/file');
}

?>

Extract makes this much easier. If you have an array like $Record['User'], it takes all the keys of that array and makes them into their own variables with the correct values.

___________________


Current Project: LivermoreMuscle.com
Sig Hosted by Motorspin

Last edited by Adam, August 22nd, 2003 09:16 PM (Edited 1 times)

Adam

Adam

Status: Offline!

Tutorial: File Manager/Directory List

In this tutorial were going to create a ftp-program like directory and file manager. I'm going to assume you know basic PHP here.

Now, the first thing were going to want to do is build a directory tree so that we can navigate. We can do this with a recursive (a function that calls itself) function.

I'll show you the PHP, then explain it.

PHP:


<?php
error_reporting
('E_ALL');
$baseDir '.';
isset(
$_GET['this']) ? $thisDir base64_decode($_GET['this']) : $thisDir '.';
# initial nest level
$nestLevel 0;
function 
findDirs($baseDir$thisDir)
{
  global 
$nestLevel;
  
$nestLevel++;
  if (
is_dir($baseDir) && $dir opendir($baseDir))
  {
      
$name explode('/'$baseDir);
      
$rName $name[count($name)-1];
      if(
$baseDir == $thisDir)
      {
          
$rName '<strong>' $rName '</strong>';
      } else {
          
$rName '<a href="' $_ENV['PHP_SELF'] . '?this=' base64_encode($baseDir) . '">' $rName '</a>';
      }
    
$array[] = str_repeat'&nbsp;'$nestLevel*2) . $rName;
    while ((
$file readdir($dir)) !== false)
    {
      if (
is_dir($baseDir."/".$file) && $file != "." && $file != "..")
      {
        
$array array_merge($arrayfindDirs($baseDir."/".$file$thisDir));
      }
    }
    
closedir($dir);
  }
  
$nestLevel--;
  return(
$array);
}
?>

So whats that do?

PHP:

<?php

error_reporting
('E_ALL');
$baseDir '.';
isset(
$_GET['this']) ? $thisDir base64_decode($_GET['this']) : $thisDir '.';
# initial nest level
$nestLevel 0;

?>

Thats pretty self explanatory - we hike up the error reporting, and then we check to see if we got a $_GET['this'] variable. Thats the variable that stores what directory were in, and its in base64 because sometimes directorys can have weird characters or spaces or what not. $thisDir isnt really this directory - its the highest directory we let the script access. Generally, if safe mode is on, we cant access a directory higher then the script, so I put it as '.' which means same as the script.

We use nestlevel so that when we form our tree, its pretty and indented.

PHP:

<?php

function findDirs($baseDir$thisDir)
{
  global 
$nestLevel;
  
$nestLevel++;

?>

Starts the function, globals the nest level, and then increases it - were in it one block deeper. If you dont get it, trust me - nesting can be a bit confusing.

PHP:

<?php
  
if (is_dir($baseDir) && $dir opendir($baseDir))
  {

?>


Makes sure $baseDir is a directory and we can open it.

PHP:

<?php

      $name 
explode('/'$baseDir);
      
$rName $name[count($name)-1];
      if(
$baseDir == $thisDir)
      {
          
$rName '<strong>' $rName '</strong>';
      } else {
          
$rName '<a href="' $_ENV['PHP_SELF'] . '?this=' base64_encode($baseDir) . '">' $rName '</a>';
      }
    
$array[] = str_repeat'&nbsp;'$nestLevel*2) . $rName;

?>

This is mostly text formating. We explode and put the last section in $rName so we have something like images, not ./atc/img/. Then, we check if the directory is the same as the one were in (as indicated from the $thisDir, which comes from $_GET['this']). If were in the directory, we give it a bold face. if not, we make a link to it. The str_repeat makes our tree look nice and nested.

PHP:

<?php
    
{
      if (
is_dir($baseDir."/".$file) && $file != "." && $file != "..")
      {

?>

THis goes through all the files/dirs in a dir and picks out all non-symbolic directorys.

PHP:

<?php

        $array 
array_merge($arrayfindDirs($baseDir."/".$file$thisDir));
      }
    }

?>


It then checks each dir a level deeper, and keeps calling itself until it picks up all the subdirectorys. This is called recursing. It uses array_merge to add what it found to the array we'll return.

PHP:

<?php

    closedir
($dir);
  }
  
$nestLevel--;
  return(
$array);
}
?>

?>

Closes te directory handle, takes nestlevel down one, and returns the array.

Using it?

I ended up using it like this:

PHP:


                <?php
                    $dirs 
findDirs($baseDir$thisDir);
                    foreach(
$dirs as $dir) {
                        print 
$dir '<br />' "\n";
                    }
                
?>

SImply takes the array given to it, and loops through it printing each directory.

Then I wanted to get all the files from the current directory. I did that with this:

PHP:


                <?php
                    $thisDirHandle 
opendir($thisDir);
                    while ((
$file readdir($thisDirHandle)) !== false)
                    {
                       if (!
is_dir($file) && $file != "." && $file != "..")
                       {
                         print 
'<a href="' $thisDir '/' $file '" target="blank">' $file '</a><br />' "\n";
                       }
                    }
                
?>


That simply opens up the directory were in, and then loops through all the files (we exclude directorys with the if line). It prints out each file as a link to itself in a new window.

My full code looked like this:

PHP:


<?php
error_reporting
('E_ALL');
$baseDir '.';
isset(
$_GET['this']) ? $thisDir base64_decode($_GET['this']) : $thisDir '.';
# initial nest level
$nestLevel 0;
function 
findDirs($baseDir$thisDir)
{
  global 
$nestLevel;
  
$nestLevel++;
  if (
is_dir($baseDir) && $dir opendir($baseDir))
  {
      
$name explode('/'$baseDir);
      
$rName $name[count($name)-1];
      if(
$baseDir == $thisDir)
      {
          
$rName '<strong>' $rName '</strong>';
      } else {
          
$rName '<a href="' $_ENV['PHP_SELF'] . '?this=' base64_encode($baseDir) . '">' $rName '</a>';
      }
    
$array[] = str_repeat'&nbsp;'$nestLevel*2) . $rName;
    while ((
$file readdir($dir)) !== false)
    {
      if (
is_dir($baseDir."/".$file) && $file != "." && $file != "..")
      {
        
$array array_merge($arrayfindDirs($baseDir."/".$file$thisDir));
      }
    }
    
closedir($dir);
  }
  
$nestLevel--;
  return(
$array);
}
?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
    <title>File Manager</title>
    <style type="text/css">
        body {
            margin: 0px 0px 0px 0px;
            padding: 0px 0px 0px 0px;
            font-family: tahoma, verdana, arial, helvetica, sans-serif;
            font-size: 9pt;
            color: #000;
            background-color: #cccccc;
            text-align: center;
            /* part 1 of 2 centering hack */
        }
        #content {
            width: 80%;
            padding: 10px;
            margin-top: 20px;
            margin-bottom: 20px;
            margin-right: auto;
            margin-left: auto;
            /* opera does not like 'margin:20px auto' */
            background: #fff;
            border: 1px solid #000;
            text-align:left;
            /* part 2 of 2 centering hack */
            width: 80%; /* ie5win fudge begins */
            voice-family: "\"}\"";
            voice-family:inherit;
            width: 75%;
        }
        html>body #content {
            width: 75%px; /* ie5win fudge ends */
        }
        #tree {
            width:30%;
            float:left;
            line-height: 150%;
        }
        #files {
            width:70%;
            float:right;
            line-height: 150%;
        }
    </style>
    </head>
    <body>
        <div id="content">
            <div>
            <h3>File Manager</h3>
            </div>
            <div id="tree">
            <h5>Tree</h5>
                <?php
                    $dirs 
findDirs($baseDir$thisDir);
                    foreach(
$dirs as $dir) {
                        print 
$dir '<br />' "\n";
                    }
                
?>
            </div>
            <div id="files">
            <h5>Files</h5>
                <?php
                    $thisDirHandle 
opendir($thisDir);
                    while ((
$file readdir($thisDirHandle)) !== false)
                    {
                       if (!
is_dir($file) && $file != "." && $file != "..")
                       {
                         print 
'<a href="' $thisDir '/' $file '" target="blank">' $file '</a><br />' "\n";
                       }
                    }
                
?>
            </div>
        </div>
    </body>
</html>

In part 2, We'll implement uploading, deleting, chmoding, renaming, and directory creating. In part 3, we'll finish it off with a secure file based login system so that not everyone can use it.

This does work with safe mode.

___________________


Current Project: LivermoreMuscle.com
Sig Hosted by Motorspin

Phil

Phil

with Mr. Jones
Status: Offline!

Tutorial: File Manager/Directory List Part 2

Well, this is part 2 of file directory program tutorial. In this tutorial, we'll be implementing uploading, deleting, chmoding, renaming, and directory creating. This really isnt too hard, although it sounds like a lot. The first thing we'll add is renaming, because its on a file by file basis.

This is the code we finished with last time, except I added a clear:both div to make it work in mozilla Smile

PHP:


<?php
error_reporting
('E_ALL');
$baseDir '.';
isset(
$_GET['this']) ? $thisDir base64_decode($_GET['this']) : $thisDir '.';
# initial nest level
$nestLevel 0;
function 
findDirs($baseDir$thisDir)
{
  global 
$nestLevel;
  
$nestLevel++;
  if (
is_dir($baseDir) && $dir opendir($baseDir))
  {
      
$name explode('/'$baseDir);
      
$rName $name[count($name)-1];
      if(
$baseDir == $thisDir)
      {
          
$rName '<strong>' $rName '</strong>';
      } else {
          
$rName '<a href="' $_ENV['PHP_SELF'] . '?this=' base64_encode($baseDir) . '">' $rName '</a>';
      }
    
$array[] = str_repeat'&nbsp;'$nestLevel*2) . $rName;
    while ((
$file readdir($dir)) !== false)
    {
      if (
is_dir($baseDir."/".$file) && $file != "." && $file != "..")
      {
        
$array array_merge($arrayfindDirs($baseDir."/".$file$thisDir));
      }
    }
    
closedir($dir);
  }
  
$nestLevel--;
  return(
$array);
}
?>
<!DOCTYPE html
     PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
    <title>File Manager</title>
    <style type="text/css">
        body {
            margin: 0px 0px 0px 0px;
            padding: 0px 0px 0px 0px;
            font-family: tahoma, verdana, arial, helvetica, sans-serif;
            font-size: 9pt;
            color: #000;
            background-color: #cccccc;
            text-align: center;
            /* part 1 of 2 centering hack */
        }
        #content {
            width: 80%;
            padding: 10px;
            margin-top: 20px;
            margin-bottom: 20px;
            margin-right: auto;
            margin-left: auto;
            /* opera does not like 'margin:20px auto' */
            background: #fff;
            border: 1px solid #000;
            text-align:left;
            /* part 2 of 2 centering hack */
            width: 80%; /* ie5win fudge begins */
            voice-family: "\"}\"";
            voice-family:inherit;
            width: 75%;
        }
        html>body #content {
            width: 75%px; /* ie5win fudge ends */
        }
        #tree {
            width:30%;
            float:left;
            line-height: 150%;
        }
        #files {
            width:70%;
            float:right;
            line-height: 150%;
        }
        #clear {
            clear: both;
        }
        
    </style>
    </head>
    <body>
        <div id="content">
            <div>
            <h3>File Manager</h3>
            </div>
            <div id="tree">
            <h5>Tree</h5>
                <?php
                    $dirs 
findDirs($baseDir$thisDir);
                    foreach(
$dirs as $dir) {
                        print 
$dir '<br />' "\n";
                    }
                
?>
            </div>
            <div id="files">
            <h5>Files</h5>
                <?php
                    $thisDirHandle 
opendir($thisDir);
                    while ((
$file readdir($thisDirHandle)) !== false)
                    {
                       if (!
is_dir($file) && $file != "." && $file != "..")
                       {
                         print 
'<a href="' $thisDir '/' $file '" target="blank">' $file '</a><br />' "\n";
                       }
                    }
                
?>
            </div>
            <div id="clear">&nbsp;</div>
        </div>
    </body>
</html>

To our file list, we'll need to add a rename command, for convience, some file information. We'll store in a table because its tabular, and in this case is a lot easier then using CSS.

The first thing we'll do is going to define a couple extra constants. Put these after our call to error reporting. This is just to keep filenames all in one place.

PHP:

<?php

# what pages this script uses, as to hide them
define('MAIN_BROWSE'$_SERVER['PHP_SELF']);
define('RENAME_SCRIPT''test_rename.php');
define('UPLOAD_SCRIPT''test_upload.php');
define('MKDIR_SCRIPT''test_mkdir.php');
define('MAXFILESIZE'1000000);
if(isset(
$_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING']) ) {
    
define('QUERYSTRING''?' .  $_SERVER['QUERY_STRING']);
} else {
    
define('QUERYSTRING''');
}

?>

Lets change some things inside our files div to reflect the changes. First, a bit more css Smile Add this to our style sheet:

Code:


#fileTable {
border: 1px #CECECE solid;
background-color: white;
width: 85%;
}

.headerRow {
background-color: #CECECE;
}
.cellTypeA {
background-color: #F2F2F0;
border-bottom: 1px #CECECE solid;
}

.cellTypeB {
background-color: #E9E9E9;
border-bottom: 1px #CECECE solid;
}

.centerText {
text-align: center;
}
.fakeLink {
color: blue;
text-decoration: underline;
cursor: pointer;
}

Now, lets add the table and file information to our loop that spits out the file names.

PHP:


            <div id="files">
            <h5>Files</h5>
                <table cellspacing="0" cellpadding="4" border="0" id="fileTable">
                    <tr>
                        <td class="headerRow centerText" width="40%">
                            <strong>Filename</strong>
                        </td>
                        <td class="headerRow centerText">
                            <strong>Last Modified</strong>
                        </td>
                        <td class="headerRow centerText">
                            <strong>Size</strong>
                        </td>
                        <td class="headerRow centerText">
                            <strong>Rename</strong>
                        </td>
                    </tr>
                    <?php
                        $thisDirHandle 
opendir($thisDir);
                        while ((
$file readdir