Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

173
Visualizações
Php script is automatically being invoked multipletimes

I am facing a strange issue here. I am using javascript ajax(I used jquery). Now the scenario is;

One ajax call is invoking a php script which is basically a long running process and it sets some session variables.

Later in some intervals(lets say in each 2 sec) I am running another ajax calls to check the session variables to know when the process(first php script execution) is completed.

First php script is fetching data from database and wring it into a file. In each fetching I am counting the loop number and storing it into a session variable to keep some kind of tracking record. Like;

 $i=0;
 $_SESSION['time']=date('m-d-Y H:i:s');
 while(...)
 {
     ini_set('session.use_only_cookies', false);
     ini_set('session.use_cookies', false);
     ini_set('session.use_trans_sid', false);
     ini_set('session.cache_limiter', null);
     session_start();
     $_SESSION['tracksatus']="loop number : ".$i." time is :"$_SESSION['time'];
     session_write_close();

     $i++;

     ......
     ......
 }

Another php script which I am invoking via setInterval ajax is just doing like;

 echo $_SESSION['trackstatus']

The set interval ajax is returning me like;

  loop number 1 time is m-d-Y H:i:s
  loop number 5 time is m-d-Y H:i:s
  loop number 8 time is m-d-Y H:i:s
  ......

Then after few call again;

  loop number 1 time is m-d-Y H1:i1:s1
  .....

Notice the change of H:i:s to H1:i1:s1

So as per my understanding the php script is invoking twice. And for your information same code was working just before 12 hrs may be. And I faced this issue before and somehow solved it(trial and error so I don't know how or may be automatically....ok actually I have no clue).

Can you please give me an insight what I am doing wrong? Please mention if you need more information.

And the funny thing is that it is working as expected just after asking this question without even changing a single line of code. But I want to know the reason.

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

I think that I know what the reason, PHP writes session variables to file, but it do it only on end of script execution, so you can`t see the changes of session in another script before end of long one.

You can fix it by adding session_write_close(); session_start(); after each change of session data.

session_write_close will write changes to HD, so another script can read it. session_start will load session from HD, but make sure that your another script make no changes for a session, these changes will be overwritten by your long script.

And one more thing if you are using separate domains: Before actual AJAX call happen your browser sends OPTIONS request to the same URL for checking CORS headers. So on start of your script check the HTTP METHOD and if it HEAD or OPTIONS make die();

about 4 years ago · Santiago Trujillo Relatório

0

Instead of using sessions, try using a temp file to keep count with a dynamic ID

Javascript

var time = Date.now();
$.get('/firstURL?time='+time);
setInterval(function(){
    $.get('/secondURL?time='+time, function(response){
        console.log(response);
    }
}, 1000);

PHP 1st URL

<?php

$id = $_GET['time'];
$count = 0;

while(...) {
    // Do your stuff

    $count++;
    file_put_contents("/tmp/{$id}", $count);
}

?>

PHP 2nd URL

<?php

$id = $_GET['time'];
$count = 0;

try {
    $count = file_get_contents("/tmp/{$id}");
} catch(Exception $e) {}

echo $count;

?>
about 4 years ago · Santiago Trujillo Relatório

0

As other have said PHP does not write the session until execution has finished. you better off creating a php function that you call that writes a file with the progress and then your second ajax call just reads the file.

function updateCreateProgress($jobStartTime, $progress){
    file_put_contents('/tmp/'.$jobStartTime.'.txt', $progress);
}

function completeProgress($jobStartTime){
    unlink('/tmp/'.$jobStartTime.'.txt')
}

now your second script can check for '/tmp/'.$jobStartTime.'.txt' if it's there read it using file_get_contents if its not there report back it has finished.

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda