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

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
TildeHash
Forum Commoner
Posts: 43
Joined: Fri Jul 16, 2010 7:17 am
Location: Apple Valley, California

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

Post 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?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

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

Post 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.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

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

Post 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?
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply