1

Given URL like below

www.example.com?1+1

How am I supposed to parse the data and do the math?

If it was something like

www.example.com?a=1&op=+&b=1

Then I can just do $_GET[“variable_name”].

But what can I do with the former? What is the best way to parse such query?

I searched for a solution but cannot seem to find something relevant with my current knowledge. I tried looking at $_SERVER but I don't think this helps.

Leonard
  • 2,978
  • 6
  • 21
  • 42
  • You can get the query string from `$_SERVER['QUERY_STRING']` but then you'd have to either parse that against what you're expecting, or eval it which would be insanely dangerous. – Jonnix Jul 17 '19 at 12:08

1 Answers1

0

If you are sure that nothing malicious would be passed (or you are just testing), then you could do something like:

$output = eval('return ' . parse_url($_SERVER['REQUEST_URI'])['query'] . ';');

echo $output;

Obligatory notice:

Caution The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

However, I would advise you use the following method and parse the expression with parser in the linked question:

$exp = parse_url($_SERVER['REQUEST_URI'])['query']; // 1+1

Reading Material

How to evaluate formula passed as string in PHP?

parse_url

eval

Script47
  • 14,230
  • 4
  • 45
  • 66
  • Thanks, but how can I get the current URL like that?? I tried the answer in the first link and echoed `$actual_link` but nothing shows up https://stackoverflow.com/questions/6768793/get-the-full-url-in-php – Leonard Jul 17 '19 at 12:23
  • @Leonard my mistake, updated: `$_SERVER['REQUEST_URI']`. **Edit:** https://stackoverflow.com/questions/6768793/get-the-full-url-in-php – Script47 Jul 17 '19 at 12:24
  • Sadly, that is exactly what I did and it does not work. When I do ` echo $_SERVER["REQUEST_URI"];` it shows nothing. – Leonard Jul 17 '19 at 12:25
  • @Leonard do you have any mod rewrites active? – Script47 Jul 17 '19 at 12:28
  • Oh, I think it was a weird server issue! I re-started it and it works now! Thanks Sorry i dont know what mod rewrites are :( – Leonard Jul 17 '19 at 12:30