如何通过使用php手动触发它来使我的服务器运行php脚本?基本上我有一个相当大的cronjob文件,每2小时运行一次,但我希望能够自己手动触发文件,而不必等待它加载(我希望它在服务器端完成).
编辑:我想从php文件执行文件...不是命令行.
Chr*_*ker 106
您可以从命令行手动调用PHP脚本
hello.php
<?php
echo 'hello world!';
?>
Command line:
php hello.php
Output:
hello world!
Run Code Online (Sandbox Code Playgroud)
请参阅文档:http://php.net/manual/en/features.commandline.php
编辑 OP编辑了问题以添加关键细节:脚本将由另一个脚本执行.
有几种方法.首先也是最简单的,您可以简单地包含该文件.当您包含文件时,其中的代码是"已执行"(实际上,已解释).任何不在函数或类体内的代码都将立即处理.看一下include
(docs)和/或require
(docs)的文档(注意:include_once
并且require_once
是相关的,但在重要方面有所不同.查看文档以了解其中的区别)您的代码如下所示:
include('hello.php');
/* output
hello world!
*/
Run Code Online (Sandbox Code Playgroud)
第二个,稍微复杂一点是使用shell_exec
(docs).使用shell_exec
,您将调用php二进制文件并将所需的脚本作为参数传递.您的代码如下所示:
$output = shell_exec('php hello.php');
echo "<pre>$output</pre>";
/* output
hello world!
*/
Run Code Online (Sandbox Code Playgroud)
最后,也是最复杂的,您可以使用CURL库来调用文件,就像通过浏览器请求它一样.查看CURL库文档:http://us2.php.net/manual/en/ref.curl.php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.myDomain.com/hello.php");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true)
$output = curl_exec($ch);
curl_close($ch);
echo "<pre>$output</pre>";
/* output
hello world!
*/
Run Code Online (Sandbox Code Playgroud)
所用功能的文档
include
:http://us2.php.net/manual/en/function.include.phprequire
:http://us2.php.net/manual/en/function.require.phpshell_exec
:http://us2.php.net/manual/en/function.shell-exec.phpcurl_init
:http://us2.php.net/manual/en/function.curl-init.phpcurl_setopt
:http://us2.php.net/manual/en/function.curl-setopt.phpcurl_exec
:http://us2.php.net/manual/en/function.curl-exec.phpcurl_close
:http://us2.php.net/manual/en/function.curl-close.phpOP对如何从脚本调用php脚本改进了他的问题.php语句'require'有利于依赖,因为如果找不到所需的脚本,脚本将停止.
#!/usr/bin/php
<?
require '/relative/path/to/someotherscript.php';
/* The above script runs as though executed from within this one. */
printf ("Hello world!\n");
?>
Run Code Online (Sandbox Code Playgroud)
您可以使用反引号表示法:
`php file.php`;
Run Code Online (Sandbox Code Playgroud)
您也可以将其放在php文件的顶部以指示解释器:
#!/usr/bin/php
Run Code Online (Sandbox Code Playgroud)
将其更改为放置php的位置。然后授予对该文件的执行权限,您可以在不指定php的情况下调用该文件:
`./file.php`
Run Code Online (Sandbox Code Playgroud)
如果要捕获脚本的输出:
$output = `./file.php`;
echo $output;
Run Code Online (Sandbox Code Playgroud)
小智 5
我更喜欢使用
require_once('phpfile.php');
Run Code Online (Sandbox Code Playgroud)
有很多选择可供您选择。以及保持事物清洁的好方法。
归档时间: |
|
查看次数: |
170472 次 |
最近记录: |