Laravel自定义帮助程序-未定义索引SERVER_NAME [英] Laravel custom helper - undefined index SERVER_NAME
问题描述
在Laravel 5.1中,我创建了一个自定义帮助程序文件:custom.php
,该文件加载到composer.json
中:
In Laravel 5.1, I created a custom helper file: custom.php
which I load in composer.json
:
"autoload": {
"files": [
"app/Helpers/custom.php"
]
},
,它包含以下方法:
function website() {
return str_replace('dashboard.', '', $_SERVER['SERVER_NAME']);
}
它按预期工作,但是每次我执行php artisan
命令时,我都会得到一个调用堆栈和以下消息:
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
为什么会这样?从我的Laravel应用程序中运行时,该方法返回正确的值.
Why is this so? The method returns the correct value when run from within my Laravel app.
推荐答案
$ _ SERVER ['SERVER_Name']全局变量仅在通过浏览器运行应用程序时可访问.当您通过php-cli/通过终端运行应用程序时,它将出现错误.将您的代码更改为
$_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']);
}
}
希望这对您有所帮助.
这篇关于Laravel自定义帮助程序-未定义索引SERVER_NAME的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!