1.问题的产生
近日使用PHP执行一个长达40s的脚本任务,但是在系统中发现该脚本被执行了两次,经过反复检查代码,仍然没有所获。
2.分析原因
代码经检查后没有问题,我们怀疑是浏览器多次请求导致的,因此我们打开了chrome development tool,截图如下:
如上图所示,在脚本执行完成后,chrome回去请求favicon.ico文件,但是这个文件在我们的服务器上面是不存在的。
3.确定原因
favicon.ico文件不存在,应该返回404才对,但是一直显示pending,这个应该是调用了我们的php脚本,然后我们在结合httpd-vhosts.conf文件的设置
<VirtualHost *:80>
ServerName autohome2.dev
DocumentRoot "D:\wamp64\www\autohome"
<Directory "D:\wamp64\www\autohome">
# use mod_rewrite for pretty URL support
RewriteEngine on
# If a directory or a file exists, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward the request to index.php
RewriteRule . index.php
# use index.php as index file
DirectoryIndex index.php
# ...other settings...
# Apache 2.4
Require all granted
## Apache 2.2
# Order allow,deny
# Allow from all
</Directory>
</VirtualHost>
我们可以看到如下的rewrite设置
# If a directory or a file exists, use the request directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Otherwise forward the request to index.php
RewriteRule . index.php
从设置可以看出,ico文件的请求就是被转发到index.php文件的。
至此,我们已经清楚了脚本被两次调用的原因。
4.问题的解决
我们可以把我们的脚本名称设置为script.php,这样ico的请求就不会被转发到script.php,或者我们把下面的设置注释掉,禁用rewrite:
#RewriteEngine on
不过如果关闭了rewrite功能,可能会影响某些框架的使用,因为很多的框架就是使用index.php作为入口,把其他的请求转发到index.php。