Fraze Jr.
Fraze Jr.

Reputation: 143

Call a URL and continue if no response

I have a php script (plugin) which is importing some products in my site. To import the products I'm forced to use two links who are executing this import.

The first URL exits to trigger the Import. This URL unlocks the second URL to import the products. If the import is finished, the second URL, who exits to execute the import, the URL displays a code (200).

My problem now is, how can I check e.g. every 30 seconds if the second URL is returning 200? - Because this is the only way to recognize if a import is finished.

I already tried fopen(..) but the problem there is that my script gets stopped because fopen doesn't gets a return.

So what I need is a function or a code which checks e.g. if the second URL is returning something after 10s and if not the code sleeps for 30 seconds and checks it again. And only if I get returned 200, I can exit this loop.

As I said, I already tried fopen(..) but this function stops my script. And my second way to try this is curl. But the problem there is, I just do not check if I get something returned... Here my curl code:

    $ch = curl_init("https://myurl.de/");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $content = curl_exec($ch);
    curl_close($ch);

Upvotes: 0

Views: 273

Answers (2)

DenisOgr
DenisOgr

Reputation: 589

I think this way (using loop and curl call) is unpredictable and non scalable. What if you will have a lot of import operations per second? What if you will have very long by time import operation? I think you must use some library to creating and handle background jobs (queueing systems) and you server must communicate with browser (user) using socket (for example, NodeJS).

Upvotes: 0

hassan
hassan

Reputation: 8288

You will not be able to do this using php itself -as long as you don't want to execute a process which is blocks the I/O-.

you may work around this with a little help from javascript's setInterval or setTimeout.

<script>
    var timer = setInterval(function () {
        // executing some ajax to call php url
        // which is check for the response status
        $.ajax({
        ....
        success: function(data) {
            // check if the response is finished
            clearInterval(timer);

        }
        ....
        });
    });
</script>

Upvotes: 1

Related Questions