Save image using cURL Save image using cURL curl curl

Save image using cURL


What can be the difference in the command line and code execution of the same command ?

your user-agent isn't even close:

curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36');

try setting it to a real curl-cli useragent, like

curl_setopt($ch,CURLOPT_USERAGENT,'curl/7.63.0');

or

curl_setopt($ch,CURLOPT_USERAGENT,'curl/'.(curl_version()['version']));

it's rare, but it's possible (and even likely given the evidence) that they're using a user-agent whitelist, and Google Chrome (or is it Safari?) is not on their whitelist, but curl-cli is...

another possible explanation is that they're trying to detect and block people lying on their user-agent, and it's easy to detect that you're lying: you're (falsely) saying that you are Safari or Chrome, and both of those always sends Acccept-Encoding: gzip/deflate/whatever, but your curl request does not (because you didn't use CURLOPT_ENCODING), thus it's easy to detect that your user-agent is fake, maybe that's what's causing the block. either way, try using a real curl user-agent.


401 is Unauthorized

403 is Forbidden

These are badly described.

401 really means not Authenticated

403 really means not Authorized

If this is indeed a protected resource that requires being logged in to fetch it, then this means that yes, the server recognises you (you didn't get a 401), but you don't have the required permissions (403).

If, on the other, hand the image really is public, actually pasting the link could help us to help you.


As it turns out the problem was a simple one.

-The first clue was that the command in terminal was working but the same command with shell_exec() was returning an error.

-The second clue was that as delboy1978uk mentioned the error was not 401 not authenticated but a 403 non authorized.

So there had to be a problem with the URL or parameter.I printed out the URL but found no error....So long story short, the problem was with the special characters in the URL. When I printed the URL the browser displayed the & character correctly not as the function got it as a parameter &.

So if I feed URL to htmlspecialchars_decode() prior to run the command then it works flawlessly.

So lookout for special characters in the URL!