David
David

Reputation: 3348

How to call file_get_contents() in PHP without waiting for result?

In some of my PHP scripts I am using this code to POST data to a URL:

$file = @file_get_contents();

This will only POST data, content returned by server is empty. The executed script is really unimportant and isn't needed for the main script that gets executed. It's like a log file.

Normally PHP will wait until this is ready executed.

Is there a way to call $file=@file_get_contents(); without waiting for the result? Just call it and execute the next command without taking care of $file=@file_get_contents();?

I have already searched for this problem but only found solutions for the console.

Upvotes: 2

Views: 2865

Answers (3)

Markus
Markus

Reputation: 440

This feature is with file_get_contents not really possible. But you can use fsockopen to achieve this.

Upvotes: 1

Salman Arshad
Salman Arshad

Reputation: 272246

You can move the asynchronous code inside a separate PHP file, then execute it using one of the program execution functions. You need to spawn the program in such a way that PHP does not wait for it to finish. For example on Unix you can use the & operator:

<?php
shell_exec("php post.php arg1 arg2 arg3 >/dev/null 2>/dev/null &");

This is tricky on Windows but not impossible.

Upvotes: 1

Jose Mato
Jose Mato

Reputation: 2799

file_get_contents is a sync method so you can't just skip it but if the method is not important a solution using PHP is create a thread and put it that log logic method, in that way you can run the process where actually the request is being attended (process / thread) and at "same time" the thread logging whatever you are doing. http://php.net/manual/es/class.thread.php

Upvotes: 1

Related Questions