Cron Script Doesn't Work in Server Side

2019-08-09 22:32发布

问题:

i have some cron files. And it was in under httpdocs. But i decided to move under cron folder. And i change the script.

config.php to ../config.php

When i call script from browser every thing works fine. But when i call from ssh i got en error undefined index : SERVER_NAME

I couldn't run cronjob. What can i do that ?

stock.php file

    include_once '../config.php';

    require_once CLASS_PATH.'class.product.php';
    include_once INC_PATH.'functions.php';

....

config.php file

    if ( !defined('ABSPATH') ) {
    define('ABSPATH', dirname(__FILE__).'/');
}
define('PROTOCOL',(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') ? 'https' : 'http');

    define('HOST', PROTOCOL.'://'.$_SERVER['SERVER_NAME']);

    define('CLASS_PATH',ABSPATH.'includes/class/');
    define('INC_PATH',ABSPATH.'includes/');

    //if (isset($_SERVER['SERVER_NAME'])){
        define('PRODUCT_IMG_PATH', 'images/product/');
    //}

    define('HEAD_META',ABSPATH.'view/head-meta.php');
    define('NAVBAR',   ABSPATH.'view/navbar.php');
    define('HEADER',   ABSPATH.'view/header.php');
    define('FOOTER',   ABSPATH.'view/footer.php');

回答1:

The reason is that when you are running through ssh or command line you are in CLI mode, therefore none of those CGI variables can be used. It's recommended to use getenv() command instead which supports some of defined variables in CLI mode. However you need to configure and define them in you php.ini

You may need to look at Command line usage documentation for more details



回答2:

How are you running it from cron? It seems that the server variables aren't being found when you run from terminal - which would make sense if you were php-running the file on the server. The SERVER-variables in php are set by the webserver - i.e. what answers a request over port 80 to the files in a specific location.

Here's php's documentation on server variables. http://www.php.net/manual/en/reserved.variables.server.php



回答3:

You web server is the one who fills the php $_SERVER array. I quote from the manual (http://www.php.net/manual/en/reserved.variables.server.php):

The entries in this array are created by the web server. There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here.

Obviously, if you call your script from the command line, there's no web servers to fill the $_SERVER array, and that's the reason of your problem.

To solve it, you can modify your config.php to load predefined values to the variables you need in case they don't exist. It would be something like this for every undef var:

if (!isset($_SERVER['SERVER_NAME'])) $_SERVER['SERVER_NAME']="localhost";


标签: php ssh