-1

I want to make a delay in my PHP codes to alert my Javascript code and then run header function in the bottom.

I tried to implement my ideas with sleep function in php . But when i tried it , all of the program sleeps for seconds .


<?php

echo "<pre>";
print_r($_FILES);
echo "</pre>" ;

$randNum = rand(0,999);
$fileAd = "Images\User".$randNum ;
$mkFile = mkdir($fileAd);
$fileDir = __DIR__ ;
$uploadFile = $fileDir. "\\" . $fileAd . "\\" . $_FILES['userfile']['name'];

if(move_uploaded_file($_FILES['userfile']['tmp_name'],$uploadFile)){
    echo "<script>
    alert(\"Thanks\");
    </script>";



}


$contentFile = $fileDir . "\\" . $fileAd . "\\" . "User" . $randNum . ".txt" ;
$str = "" ;

foreach($_POST as $key=>$value){
    if(is_array($value)){
        $str .= "$key : ";
        $str .= implode(" , ",$value).PHP_EOL;

    }else {
        $str .= "$key : $value".PHP_EOL;
    }
}

file_put_contents($contentFile,$str);

header("Location: sugFuncs.php");

?>


Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175
Omidgh
  • 43
  • 3
  • PHP is single threaded, if you pause it, it will pause everything. PHP is completely executed before _anything_ prints on the page, this includes your javascript. Also, you cannot set headers after anything has been printed on the page, so you couldn't echo any JavaScript (or anything) and then change the headers. – GrumpyCrouton Oct 17 '19 at 15:25
  • you can turn your php into "multithreaded" application with pcntl_fork() and do a sleep inside of fork'ed process. (term multithreaded is not very suitable technically speaking, but it gets the point across) – Dimi Oct 17 '19 at 15:33
  • I want to alert something when i received data from user.I'm a beginner in php and I'm learnin it yet . – Omidgh Oct 17 '19 at 16:17

1 Answers1

0

It is because you sleep at server-side. The server would need to tell the client to sleep instead of sleeping on its own, like:

if(move_uploaded_file($_FILES['userfile']['tmp_name'],$uploadFile)){
    echo "<script>
    setTimeout(() => alert(\"Thanks\"), 5000);
    </script>";
}
Lajos Arpad
  • 64,414
  • 37
  • 100
  • 175