Question

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>
Was it helpful?

Solution

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

OTHER TIPS

"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

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top