15

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?

2
  • Look for my answer here. Commented May 8, 2021 at 18:19
  • 3
    I'm using jq for that, see stackoverflow.com/a/34407620/906265 e.g. printf %s "k=$SOMEVAL"|jq -sRr @uri Commented Sep 21, 2022 at 16:22

3 Answers 3

19

On CentOS, no extra package needed:

python -c "import urllib;print urllib.quote(raw_input())" <<< "$message"
Sign up to request clarification or add additional context in comments.

5 Comments

This solution is python 2 only
Python 3 version looks like python3 -c "import urllib.parse; print(urllib.parse.quote(input())".
@JasonR.Coombs you forgot one closing brace :)
A correct Python 3 version looks like python3 -c "import urllib.parse; print(urllib.parse.quote(input()))" (tested this time).
Python version agnostic: python -c $'try: import urllib.request as urllib\nexcept: import urllib\nimport sys\nsys.stdout.write(urllib.quote(input()))' <<< "$message" and adds no \n
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")"

Comments

7

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.

3 Comments

No this doesn't work. Replace sys.stdin.read() with input() instead. Using the read() adds %0A which is file termination character.
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".
Works for me as posted by @Murphy (28/01/2020)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.