Jump to content

saving operators from url


0rangeFish

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"];

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)

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
}

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']));

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.