PHP 初学者:使用 exec 命令是标准做法吗?
我刚刚开始 php.我只是好奇是否有更好的方法来做到这一点。这将在与此脚本相同的文件夹中显示我的所有脚本。
我不确定使用 exec 命令是否是标准的。看起来不太便携。
<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>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
有用于此类操作的目录函数: http://www.php.net/manual /en/ref.dir.php
There are directory functions for such operations: http://www.php.net/manual/en/ref.dir.php
“exec”是可移植的,因为它是一个 API! :-) 不可移植的是代表您通过“exec”调用的命令行的字符串。
在这种情况下,您可以使用 PHP API 来读取该目录。这在您服务器上使用的每个操作系统上都是可移植的。
例如: PHP 中的 dir 类
"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
不可以。使用
exec
与主机操作系统交互是一种非常不可移植的做法。几乎对于任何情况,都有一个独立于操作系统的解决方案;在这种特殊情况下,您可以使用glob< 查找当前目录中的所有文件/code>
、
readdir
或scandir
。在接受任何形式的用户输入的程序中使用
eval
通常也会导致严重的安全风险。您的程序目前不会遭受此类风险,但它也非常微不足道。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 withglob
,readdir
orscandir
.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.是的,有更好的方法来完成您所追求的事情。有 glob 或 readdir。
就“标准实践而言”而言,您会在 PHP 领域看到很多这样的情况。如果开发人员不太了解 PHP 庞大的代码库,但了解 shell,他们最终会到处使用 exec 和反引号 (``) 来完成工作。这是一些 PHP 开发人员讨厌的标准做法,而另一些开发人员则离不开它。看到它就习惯了。
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.