Jump to content

very simple question


mysterbx

Recommended Posts

If I understand properly, you are retrieving the string value of "12-1" and you need to execute that equation rather than displaying it to the screen. If this is the case, you will either need to build a parser of some sort (safer) or use eval() to execute the equation (easier but more dangerous):

 

<?php
$eq = "12-1";
eval("\$result = $eq;");
echo $result;
?>

Link to comment
Share on other sites

obsidian hinted at this, but don't put that code out for public use!  It will allow your users to execute any command they want on your webserver.

 

You can avoid this by sanitizing the input, for example:

 

$safe_eq = preg_replace('|[^[:digit:]()+*/-]|', '', $eq);

 

That will allow only digits and the following symbols: ( ) + * / -

 

I think that ought to be safe.. at least I can't imagine anything you could do with that other than causing the eval to fail due to syntax error.

Link to comment
Share on other sites

code is for timed backups...

It gets the time, then gets the timezone.

 

And the output is: 15(time)-5(timezone), in otherwords: 15-5

 

and I needed a code that "does the math"

 

the command runs in background, so no publick use will be allowed...

 

If that's the case, I would recommend you do something like this (I'm one to always go above and beyond on precautions):

<?php
// since you know it will always be [digits] + or - [digits], this will work:
function parseTime($string)
{
  if (!preg_match('|^([\d]+)(+|-)([\d]+)$|', $string, $match))
  {
    // Invalid format presented
    return FALSE;
  }

  switch ($matches[2])
  {
    case '+':
      return intval($matches[1]) + intval($matches[3]);
      break;

    case '-':
      return intval($matches[1]) - intval($matches[3]);
      break;
  }
}
?>

 

Hope this makes sense.

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.