PHP seems to execute script twice

人走茶凉 提交于 2021-01-27 04:08:30

问题


My web server is acting wierd. It seems like it executes scripts (PHP) twice before sending then to apache.

I've run this file:

<?php
echo '<pre>';
session_start();
$_SESSION['index']++;
echo '<br>';
print_r($_SESSION);
?>

And I know that ++ will give a notice at first, but it's just to investigate if it runs twice. Anyway, the printed session shows that the index-index increases by two each time you load the page.

The webserver is apache2, php5 installed on a debian unit.

Anyone has any ideas?


回答1:


echo '<pre>'; //Headers and cookies already sent.
session_start(); //Cannot set cookie anymore, system tries again, I guess

Start session first, then output anything. Try placing session_start(); on top




回答2:


I can't thank the poster of this question enough. His session test made me realize that I had the same problem of a php script running several times.

In my script I had two PDO functions seperated from each other by an if-else-construct. One was a simple select, and one a simple insert function. But everytime I ran the script, both pdo commands got executed. PDO ended up writing rows in my table which had the entry 'public'.

So what happened? My page got send multiple times because of ELEMENTS IN THE HTML CODE THAT COULD NOT BE FOUND. In my case that was a css file which was named incorrectly. When I solved that (after 4 hours of looking at code) the problem disappeared. Also broken images for example trigger the same event.




回答3:


Oke folks, found a completely insane solution to this problem. Just posting for future reference. I recently installed a HTML validator in Chrome (an extension). This seems to be the culprit. After everything has loaded, the validator seems to be re-requesting the page so it is executed twice. Nice plugin. Not! Took me about half a day to figure this out.




回答4:


I am seeing the same behaviour... a $_POST would be present the first time the page ran, then wouldn't the second time... scoured the code to find why the page might be posting back to itself again. No avail.

After seeing user1601869's answer above, I started checking. I had some links to stylesheets I hadn't written yet, so put skeletons of those in.

It turns out that for me, the culprit was:

<link rel="shortcut icon" href="">

This was just a placeholder for an icon that was causing my page to break. I suggest that if you have the same problem, look for links in the <HEAD></HEAD> that are broken!



来源:https://stackoverflow.com/questions/14966984/php-seems-to-execute-script-twice

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