I wonder how I can manage a URL with special characters when working with cURL. In the code sample below I have implemented a function that returns the HTTP response code for a url
(NB. I know that there are other ways to get the response code, but this is just for illustrating the problem with special characters in the URL)
<?php
function get_http_code($url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_exec($ch);
return curl_getinfo($ch, CURLINFO_HTTP_CODE);
}
// urlA has a special character 'â'
$urlA = "https://media.winefinder.com/upload/artiklar/bilder/KSU128248-1-Domaine-de-Ferrand-Châteauneuf-du.jpg";
// urlB has no special charactes
$urlB = "https://media.winefinder.com/upload/artiklar/bilder/A129749-1-Domaine-Lafage-Princesse-2019.png";
echo "<div>Code A = " . get_http_code($urlA) . "</div>"; // --> 404
echo "<div>Code B = " . get_http_code($urlB) . "</div>"; // --> 200
?>
Both urls exists, but the first one returns 404 (Not found) due to the special character in the url. How can I convert the URL to a encoded url that will return 200? I have tried with urlencode()
, rawurlencode()
etc, but I can't make it work.
PS. I have tried to find similar questions at SO, but couldn't find any that helped me here...