Page 1 of 1

Any reason not to use exec() for something like this?

Posted: Sun Nov 04, 2012 10:52 pm
by TildeHash
If I want to list a directory's contents as hyperlinks I can go about it in two very simple ways. Both methods allow me to display files based on their extension, and with an added 'is_dir' statement I may omit directories if I want.

The first way is to use 'glob' like this:

Code: Select all

<?php
	foreach (glob('./' . '*', 0) as $file) {
		echo '<a href="' . $file . '">' . basename($file) . '</a><br>' . PHP_EOL;
	}
?>
This way is short and simple.

The second way is to use 'exec' like this:

Code: Select all

<?php
	$files = array();
	exec('ls ./', $files);

	foreach ($files as $file) {
		echo '<a href="./' . $file . '">' . $file . '</a><br>' . PHP_EOL;
	}
?>
I like this method better, as reading directories recursively is much easier. And I get all the power of ls, so I can list modification times, permissions, user, group, file size, and all that with the one 'exec' line. However, if I'm not mistaken, 'exec' invokes the operating system's command-line and returns its output. So it seems that this method would be slower or more prone to security issues. (I already know it doesn't work on Windows servers, and I really don't care about that.)

Is there any significant reason not to use 'exec' instead of 'glob' for stuff like this?

Re: Any reason not to use exec() for something like this?

Posted: Mon Nov 05, 2012 2:02 am
by requinix
I wouldn't use exec() for it. You can get all the information you need with PHP, and without (most of) the risk of things being disabled or insecure, or being on a different operating system, or other things PHP handles for you transparently.

They're wordy but try the DirectoryIterator or RecursiveDirectoryIterator classes.

Re: Any reason not to use exec() for something like this?

Posted: Tue Nov 06, 2012 3:27 pm
by pickle
I avoid using exec() whenever possible - simply because you're running a command line ...command, and that could cause a security issue.

Alternatively, if the directory is already publicly viewable, have you looked into allowing Apache to output the default directory index?