Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP seems to execute script twice

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?

like image 989
jorel Avatar asked Feb 19 '13 20:02

jorel


People also ask

How do I run a PHP script only once?

Of course it is possible to add a cron job and then delete it after the job has been executed once, but it is not a very good method. To run a PHP script at a given time only once, use the Linux's at command. at schedules a job to be executed only once.

How PHP scripts are executed?

Broadly speaking, the PHP interpreter goes through four stages when executing code: Lexing. Parsing. Compilation.

Does PHP run sequentially?

PHP interpreter is always sequential and it never executes code in parallel. In Chapter 9, Multithreaded and Distributed Computing with pthreads and Gearman, we'll use PHP module pthreads that makes it possible to run PHP code in multiple threads, but we'll see that it's not as simple as it seems.

How do I stop a PHP script from running?

The exit() function in PHP is an inbuilt function which is used to output a message and terminate the current script. The exit() function only terminates the execution of the script. The shutdown functions and object destructors will always be executed even if exit() function is called.


1 Answers

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

like image 154
sybear Avatar answered Oct 01 '22 10:10

sybear