Trygve
Trygve

Reputation: 1387

wget error 400 from PHP, 200 from command line

From the command line (via SSH on my server) this works:

wget "https://www.example.com/script?paramA=1234&paramB=ABCD"

from PHP on the same server:

$url = "https://www.example.com/script?paramA=1234&paramB=ABCD";
exec("/usr/bin/wget $url");

I get:

HTTP request sent, awaiting response... 400 Bad Request
2018-11-07 15:01:21 ERROR 400: Bad Request.

What is going on here?

Upvotes: 0

Views: 692

Answers (1)

Lou
Lou

Reputation: 876

Let's see, what's different between the two?

wget "https://www.example.com/script?paramA=1234&paramB=ABCD"

VS

$url = "https://www.example.com/script?paramA=1234&paramB=ABCD";
exec("/usr/bin/wget $url");

Let's take your PHP code : If you print echo $url you will get :

https://www.example.com/script?paramA=1234&paramB=ABCD

Literally.

So, what's going on in your exec call then? if you echo "/usr/bin/wget $url" you will get :

/usr/bin/wget https://www.example.com/script?paramA=1234&paramB=ABCD

Literally. Now what's the difference between

wget "https://www.example.com/script?paramA=1234&paramB=ABCD"

and

/usr/bin/wget https://www.example.com/script?paramA=1234&paramB=ABCD

Of course there is the path : /usr/bin but... If you try it out, you'll find that's not your problem...

What else ? The quotes. The url in your shell command is wrapped in quotes, while it's not, in the one generated by your PHP code.

As mentioned by @ArtisticPhoenix in the comments, you can use the php function escapeshellarg() on your $url variable. It will add the quotes around your url (and also make sure that your string stays a string, to prevent injection, for example) and your command should run fine.

If you want to know what's happening here, it's that the & symbol in your url is parsed by the console that execute two commands instead of just one. Your url call (With paramB missing and another command paramB=ABCD that creates a variable in your shell. You can see it by typing echo $paramB that will print ABCD in your console. The API you are calling probably relies on paramB to be present, therefore, returning you a 400 error.

Hope this helps. Good luck.

Upvotes: 2

Related Questions