Jump to content

Letting user input PHP code and having a function parameter act on it


BenGoldberg

Recommended Posts

One more question. So I have a function with two parameters, $x and $y. Here it is.

 

function dydx($x,$y){

$equation = 2 * $x;
return $equation;
}

 

Now here's the problem. I want $equation to be user defined. Easy enough, I use a post command and I get $equation to equal whatever the user inputs. The problem is that if I get input from the user, I'm not sure how to take that input and then have the function parameters work on it. Like if the user inputs "3*$x + 2*$y", i want to be able to let the parameters for the function dydx act on it. How could I go about doing this?

Link to comment
Share on other sites

Eval seems to be the right function for my application, but for the life of me I can not get it to work. Here's the basic code I'm working with.

 

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

<table>
<tr>
	<td>Enter function y prime:</td>
	<td><input type="text" size="50" maxlength="" name="yprime" value="<?php echo (isset($_POST['yprime']) ? $_POST['yprime'] : '')?>" /></td>
</tr>

</table>

</br>

<input type="submit" name="rk" value="Submit" />

</form>

<?php

$yprime = strval( $_POST['yprime'] ); //saving the function as a string

function dydx($x,$y){

eval("\$equation = \"$yprime\";");
return $equation;
}

echo dydx(3,2); //equals 0 when it should equal 9 (yprime being 3*$x)

?>

 

(The example input i use for yprime is 3*$x)

 

I've done hours of googling and researching how eval works, but no matter what I try, the function dydx() always returns 0. The code above is what I believe to be my best attempt at getting it to evaluate $yprime properly, but it doesn't work. Argh!

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.