L
L
lasthero672021-11-22 10:36:29
PHP
lasthero67, 2021-11-22 10:36:29

What condition to put if the address is not available in curl?

Hello. There is WordPress 5.8.2. On the site, I use the curl library with the following construction

$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url . '?' . http_build_query($params));
$response = curl_exec($ch);
$data = new SimpleXMLElement($response);
print_r($response);
curl_close($ch);


where url is the request address, $params are the request parameters. Recently, pages with curl periodically stopped opening (WordPress writes "The site has encountered a critical error."). This happens for a short time, literally when the page is reloaded, everything loads. I assume that such an error occurs when the request address is not available. How to set a condition so that if the request address is unavailable, further processing does not occur and the page remains available?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
rPman, 2021-11-22
@rPman

after calling curl_exec, make a call to curl_getinfo and check what exactly the server returns to you, in particular CURLINFO_HTTP_CODE (or better CURLINFO_RESPONSE_CODE) ($info['http_code']) should be 200, if not, then see
CURLINFO_SSL_VERIFYRESULT (see the list of codes in the comments) and CURLINFO_PROXY_SSL_VERIFYRESULT if a proxy is used,
see the response CURLINFO_HTTP_CONNECTCODE, CURLINFO_OS_ERRNO
CURLINFO_CONDITION_UNMET
ps also check $response, if it is empty then there is no point in trying to parse it into xml, this is also an error (this means the server returned an empty response without generating errors, this happens when crooked hands backend programmers implement api)

S
spaceatmoon, 2021-11-22
@spaceatmoon

Always use the response time limit.

curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5); //5 секунд

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question