How to reuse cUrl context after executing a PUT request in PHP?

I have code in which I try to use the curl context to make requests and receive requests. After each send request, the request for the request is interrupted with this PHP warning:

curl_exec (): resource CURLOPT_INFILE is gone, resetting to default settings

I could use the PHP shutup operator, but I would prefer to properly reset the curl context. Does anyone know how to do this? I could also use different curl contexts, but I would prefer to reuse the connection as the application sends a lot of requests. I could keep the file descriptor open, but it seems like a hacker solution, especially since it is all included in the functions, so I can call doPut, doGet, etc.

$curlContext = curl_init(); $fh = fopen('someFile.txt', 'rw'); curl_setopt($curlContext, CURLOPT_URL, $someUrl); curl_setopt($curlContext, CURLOPT_PUT, TRUE); curl_setopt($curlContext, CURLOPT_INFILE, $fh); curl_setopt($curlContext, CURLOPT_INFILESIZE, $size); $curl_response1 = curl_exec($curlContext); fclose($fh); curl_setopt($curlContext, CURLOPT_PUT, FALSE); curl_setopt($curlContext, CURLOPT_HTTPGET, TRUE); curl_setopt($curlContext, CURLOPT_URL, $someOtherUrl); $curl_response1 = curl_exec($curlContext); 

Thanks.

+4
source share
3 answers

After fclose ($ fh) do curl_setopt ($ curlContext, CURLOPT_INFILE, STDIN);

In order to avoid "CURLOPT_INFILE resource has left, reset the default settings."

+1
source

Starting with PHP 5.5, curl_reset can be used to reset all previous settings.

For PHP <5.5, the Li-chih Wu solution is a possible workaround.

+1
source

You can simply use curl_setopt_array instead of reusing the context

 $file = 'log.txt'; $fh = fopen($file, 'rw'); $options = array( CURLOPT_URL => 'http://localhost/lab/stackoverflow/b.php', CURLOPT_PUT => 1, CURLOPT_INFILE => $fh, CURLOPT_INFILESIZE => filesize($file), CURLOPT_HEADER => false ); // First Request curl_setopt_array($ch = curl_init(), $options); echo curl_exec($ch); fclose($fh); // Secound Request $options[CURLOPT_URL] = "http://localhost/lab/stackoverflow/c.php"; unset($options[CURLOPT_INFILE], $options[CURLOPT_INFILESIZE]); curl_setopt_array($ch = curl_init(), $options); echo curl_exec($ch); 
0
source

Source: https://habr.com/ru/post/1403740/


All Articles