Execute a PHP script from another PHP script

后端 未结 11 1660
伪装坚强ぢ
伪装坚强ぢ 2020-12-02 14:04

How would I make my server run a php script by triggering it manually using php? Basically I have a pretty big cronjob file that is ran every 2 hours, but I want to be able

11条回答
  •  鱼传尺愫
    2020-12-02 14:41

    You can invoke a PHP script manually from the command line

    hello.php
    
    
    Command line:
    php hello.php
    
    Output:
    hello world!
    

    See the documentation: http://php.net/manual/en/features.commandline.php


    EDIT OP edited the question to add a critical detail: the script is to be executed by another script.

    There are a couple of approaches. First and easiest, you could simply include the file. When you include a file, the code within is "executed" (actually, interpreted). Any code that is not within a function or class body will be processed immediately. Take a look at the documentation for include (docs) and/or require (docs) (note: include_once and require_once are related, but different in an important way. Check out the documents to understand the difference) Your code would look like this:

     include('hello.php');
     /* output
     hello world!
     */
    

    Second and slightly more complex is to use shell_exec (docs). With shell_exec, you will call the php binary and pass the desired script as the argument. Your code would look like this:

    $output = shell_exec('php hello.php');
    echo "
    $output
    "; /* output hello world! */

    Finally, and most complex, you could use the CURL library to call the file as though it were requested via a browser. Check out the CURL library documentation here: 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 "
    $output
    "; /* output hello world! */

    Documentation for functions used

    • Command line: http://php.net/manual/en/features.commandline.php
    • include: http://us2.php.net/manual/en/function.include.php
    • require: http://us2.php.net/manual/en/function.require.php
    • shell_exec: http://us2.php.net/manual/en/function.shell-exec.php
    • curl_init: http://us2.php.net/manual/en/function.curl-init.php
    • curl_setopt: http://us2.php.net/manual/en/function.curl-setopt.php
    • curl_exec: http://us2.php.net/manual/en/function.curl-exec.php
    • curl_close: http://us2.php.net/manual/en/function.curl-close.php

提交回复
热议问题