14

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?

Greg Alexander
  • 1,192
  • 3
  • 12
  • 25
  • Look for my answer [here](https://stackoverflow.com/a/67448946/10534012). – Darkman May 08 '21 at 18:19
  • 3
    I'm using `jq` for that, see https://stackoverflow.com/a/34407620/906265 e.g. `printf %s "k=$SOMEVAL"|jq -sRr @uri` – Ivar Sep 21 '22 at 16:22

3 Answers3

18

On CentOS, no extra package needed:

python -c "import urllib;print urllib.quote(raw_input())" <<< "$message"
Rockallite
  • 16,437
  • 7
  • 54
  • 48
9

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")"
Walf
  • 8,535
  • 2
  • 44
  • 59
Gordon Davisson
  • 118,432
  • 16
  • 123
  • 151
6

Extending Rockallite's very helpful answer for Python 3 and multiline input from a file (this time on Ubuntu, but that shouldn't matter):

cat any.txt | python3 -c "import urllib.parse, sys; print(urllib.parse.quote(sys.stdin.read()))"

This will result in all lines from the file concatenated into a single URL, the newlines being replaced by %0A.

Murphy
  • 3,827
  • 4
  • 21
  • 35
  • 2
    No this doesn't work. Replace `sys.stdin.read()` with `input()` instead. Using the `read()` adds `%0A` which is file termination character. – Sudip Bhattarai Nov 22 '19 at 05:37
  • Using `input()` would only return the first line, but my intention was to get all lines from the file, encoded in one URL. You could easily convert `%0A` to newline again if necessary: `[...] | sed "s/%0A/\n/g"`. – Murphy Nov 22 '19 at 09:25
  • Works for me as posted by @Murphy (28/01/2020) – iainH Jan 28 '20 at 10:22