Executing Shell Commands with PHP

In this sixth part of an eight-part series on working with the file and operating systems of a computer with PHP, you’ll learn how to use PHP to write to a file and how to execute shell commands. This article is excerpted from chapter 10 of the book Beginning PHP and PostgreSQL 8: From Novice to Professional, written by W. Jason Gilmore and Robert H. Treat (Apress; ISBN: 1590595475).

Writing to a File

This section highlights several of the functions used to output data to a file.

fwrite()

int fwrite (resource handle, string string [, int length])

The fwrite() function outputs the contents of string to the resource pointed to by handle. If the optional length parameter is provided, fwrite() will stop writing when length characters have been written. Otherwise, writing will stop when the end of the string is found. Consider this example:

<?php
$subscriberInfo = "Jason Gilmore|wj@example.com";
$fh = fopen("/home/www/data/subscribers.txt", "at");
fwrite($fh, $subscriberInfo);
fclose($fh);
?>


Tip If the optional length parameter is not supplied to fwrite(), the magic_quotes_runtime configuration parameter will be disregarded. See Chapters 2 and 9 for more information about this parameter.


fputs()

int fputs (resource handle, string string [, int length])

The fputs() function operates identically to fwrite(). Presumably, it was incorporated into the language to satisfy the terminology preferences of C/C++ programmers.

{mospagebreak title=Reading Directory Contents}

The process required for reading a directory’s contents is quite similar to that involved in reading a file. This section introduces the functions available for this task, and also introduces a function new to PHP 5 that reads a directory’s contents into an array.

opendir()

resource opendir (string path)

Just as fopen() opens a file pointer to a given file, opendir() opens a directory stream specified by path.

closedir()

void closedir (resource directory_handle)

The closedir() function closes the directory stream pointed to by directory_handle.

readdir()

string readdir (int directory_handle)

The readdir() function returns each element in the directory specified by directory_handle. You can use this function to list all files and child directories in a given directory:

<?php
$dh = opendir(‘/usr/local/apache2/htdocs/’);
while ($file = readdir($dh))
echo "$file <br>";
closedir($dh);
?>

Sample output follows:

——————————————–.
..
articles
images
news
test.php
——————————————–

Note that readdir() also returns the . and .. entries common to a typical Unix directory listing. You can easily filter these out with an if statement:

if($file != "." AND $file != "..")…

scandir()

array scandir (string directory [,int sorting_order [, resource context]])

The scandir() function, which is new to PHP 5, returns an array consisting of files and directories found in directory, or returns FALSE on error. Setting the optional sorting_order parameter to 1 sorts the contents in descending order, overriding the default of ascending order. Revisiting the example from the previous section:

<?php
print_r(scandir("/usr/local/apache2/htdocs"));
?>

This returns:

——————————————–Array ( [0] => . [1] => .. [2] => articles [3] => images
[4] => news [5] => test.php )
——————————————–

The context parameter refers to a stream context. You’ll learn more about this topic in Chapter 16.

{mospagebreak title=Executing Shell Commands}

The ability to interact with the underlying operating system is a crucial feature of any programming language. This section introduces PHP’s capabilities in this regard.

PHP’s Built-in System Commands

Although you could conceivably execute any system-level command using a function like exec() or system(), some of these functions are so commonplace that the developers thought it a good idea to incorporate them directly into the language. Several such functions are introduced in this section.

rmdir()

int rmdir (string dirname)

The rmdir() function removes the directory specified by dirname, returning TRUE on success and FALSE otherwise. As with many of PHP’s file system functions, permissions must be properly set in order for rmdir() to successfully remove the directory. Because PHP scripts typically execute under the guise of the server daemon process owner, rmdir() will fail unless that user has write permissions to the directory. Also, the directory must be empty.

To remove a nonempty directory, you can either use a function capable of executing a system-level command, like system() or exec(), or write a recursive function that will remove all file contents before attempting to remove the directory. Note that in either case, the executing user (server daemon process owner) requires write access to the parent of the target directory. Here is an example of the latter approach:

<?php
function delete_directory($dir)
{
if ($dh = @opendir($dir))
{

/* Iterate through directory contents. */
while (($file = readdir ($dh)) != false)
{
if (($file == ".") || ($file == "..")) continue;
if (is_dir($dir . ‘/’ . $file))
delete_directory($dir . ‘/’ . $file);
else
unlink($dir . ‘/’ . $file);
} #endWHILE

@closedir($dh);
rmdir($dir);
} #endIF
} #end delete_directory()

$dir = "/usr/local/apache2/htdocs/book/chapter10/test/";
delete_directory($dir);
?>

rename()

boolean rename (string oldname, string newname)

The rename() function renames a file specified by oldname to the new name newname, returning TRUE on success and FALSE otherwise. Because PHP scripts typically execute under the guise of the server daemon process owner, rename() will fail unless that user has write permissions to that file.

touch()

int touch (string filename [, int time [, int atime]])

The touch() function sets the file filename’s last-modified and last-accessed times, returning TRUE on success or FALSE on error. If time is not provided, the present time (as specified by the server) is used. If the optional atime parameter is provided, the access time will be set to this value; otherwise, like the modification time, it will be set to either time or the present server time.

Note that if filename does not exist, it will be created, assuming that the script’s owner possesses adequate permissions.

Please check back for the next part of the series.

[gp-comments width="770" linklove="off" ]

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort