tags:

views:

59

answers:

4

I am just starting php. I am just curious if there is a better way to do this. This displays all of my scripts in the same folder as this script.

I am not sure if it is standard to use the exec command. It does not seem very portable.

<html>
<head>
   <title>My PHP Practice Scripts</title>
</head>

<body>
   <center><h1>PHP Scripts</h1></center>
   <?php
      exec("ls -1 *.php", $output);

      foreach ($output as &$tmp){
         echo "<a href=\"$tmp\">$tmp</a><br>";
      }
   ?>
</body>
</html>
+3  A: 

There are directory functions for such operations: http://www.php.net/manual/en/ref.dir.php

Kel
more OS neutral. Better approach.
Visionary Software Solutions
@Visionary: I missed the point about portability. Removed my answer.
BoltClock
+1  A: 

"exec" is portable beacuse is an API! :-) What is not portable is the string that represents the command line you invoke through "exec".

In this case you can use a PHP API to read the directory. That is portable on every OS you use onto your server.

Ex: dir class in PHP

robob
+1  A: 

Is using the exec command standard practice?

No. Using exec to interact with the host operating system is a very non-portable practice. For virtually any situation, there is an OS-independent solution; in this particular case, you can find all the files in the current directory with glob, readdir or scandir.

Using eval in a program that accepts any form of user input also often leads to serious security risks. Your program doesn't suffer from such risks currently, but it is also very trivial.

meagar
while it isn't part of the question, you get props for mentioning that `eval()` should never be used w/ user accessible data.
sholsinger
A: 

Yes, there's a better way to do what you're after. There's glob or readdir for starters.

As far as "standard practice goes", you'll see a lot of this in PHP land. If a developer doesn't know PHP's huge codebase very well but does know the shell they'll end up using exec and backticks (``) all over the place to get their job done. It's a standard practice that some percentage of PHP developers hate, and another percentage couldn't live without. Get used to seeing it.

Alan Storm