我有一个名为sample.php
的php文件,其中包含以下内容:
<?php
echo "Hello World!";
?>
我想做的是,使用第二个php脚本运行这个php脚本。
我认为shell_exec
可以帮助我,但我不知道它的语法。
顺便说一下,我想用cpanel
执行这些文件。所以我必须执行shell。
有办法做到这一点吗?
如果需要将php文件的输出写入变量,请使用ob_start和ob_get_contents函数。见下文:
<?php
ob_start();
include('myfile.php');
$myStr = ob_get_contents();
ob_end_clean();
echo '>>>>' . $myStr . '<<<<';
?>
因此,如果您的"myfile.php"包含以下内容:
<?php
echo 'test';
?>
然后你的输出将是:
>>>>test<<<<
您可以将cURL用于远程请求。以下来自php.net:
<?php
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, 0);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
?>
这里有一个很好的教程:http://www.sitepoint.com/using-curl-for-remote-requests/
也可以考虑在此处观看此YouTube视频:http://www.youtube.com/watch?v=M2HLGZJi0Hk
你可以试试这个:
主PHP文件
<?php
// change path/to/php according to how your system is setup
// examples: /usr/bin/php or /opt/lampp/bin/php
echo shell_exec("/path/to/php /path/to/php_script/script.php");
echo "<br/>Awesome!!!"
?>
辅助PHP文件
<?php
echo "Hello World!";
?>
运行主PHP文件时的输出
Hello World!
Awesome!!!
希望它能帮助你。
试试这个:
<?php
// change path/to/php according to how your system is setup
// examples: /usr/bin/php or /opt/lampp/bin/php
$output = shell_exec("/path/to/php /path/to/php_script/script.php");
print_r($output);
?>
这可能对你有帮助。
需要强调的是,包含/执行用户生成的代码是危险的。使用系统调用(exec
、shell_exec
、system
)而不是include
有助于分离执行上下文,但这并不安全。考虑适当的卫生设施或沙箱。
考虑到这一点,这里有一个工作示例,包括生成(临时)文件、执行它和清理:
<?php
// test content
$code = <<<PHP
echo "test";
PHP;
// create temporary file
$d=rand();
$myfile="$d.php";
file_put_contents($myfile,"<?php'n$code'n?>");
// start capture output
ob_start();
// include generate file
// NOTE: user-provided code is unsafe, they could e.g. replace this file.
include($myfile);
// get capture output
$result = ob_get_clean();
// remove temporary file
unlink($myfile);
// output result
echo "================'n" . $result . "'n================'n" ;
输出:
================
test
================
terminal view:
abgth@ubuntu:/var/www$ cat > test.php
<?php
echo shell_exec("php5 /var/www/check.php");
?>
abgth@ubuntu:/var/www$ cat > check.php
<?php
echo 'hi';
?>
abgth@ubuntu:/var/www$ php5 test.php
hi
我希望你正在寻找这个
转到终端并键入
php文件名.php
filename.php应该是您要执行的文件的名称!