0

My need is to send multiple values when a user clicks a button which uses GET METHOD. Since multiple values are to be sent, I am using an argument as follows:

$argument='var2=value2&var3=value3';
echo "<button value='value1&$argument&' type='submit' name='var1'>Send</button>";

Essentially, the button tag in HTML has a restriction that it can send ONLY one name-value pair. In this case, it will send name='var1' and corresponding value as value1. Hence, I am appending the other name-value pairs through the PHP $argument variable. In this case, var2=value2&var3=value3 are getting appended, and sent.

All good till here.

The problem is that when it reaches the submitted page, it is getting the following encoding: https://example.com/dir1/page.php?var1=value1%26var2%3Dvalue2%26var3%3Dvalue3%26

Essentially, the & is getting %26, and = is becoming %3D. I am aware that this is due to the inbuilt encodeURIComponent of HTML, but due to this encoding the form submission is failing.

I am looking for a way/method to receive the following in the submitted page (i.e. without encoding), so that it can be processed smoothly:

https://example.com/dir1/page.php?var1=value1&var2=value2&var3=value3&

PS: have explored existing threads like Escaping ampersand in URL & Why does %26 get decoded to & when passed as a parameter to a JavaScript function from a link? & many more, but unable to find the answer.

Also tried the following as mentioned in URL/HTML escaping/encoding, but not working:

echo "<button value='value1&".htmlspecialchars($argument)."' type='submit' name='var1'>Send</button>";

If any existing answer exists, pls point me to it in the comment before marking this question down. Thanks

3
  • 2
    Put these values individually in hidden fields in the form which the button is part of. Commented Jan 19, 2023 at 14:17
  • P.S. htmlspecialchars is for HTML-encoding to protect against XSS. It has nothing to do with URL-encoding. In PHP there's a separate urlencode function for that. Commented Jan 19, 2023 at 14:17
  • I've posted a full answer, with an example. Glad it helped. Commented Jan 19, 2023 at 14:37

1 Answer 1

1

You can simply put these values individually in hidden fields in the form which the button is part of.

e.g.

<form>
    <button type='submit' name='send'>Send</button>
    <input type="hidden" name="var1" value="<?php echo htmlspecialchars($val1)?>">
    <input type="hidden" name="var2" value="<?php echo htmlspecialchars($val2)?>">
</form>

The browser will then use these to create a properly-constructed and encoded URL for you automatically when the form is submitted.

Sign up to request clarification or add additional context in comments.

Comments

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.