Php – Laravel custom helper – undefined index SERVER_NAME

laravellaravel-5.1PHP

In Laravel 5.1, I created a custom helper file: custom.php which I load in composer.json:

"autoload": {
    "files": [
        "app/Helpers/custom.php"
    ]
},

and it contains this method:

function website() {
    return str_replace('dashboard.', '', $_SERVER['SERVER_NAME']);
}

It works as expected, but every time I do php artisan commands, I get a call stack and this message:

Notice: Undefined index: SERVER_NAME in /path/to/custom.php on line 4

Why is this so? The method returns the correct value when run from within my Laravel app.

Best Answer

$_SERVER['SERVER_Name'] global variable is only accessible when running your application through a browser. It will through an error when you run your application through php-cli/through the terminal. Change your code to

function website() {

    if(php_sapi_name() === 'cli' OR defined('STDIN')){
        // This section of the code runs when your application is being runned from the terminal
        return "Some default server name or you can use your environment to set your server name"
    }else{
        // This section of the code run when your app is being run from the browser
        return str_replace('dashboard.', '', $_SERVER['SERVER_NAME']);
    }
}

Hope this helps you.

Related Topic