John Davidson

php - CURLOPT_URL with underscores, how to?

0 comments
Message:


I'm sorry, I speak a little English.


My code:


$cu = curl_init();
curl_setopt( $cu, CURLOPT_URL, $url );
curl_setopt( $cu, CURLOPT_USERAGENT, $user_agent );
curl_setopt( $cu, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $cu, CURLOPT_COOKIEFILE, $cookie_file );
curl_setopt( $cu, CURLOPT_COOKIEJAR, $cookie_file );
$html = curl_exec( $cu );
curl_close( $cu );

It works:


$url = 'https://www.example.com/Profile/123/Any/Photos/News/';

It doesn't work:


$url = 'https://www.example.com/Profile/123/_Any_/Photos/News/';

Why? What is the problem and how to solving?



My Answer:
The issue you are facing is likely due to the presence of underscores in the URL. When using CURLOPT_URL with curl in PHP, special characters like underscores may need to be encoded in order to be properly interpreted by the server.

You can use the urlencode function in PHP to encode the URL before passing it to CURLOPT_URL. Here is an example of how you can modify your code to encode the URL:

php
$cu = curl_init();
$url = 'https://www.example.com/Profile/123/_Any_/Photos/News/';
$url = urlencode($url);
curl_setopt($cu, CURLOPT_URL, $url);
curl_setopt($cu, CURLOPT_USERAGENT, $user_agent);
curl_setopt($cu, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($cu, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($cu, CURLOPT_COOKIEJAR, $cookie_file);

$html = curl_exec($cu);
curl_close($cu);


By encoding the URL using urlencode, you can ensure that special characters like underscores are properly handled by the server. This should help resolve the issue you are facing with the URL containing underscores.

Rate this post

5 of 5 based on 6386 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us