Jump to content

saving operators from url


0rangeFish
Go to solution Solved by QuickOldCar,

Recommended Posts

The url looks like this: h t t p :// localhost:8888/letterMath.php/?equation=1+2+3. The 1+2+3 is put into the variable $equation.

 

But when I echo $equation is just gives me 1 2 3. (with the spaces replacing the +)

 

This is the code used to put it out of the url: $equation = $_GET["equation"];

Edited by 0rangeFish
Link to comment
Share on other sites

Pluses in query strings have a special meaning and you won't get pluses back out from $_GET.

 

People really shouldn't be putting stuff in the URL by themselves. Give them a form to type their equation into; it can still use GET but your code will work (because the browser will encode the pluses correctly).

 

But if you insist, +s represent spaces so

$equation = str_replace(" ", "+", $_GET["equation"]);
That won't help you next time you need a symbol that has a special meaning.

 

Or you can forgo the "equation=" part, leaving just /letterMath.php/?1+2+3 and

$equation = $_SERVER["QUERY_STRING"];
(which will give you the raw value)
  • Like 1
Link to comment
Share on other sites

  • Solution

The + needs to be properly encoded in the browser address as %2B

 

A simple test to try

$value = "1+2+3";
$array = array("equation"=>$value);
$query = http_build_query($array);

echo "<a href='?".$query."'>http_build_query</a><br />";
echo "<a href='?equation=".urlencode($value)."'>urlencode</a><br />";
echo "<a href='?equation=".rawurlencode($value)."'>rawurlencode</a><br />";

if(isset($_GET['equation'])){
//if url is already properly encoded in browser
echo $equation = $_GET['equation']."<br />"; //yes
echo $equation = urldecode($_GET['equation'])."<br />"; //no
echo $equation = rawurldecode($_GET['equation'])."<br />"; //yes
}
Link to comment
Share on other sites

And Requinix's solution is fine to always replace spaces to a + if that's what that parameter expects

The below code would change the spaces, encoded spaces and spaces to a +

A person may or may not encode the + sending data to you

$equation = str_replace(array("%2B", "%20", " "), "+", trim($_GET['equation']));
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.