Laravel custom helper - undefined index SERVER_NAME

痞子三分冷 提交于 2020-01-23 11:06:07

问题


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.


回答1:


$_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.




回答2:


Artisan works on the command line, so there is no SERVER_NAME. Use something like:

Request::server('SERVER_NAME', 'UNKNOWN')

instead of $_SERVER[] to provide a default to avoid the error.




回答3:


Maybe it's because when you run this helper as usually, SERVER_NAME has something in it, because you run it from browser.

When you run Artisan command, there is not any server, that's why SERVER_NAME is empty.



来源:https://stackoverflow.com/questions/35837248/laravel-custom-helper-undefined-index-server-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!