Exiting the cURL sample

I am trying to find a way to just quickly access the file and then disconnect immediately.

So, I decided to use cURL as this is the fastest option for me. But I can’t understand how I can "disable" cURL.

In the code below, the Apache access logs say that the file I tried to access was indeed accessible, but I feel a little bit because when I just run the while loop without breaking out of it, it just keeps looping. Shouldn't the loop be stopped when cURL has finished fetching the file? Or am I just stupid; Is the cycle constantly restarting?

<?php $Resource = curl_init(); curl_setopt($Resource, CURLOPT_URL, '...'); curl_setopt($Resource, CURLOPT_HEADER, 0); curl_setopt($Resource, CURLOPT_USERAGENT, '...'); while(curl_exec($Resource)){ break; } curl_close($Resource); ?> 

I tried to set the parameters CURLOPT_CONNECTTIMEOUT_MS / CURLOPT_CONNECTTIMEOUT to very small values, but in this case it did not help.

Is there a more β€œright” way to do this?

0
source share
2 answers

This statement is superdense:

 while(curl_exec($Resource)){ break; } 

Instead, just keep the return value for future reference:

 $result = curl_exec($Resource); 

The while helps nothing. So, now to your question: you can tell curl that it should take only some bytes from the body and then leave. This can be achieved by reducing the value of CURLOPT_BUFFERSIZE to a small value and using the callback function to report this, it should stop:

 $withCallback = array( CURLOPT_BUFFERSIZE => 20, # ~ value of bytes you'd like to get CURLOPT_WRITEFUNCTION => function($handle, $data) { echo "WRITE: (", strlen($data), ") $data\n"; return 0; }, ); $handle = curl_init("http://stackoverflow.com/"); curl_setopt_array($handle, $withCallback); curl_exec($handle); curl_close($handle); 

Conclusion:

 WRITE: (10) <!DOCTYPE 

Another option is to make a HEAD request using CURLOPT_NOBODY , which will never receive the body. But this is not a GET request.

Connection timeout settings are how long it takes until the connection time is up. A connection is a phase until the server accepts input from curl, and curl begins to know what the server is doing. This is not related to the phase where curl retrieves data from the server, which

CURLOPT_TIMEOUT maximum number of seconds to execute cURL functions.

In the PHP manual, you will find a long list of available options: curl_setopt & shy; Docs .

+1
source

Perhaps this could be useful?

 $GLOBALS["dataread"] = 0; define("MAX_DATA", 3000); // how many bytes should be read? $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://www.php.net/"); curl_setopt($ch, CURLOPT_WRITEFUNCTION, "handlewrite"); curl_exec($ch); curl_close($ch); function handlewrite($ch, $data) { $GLOBALS["dataread"] += strlen($data); echo "READ " . strlen($data) . " bytes\n"; if ($GLOBALS["dataread"] > MAX_DATA) { return 0; } return strlen($data); } 
+1
source

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


All Articles