user1631995
user1631995

Reputation:

Delay PHP execution until JavaScript cookie set?

I am trying to delay PHP execution until a cookie is set through JavaScript. The code is below, I trimmed the createCookie JavaScript function for simplicity (I've tested the function itself and it works).

<?php
if(!isset($_COOKIE["test"])) {
    ?>
    <script type="text/javascript">
        $(function() {
            // createCookie script
            createCookie("test", 1, 3600);
        });
    </script>
    <?php
    // Reload the page to ensure cookie was set
    if(!isset($_COOKIE["test"])) {
        header("Location: http://localhost/");
    }
}
?>

At first I had no idea why this didn't work, however after using microtime() I figured out that the PHP after the <script> was executing before the jQuery ready function. I reduced my code significantly to show a simple version that is answerable, I am well aware that I am able to use setcookie() in PHP, the requirements for the cookie are client-side.

I understand mixing PHP and JavaScript is incorrect, but any help on how to make this work (is there a PHP delay? - I tried sleep(), didn't work and didn't think it would work, since the scripts would be delayed as well) would be greatly appreciated.

Upvotes: 2

Views: 2578

Answers (6)

Ja͢ck
Ja͢ck

Reputation: 173562

This can't be done within a single request. PHP runs first, then JavaScript. Even incremental loading won't help, because cookies are sent via headers and those have already been sent by the time PHP runs.

However, you can let the JavaScript set the cookie and then reload the page once it's done by using location.reload(). PHP would then only need to print the JavaScript, like so:

<?php
if(!isset($_COOKIE["test"])) {
    ?>
    <script type="text/javascript">
        $(function() {
            // createCookie script
            createCookie("test", 1, 3600);
            // reload the page, which would send the cookie at the next request
            location.reload();
        });
    </script>
    <?php
    // stop execution and wait for JavaScript to call you again.
    exit;
}
?>

Upvotes: 0

jimp
jimp

Reputation: 17487

It is not impossible to do what you are trying to do, as other answers have stated, but it is also not trivial and seriously a bad idea for your server to wait per-request for the client to "set a cookie."

But it can be done.

  1. PHP code would write a <script> block for setting the cookie.
  2. PHP code would begin an idle loop, monitoring a session variable. Not a cookie. The cookies for the PHP script executing are already set and are not going to change by JavaScript.
  3. JavaScript block written in #1 would also need to make an AJAX call to the server. The PHP script it calls should set the cookie you care about, but also set the session variable #2 cares about.
  4. The original script, monitoring the session, should wake up and continue as you planned.

While PHP does execute before JavaScript, all browsers incrementally load the HTML/CSS/JavaScript content generated by PHP (or any server-side language). Because of the incremental loading, it is possible for your PHP script to delay for JavaScript to do something (as outlined above) before continuing. But your server is going to have a lot of headache to deal with, such as how long to wait for JavaScript to break the idle loop in #2 if the JavaScript request never comes through, etc.

This is not a normal execution flow for a standard webpage. Unless you really need this, perhaps consider this a proof-of-concept answer.

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

Cookies can be set in PHP with setcookie

setcookie("test",1,time()+3600);

Upvotes: 1

webjawns.com
webjawns.com

Reputation: 2300

If you want to execute JavaScript before PHP, you'll have to divide it into two requests. You can load your JavaScript in one request, and execute an Ajax request after your cookie is set. Keep in mind that all server-side code is processed before the client-side code will be executed.

I have to ask though.. why do you want to do it this way? What are you trying to accomplish?

Upvotes: 1

Kale McNaney
Kale McNaney

Reputation: 457

The PHP executes on the server-side, the JS on the client-side. In a single GET request from the browser, the PHP will always execute before the JS.

Upvotes: 0

deceze
deceze

Reputation: 522109

PHP executes first in its entirety on the server. It then sends the final HTML/Javascript/CSS output to the browser. The browser receives this and executes any Javascript.

It is fundamentally impossible to do what you're trying to do with that code. PHP and Javascript run at completely different times in completely different environments. You need to start another request to the server once Javascript set the cookie to start another PHP script. Redirect using Javascript or look into AJAX.

Upvotes: 1

Related Questions