Back to DFS's Workshop Page
Back to Agenda Page


Accessing System Information

To create interesting and useful scripts, it is frequently necessary to get information which can easily be obtained by running standard commands from the Command Line. Commands such as cd, pwd and ls allow you to navigate and view the file system.

PHP provides a mechanism for issuing these commands (and all others in /bin, /usr/bin, etc.) and accessing their output.

popen() allows you to execute these commands, having the output streamed into your script for processing.

$pp = popen("/bin/ls" , "r");

The above line of code would open a stream of data for reading created by executing the ls command on the directory where the script being run resides. $pp can then be used as a pointer for accessing this stream using PHP built-in commands such as fgets().

$line = trim( fgets($pp, 512) );

This line of code would read the first line of output from ls and delete the line-terminating newline.

As a starter script you can place the following code into a file (ls.php would be a good name) which you can run from the Command Line.

<?php
$pp = popen("/bin/ls", "r");
while ($line = trim(fgets($pp, 256)))
{
   echo $line . "\n";
}
pclose($pp);
?>

This complete, short script will do a full listing of the directory in which the script exists.

Notes


© 2005 DFStermole
Created: 27 Nov 05
Last Modified: 27 Nov 05