如何检查php脚本是否在本地服务器上运行?
是否可以检查网站(php)是在本地运行还是在托管服务器上运行? 如果网站在本地运行,我想启用一些日志,并且我不希望这些日志出现在在线网站上。 我可以设置一个变量 $local=1;
但我必须在上传之前更改它..有没有办法自动执行此任务?
本地服务器:WampServer 2.0 / Apache 网络服务器:阿帕奇
Is it possible to check if the website (php) is running locally or on a hosted server?
I want to enable some logs if the website is running locally and I don't want these to appear on the site online..
I can set a variable $local=1;
but I'll have to change that before uploading.. is there anyway to automate this task?
Local Server : WampServer 2.0 / Apache
WebServer: Apache
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
检查
$_SERVER['REMOTE_ADDR']=='127.0.0.1'
。仅当在本地运行时才会出现这种情况。请注意,这也意味着服务器本地。因此,如果服务器上运行任何向 PHP 页面发出请求的脚本,它们也将满足此条件。Check
$_SERVER['REMOTE_ADDR']=='127.0.0.1'
. This will only be true if running locally. Be aware that this means local to the server as well. So if you have any scripts running on the server which make requests to your PHP pages, they will satisfy this condition too.我相信最好的方法是“伪造”测试模式,这可以通过在本地环境中创建文件来完成。
当我使用这种方法时,我创建了一个名为
testing.txt
的空文本文件,然后使用以下代码:这种方法与任何操作系统 100% 兼容,如果需要,您可以使用多个测试文件更精细的方法(例如
development.txt
、testing.txt
、staging.txt
或product.txt
)以便自定义您的部署过程。I believe the best approach is to 'fake' a testing mode, which can be done by creating a file in your local environment.
When I used this approach I created an empty text file called
testing.txt
and then used the following code:This approach is 100% compatible with any Operating System and you can use several test files in case you want a more granular approach (e.g.
development.txt
,testing.txt
,staging.txt
, orproduction.txt
) in order to customise your deployment process.您应该自动化部署
这不是您问题的直接答案,但在我看来是更好的方法。在自动化部署过程中,设置像
$local = true
这样的变量,就像其他配置值(例如数据库连接)一样,不是手动的、容易出错的任务。在我看来,检查“本地性”是错误的方式:您不想向每个本地访问者(代理可能是其中一个)显示您的日志,但仅在部署在测试环境中时才显示日志。
一个流行的自动化部署工具是 Capistrano,应该有以 PHP 为中心的工具也。
You should automate deployment
This is not directly the answer to your question, but in my opinion the better way. In an automated deployment process, setting a variable like
$local = true
, like other configuration values (for example your db-connection), would be no manual, error prone, task.Checking for 'localness' is in my opinion the wrong way: you dont want to show your logs to every local visitor (a Proxy may be one), but only when deployed in a testing environment.
A popular tool for automated deployment is Capistrano, there should be PHP-Centric tools too.
以防万一这对任何人都有用,我做了这个函数,因为上面的答案并没有真正达到我想要的效果:
Just in case this is useful to anybody, I made this function as the above answers didn't really do what I was looking for:
我构建了这个函数来检查当前的服务器名称是否有名称服务器记录,通常本地服务器没有。
I have build this function that checks if current server name has name server records, normally local server don't has.
你的远程服务器不可能有C盘!所以我用这个运行:
Your remote server is unlikely to have a C drive! So I run with this: