Jump to content

Archived

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

0rangeFish

saving operators from url

Recommended Posts

I'm trying to get an equation from a user that types it in the url, ex) 1+2+3. I can get the 1,2,3 fine, but the + operator is no longer in the string. Same with the * and / operators. Is there a way to keep them as a string using $_GET?

Share this post


Link to post
Share on other sites

Where is it in the URL? Is there any URL rewriting? Why are people typing directly into the URL in the first place?

Share this post


Link to post
Share on other sites

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

Share this post


Link to post
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)

Share this post


Link to post
Share on other sites

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
}

Share this post


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

Share this post


Link to post
Share on other sites

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