View unanswered posts | View active topics It is currently December 15th, 2017, 11:13 pm



Reply to topic  [ 4 posts ] 
 QuickPHP Mods 
Author Message
Moderator

Joined: December 22nd, 2008, 7:02 am
Posts: 20
Post QuickPHP Mods
Module: Directory Listing
Version: 1.2
Last Updated: 2008-12-23

Okay Zach, Just to show ya how i Enjoyed QuickPHP, I thought I would share this little gem i wrote up. I took the idea from another thread here, and thought I would try my hand at showing ppl, that the QuickPHP Mod is a pretty nice tool to have. Anyways the post wanted QuickPHP to provide a Directory List for Directories which didnt have a index.php. So I got to thinking....
Since QuickPHP Mod runs before, couldnt we make a check to see if this was a directory url or a file url. and if it was a directory url, we can check for the existance of an index.
if none exists, than we can change the RequestURI to our shiny Directory Lisings....

Okay, so a long time ago, I knew about Xitami Web Server (Another favorite of mine), and I knew it had a template for directory listings, so I figured that wud cut my work in half, cuz now I didnt need to design a page from the ground up. after a couple of hrs, and debugging the QuickPHP Mod, to get it to do wut I wanted, And Converting the Xitami Directory Template into a pure php Directiory Listings. I think I finally got it.

Okay, so lets get started eh?

These Mods use my custom QuickPHP_ReqMod Loader which is posted below

File: QuickPHP_ReqMod.php
Add:
Code:
mod_load('httpdir');


File: mods/httpdir.php
Yes, create a new folder where QuickPHP is located
Code:
<?php
   $mod['version'] = '1.2';
   if($mod['opendir']=(is_dir($ScriptFilename) && !is_file($ScriptFilename.'/.lock')))
      $RequestURI='/quickphp/httpdir.php?dir='.urlencode($ScriptFilename).(($hp=strpos($RequestURI,'?'))?('&'.substr($RequestURI,$hp+1)):'');
?>


As u can see its a very simple module, which just checks the uri for a valid directory :)

now in yer web directory, we will create a new folder quickphp. this is where we are gonna put our new handy dandy script as well as some images
File: quickphp/httpdir.php
Code:
<?php

   if(!isset($_GET['dir']) ||
      strlen($dir=urldecode($_GET['dir'])) &&
         strtolower(substr($dir,0,$drl=strlen($_SERVER['DOCUMENT_ROOT'])))!=
         strtolower($_SERVER['DOCUMENT_ROOT']))
   {
      header("HTTP/1.0 404 Not Found");
      die();
   }
   if($hi=(is_file("$dir/index.php")?1:(is_file("$dir/index.html")?2:0)))
   {
      include("{$dir}/index.".($hi==1 ? 'php':'html'));
      die();
   }
   
   function units($bytes=0)
   {
            if ($bytes<=0)
                  return '0 Byte';
   
            $convention=1024; //[1000->10^x|1024->2^x]
            $s=array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB');
            $e=floor(log($bytes,$convention));
            return round($bytes/pow($convention,$e),2).' '.$s[$e];
   }
   $urlbase=str_replace('\\','/',substr($dir,$drl));
   $dir.=(substr($dir,-1)=='/')?'':'/';
   $urlparent=($up=strrpos($urlbase,'/'))?substr($urlbase,$up):null;
   $order=(isset($_GET['order']) && preg_match('/^[nstx]{2,3}$/i',$_GET['order']))
         ?$_GET['order']:'nx';
   $dorder = substr($order,0,1);
   $name_reorder=(($dorder=='n')?'N':'n').'x';
   $size_reorder=(($dorder=='s')?'Sn':'sn').'x';
   $time_reorder=(($dorder=='T')?'tn':'Tn').'x';

?>
<HTML><TITLE>Directory listing of <?php echo $urlbase; ?></TITLE><BODY>
<H3>Index of:&nbsp;
<?php if(!is_null($urlparent)) { ?>
   <A HREF="<?PHP echo $urlparent; ?>">
   <IMG SRC="/quickphp/dir_up.gif" BORDER=0 ALT="Up to <?php echo $urlparent; ?>"></A>
<?php }    echo $urlbase; ?></H3>
<HR>
<TABLE BORDER=0 WIDTH="700" CELLSPACING=0>
<TR><TH ALIGN=LEFT><A HREF="<?php echo "{$urlbase}?order={$name_reorder}"; ?>">Name</A></TH>
     <TH ALIGN=RIGHT><A HREF="<?php echo "{$urlbase}?order={$size_reorder}"; ?>">Size</A></TH>
   <TH ALIGN=RIGHT><A HREF="<?php echo "{$urlbase}?order={$time_reorder}"; ?>">Modified</A></TH></TR>
<?php
   $files=array();
   if($dh=opendir($dir))
   {
      while(($file=readdir($dh)) !== false)
      {
         if($file[0]=='.') continue;
         $files[]=$file;
         $fsize[]=filesize($dir.$file);
         $ftime[]=filemtime($dir.$file);
         $ftype[]=(is_dir($dir.$file)?false:strtolower(pathinfo($dir.$file,PATHINFO_EXTENSION)));
      }
      closedir();
      // Still need sort order
      foreach($files as $idx=>$file)
      {
         $icon='/quickphp/dir'.(($ftype[$idx]===false)?
            '_dir':((is_file("dir{$ftype[$idx]}.gif"))?
            "{$ftype[$idx]}":'_any')).'.gif';
?>
<TR><TD>
<A HREF="<?php echo "{$urlbase}{$file}"; ?>"><IMG SRC="<?php echo $icon; ?>" BORDER=0><?php echo $file; ?></A></TD>
<?php if($ftype[$idx]===false) { ?>
<TD></TD>
<?php } else { ?>
<TD ALIGN=RIGHT><?php echo units($fsize[$idx]); ?></TD>
<?php } ?>
<TD ALIGN=RIGHT><?php echo date("d-M-Y H:i:s", $ftime[$idx]); ?></TD></TR>
<?php }
} ?>
</TABLE><HR>
<P><I>Powered by <A HREF="http://www.zachsaw.co.cc/?pg=quickphp_php_tester_debugger">QuickPHP</A></I>
</BODY>
</HTML>


And there ya have it :) (BTW I also ripped the gif images from xitami as well, http://www.cornflake.com/images/icons/ )

Yes, I know, the Sorting routine isnt even made. I was gonna add it, but thought I wud show ya What could be done with QuickPHP :) And to stir up others to post some script ideas as well :)

Update: U can create .lock in directories where u don't have an index.php and don't want directory access.

ANyways, Enjoy :)


Last edited by Laffin on December 24th, 2008, 4:12 pm, edited 3 times in total.



December 22nd, 2008, 9:17 pm
Profile
Moderator

Joined: December 22nd, 2008, 7:02 am
Posts: 20
Post QuickPHP Mod: Custom Error Pages
Module: Custom 404 Error Pages
Version: 1.3
Last Updated: 2008-12-22


Instead of creating more threads with diff Modules, I thought it wud be better to keep Mods in their own thread

Okay Another Module this time for custom 404 error pages.
Please note the filepath/name convention uses my directory layout, posted in another thread.

This Module allows u to create your own custom 404 pages :)
Its very simplistic, but it does get the job done :) (Again this was a template from xitami, thought it wud be a nice conversion)

File: bin/QuickPHP_ReqMod.php
Add
Code:
    include('mods/errors.php');


File: bin/mods/errors.php
Code:
<?php
   $mod['version']="1.3";
   if(!(isset($mods['httpdir']) && $mods['httpdir']['opendir']) &&
      (!is_file(is_dir($ScriptFilename)?($ScriptFilename.(substr($ScriptFilename,-1)!='/'?'/':'').$DefaultDoc):$ScriptFilename)))
         $RequestURI='/quickphp/errors.php?err=404&uri='.urlencode($RequestURI);   
?>


File: web/quickphp/errors.php
Code:
<?php
   header("HTTP/1.0 404 Not Found");
   $errors=array(0=>'Unknown',404=>'File Missing');
   $errcode=(isset($_GET['err']) && ($errcode=intval($_GET['err'])) && isset($errors[$errcode]))?$errcode:0;
   $message=(isset($_GET['msg'])?htmlentities($_GET['msg'],ENT_QUOTES,'ISO-8859-1',true):null);
   $uri=(isset($_GET['uri'])?htmlentities(urldecode($_GET['uri']),ENT_QUOTES,'ISO-8859-1',true):'');
?>
<HTML><TITLE>Error</TITLE><BODY><H1>
<HTML><BODY>
<H2>Error <?php echo $errcode; ?></H2>
<H3><?php echo $errors[$errcode]; ?></H3>
<?php if(!is_null($message)) { ?>
<P><?php echo $message; }?>
<HR>
<TABLE>
<TR><TD>Server       </TD><TD><?php echo $_SERVER["SERVER_SOFTWARE"]; ?></TD></TR>
<TR><TD>Name         </TD><TD><?php echo $_SERVER["SERVER_NAME"]; ?></TD></TR>
<TR><TD>Host         </TD><TD><?php echo $_SERVER["HTTP_HOST"]; ?></TD></TR>
<TR><TD>URI          </TD><TD><?php echo $uri; ?></TD></TR>
<TR><TD>Your IP      </TD><TD><?php echo $_SERVER["REMOTE_ADDR"]; ?></TD></TR>
<TR><TD>Your browser </TD><TD><?php echo $_SERVER["HTTP_USER_AGENT"]; ?></TD></TR>
</TABLE>
</BODY></HTML>


Update: I noticed that the URI was for the custom error page, I added some more code so it displays the original URI :)


Last edited by Laffin on December 24th, 2008, 4:13 pm, edited 2 times in total.



December 23rd, 2008, 7:00 am
Profile
Moderator

Joined: December 22nd, 2008, 7:02 am
Posts: 20
Post QuickPHP Mod: Module Loader
Name: Module loader
Version: 1.4
Last Updated: 2008-12-23

Not exactly a module, but the main QuickPHO_Mod script for loading modules. I have been using this as a means to load up modules, and do some common things between modules.

New in 1.3
Added comments on using the debug log systems (Yes, u can use the original system, or the mod_loader system)
Added module detection, if the module dusn exist than there is no sense in trying to load up the module :) It just returns gracefully.


The Original Post
Okay Zach, after creating my two Mods above (Initially they were the same Mod, but I just decided to seperate them).
I ran into a huge problem.

U cant have more than 1 Rewrite module, as it doesnt update the other variables!

What a nightmare... so I thought, well if there was a module loader that can do this for u this would be great.
However another problem introduced itself, remember the feature request I made about the debug log? Appending instead of overwriting.... Yeah this is one of them instances where ya wished the feature was already built. Sometimes when yer coding ya just get introduced to the snowball affect, and it just dusn seem to end.... I cuouldn't examine wut was going on in the module loader because I couldnt tell what the variables where, as the log file kept overwriting itself.

Okay so I needed a new debug log function for a new mod loader so modules can play nice. Fortunately PHP does make some things very easy for u. and others can be a pain.

so I turned off DebugLog feature, and wrote a simple one with ob_start buffering system (simple). But I think I will expand it to produce some extra info (timestamp and startup values)

I think I got it all worked out now, well so far it works pretty good.

mod_load(modulebasename)

to keep some things simple, I use the basename of the module, the mod_load function adds other information to generate a ModuleSignature as well as the filename.
I think I got the RequestURI update detection working properly.
and the variable dump routine is a nice one, cuz now i can see in the log file something like this
Code:
'RequestURI' => "/"
'RquestHeaders' => "Host: localhost:8088
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.5) Gecko/2008120122 Firefox/3.0.5
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Cache-Control: max-age=0
"
Loading Module: acesslog

      Updated 'ModuleSignature' => " mod_loader/1.4 mod_acesslog/1.0"
Updated 'mods' => array(
    'acesslog' => array(
        'version' => "1.0"
    )
)
Loading Module: httpdir
Updated 'RequestURI' => "/quickphp/httpdir.php?dir=C%3A%5Cquickphp%5Cweb%5C%5C"
Updated 'ModuleSignature' => " mod_loader/1.4 mod_acesslog/1.0 mod_httpdir/1.2"
Updated 'mods' => array(
    'acesslog' => array(
        'version' => "1.0"
    )
    'httpdir' => array(
        'version' => "1.2"
        'opendir' => true
    )
)
Loading Module: errors
Updated 'ModuleSignature' => " mod_loader/1.4 mod_acesslog/1.0 mod_httpdir/1.2 mod_errors/1.3"
Updated 'mods' => array(
    'acesslog' => array(
        'version' => "1.0"
    )
    'httpdir' => array(
        'version' => "1.2"
        'opendir' => true
    )
    'errors' => array(
        'version' => "1.3"
    )
)


I updated the above posts/mods with the new versions to conform to the mod_loader :)

WooHoo, Finally the Script!
File: QuickPHP_ReqMod.php
Code:
<?php
      $ModuleSignature.=' mod_loader/1.4';

      // U can use the Default Log System
    $DebugLog = false;
     // Or U can use mod_loader's log system   
    // $logfile='/quickphp/logs/quickphp.mod.log';
    // Or not have a debug log for QuickPHP_ReqMod system
    $logfile=null;
   
    function display_var($varname,$var,$ind=0)
    {
         $indent=str_repeat(' ',$ind*4);
         $text=$indent."'{$varname}' => ";
       if(is_array($var))
         {   
             $text.="array(\n";
           foreach($var as $idx => $val)
                 $text.=display_var($idx,$val,$ind+1);
              $text.= $indent .')';
       } elseif($typ=(is_string($var)?1:(is_numeric($var)?2:0))) {
          $text.=($qt=($typ==1?'"':'')). $var . $qt;
       } elseif(is_bool($var)) {
          $text.=($var?'true':'false');
         } else {
            $text.= 'resource ['. gettype($var) .']';
         }
         return $text."\n";
      }
      
    function mod_load($name)
    {
       static $qpv=array();
       $filename="mods/{$name}.php";
       if(file_exists($filename))
          echo "Loading Module: $name\n";
       else {
          echo "Missing Module: $name\n";
            return;
         }
       if(empty($qpv))
       {
           $qpv=array(   array(1,'DebugLog'), array(1,'RequestURI'), array(1,'RequestHeaders'), array(1,'UniqueID'),
                    array(1,'ModuleSignature'), array(0,'DocumentRoot'), array(0,'DefaultDoc'), array(0,'GatewayInterface'),
                    array(0,'QueryString'), array(0,'RedirectStatus'), array(0,'RemoteAddr'), array(0,'RemotePort'),
                    array(0,'RequestMethod'), array(0,'ScriptFilename'), array(0,'ScriptName'), array(0,'ServerAddr'),
                    array(0,'ServerName'), array(0,'ServerPort'), array(0,'ServerProtocol'), array(0,'ServerSignature'),
                    array(0,'ServerSoftware'), array(0,'PhpSelf'),array(1,'mods'));
       }
       foreach($qpv as $v)
          $$v[1] = $GLOBALS[$v[1]];
       $mod=array();
       include($filename);
       $ModuleSignature.=" mod_{$name}/{$mod['version']}";
       $mods[$name]=$mod;
       $update=false;
       foreach($qpv as $v)
       {
          if($v[0] && $GLOBALS[$v[1]]!==$$v[1])
          {
             $update=true;
             $GLOBALS[$v[1]]=$$v[1];
             echo 'Updated '. display_var($v[1],$$v[1]);
          }
       }
       if($update)
       {
          $urlparts=parse_url($RequestURI);
          $GLOBALS['QueryString']=isset($urlparts['query'])?$urlparts['query']:'';
          $GLOBALS['PhpSelf']=$GLOBALS['ScriptName']=$urlparts['path'];
          $GLOBALS['ScriptFilename']=str_replace('/','\\',($DocumentRoot.'/'.$urlparts['path']));
       }
    }
      ob_start();
      
    $mods=array();
      
      echo display_var('RequestURI',$RequestURI);
      echo display_var('RquestHeaders',$RequestHeaders);
      
      mod_load('acesslog');
    mod_load('httpdir');
    mod_load('errors');
   
    $contents=ob_get_contents();
    ob_end_clean();
      if(!empty($logfile)) file_put_contents($logfile,$contents,FILE_APPEND);
      else echo $contents;
?>


December 23rd, 2008, 11:20 am
Profile
Moderator

Joined: December 22nd, 2008, 7:02 am
Posts: 20
Post QuickPHP Mods: Access Log
Module: Access Log
Version: 1.0
Last Updated: 2008-12-23

Okay, now that we got a good base of Mods for QuickPHP, I finally got around to doing a simple access log module. Although due to QuickPHP not having a post processing script. There is no way to get some variables, such as Status Code and Content Size.
Log Format Variables
  • h - User Host IP
  • t - Time
  • r - Request URI
Pretty simple, if u want to change the format u change one string:
Code:
$logformat ="h t r";

pretty straight forward :)

Also note, that acesslog works best when it preceeds all other Mods. this way u can see what the user initially requested.
remember to set $logfile to whereever u want yer log file to be.

But its very nice to be able to see, who when and where. So we only got three variables

File: /bin/mods/accesslog.php
Code:
<?php
   $mod['version']="1.0";
   
   $logfile='/quickphp/logs/acess.log';
   // Because this is a pre processor we dont have access to some post processing variables, namely STATUS code and Output Size
   // But it should still give u a good reference to who has accessed yer site.
   // Note: This shud proceed any Mod Rewrite modules (ie: httpdir & errors)
   $logformat ="h t r";
   
   $alv = array ('h'=>$RemoteAddr,'t'=>date('[d/M/Y:H:i:s O]'),'r'=>"\"$RequestURI\"");
   $alk = array_keys($alv);
   $contents=str_replace($alk,$alv,$logformat)."\n";
   file_put_contents($logfile,$contents,FILE_APPEND);

?>


December 24th, 2008, 4:31 pm
Profile
Display posts from previous:  Sort by  
Reply to topic   [ 4 posts ] 

Who is online

Users browsing this forum: No registered users and 1 guest


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
Jump to:  
cron
Powered by phpBB.