Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL encoding a string in bash script

I am writing a bash script in where I am trying to submit a post variable, however wget is treating it as multiple URLS I believe because it is not URLENCODED... here is my basic thought

MESSAGE='I am trying to post this information'
wget -O test.txt http://xxxxxxxxx.com/alert.php --post-data 'key=xxxx&message='$MESSAGE''

I am getting errors and the alert.php is not getting the post variable plus it pretty mush is saying

can't resolve I can't resolve am can't resolve trying .. and so on.

My example above is a simple kinda sudo example but I believe if I can url encode it, it would pass, I even tried php like:

MESSAGE='I am trying to post this information'
MESSAGE=$(php -r 'echo urlencode("'$MESSAGE'");')

but php errors out.. any ideas? How can i pass the variable in $MESSAGE without php executing it?

like image 913
Greg Alexander Avatar asked Aug 09 '12 03:08

Greg Alexander


People also ask

How do I encode text in URL?

URL Encoding FunctionsPHP has the rawurlencode() function, and ASP has the Server.URLEncode() function. In JavaScript you can use the encodeURIComponent() function. Click the "URL Encode" button to see how the JavaScript function encodes the text. Note: The JavaScript function encodes space as %20.

What is URL encoded string?

URL encoding is a mechanism for translating unprintable or special characters to a universally accepted format by web servers and browsers.

Does cURL do URL encoding?

URL-encodingcURL can also encode the query with the --data-urlencode parameter. When using the --data-urlencode parameter the default method is POST so the -G parameter is needed to set the request method to GET.

What does -- data Urlencode do?

To help you send data you have not already encoded, curl offers the --data-urlencode option. This option offers several different ways to URL encode the data you give it. You use it like --data-urlencode data in the same style as the other --data options.


2 Answers

On CentOS, no extra package needed:

python -c "import urllib;print urllib.quote(raw_input())" <<< "$message"
like image 63
Rockallite Avatar answered Sep 19 '22 12:09

Rockallite


You want $MESSAGE to be in double-quotes, so the shell won't split it into separate words, then pass it to PHP as an argument:

ENCODEDMESSAGE="$(php -r 'echo rawurlencode($argv[1]);' -- "$MESSAGE")"
like image 35
Gordon Davisson Avatar answered Sep 19 '22 12:09

Gordon Davisson