pulling a random number into a symfony form - php

I am pulling two random numbers to create a math equation in a symfony form. The problem is when the form is submitted, the random numbers are updated, making the form submission invalid. How can I keep the initial number values loaded, so the form will process, but after successful process, load a new set?
actions.class
public function executeIndex(sfWebRequest $request)
{
$num1 = rand(0 , 20);
$num2 = rand(0 , 20);
$realAnswer = $num1 + $num2;
$show = $num1 . " + " . $num2 . " = ";
$this->getResponse()->setSlot("displayNum", $show);
$this->form = new UserForm();
echo $num1 . "<br>" . $num2 . "<br>" . $realAnswer;
if ($request->isMethod('post') && ($request->getPostParameter('captcha[answer]') == $realAnswer))
{
$this->processForm($request, $this->form);
}
}
I am using a partial to render the form -> _form.php
<tr height="40">
<td width="100" valign="middle">
<?php echo get_slot("displayNum", "default value if slot doesn't exist"); ?>
</td>
<td width="400" colspan="4" valign="middle">
<input type="text" id="captcha" class="url" name="captcha[answer]" style="width:100px" />
</td>
</tr>
Example: When the page initially loads, two random numbers are generated (ex. 10 & 15). This renders
10 + 15 = (input field)
The user inserts 25 and clicks save. This was correct, but because the form executes the index action again, there is a new set of random numbers making the "if" condition false.
UPDATE:
Per j0k's suggestion I have made the changes to the action.
public function executeIndex(sfWebRequest $request)
{
$user = $this->getUser();
if (!$request->isMethod('post'))
{
// first display of the form, generate nums
$num1 = rand(0 , 20);
$num2 = rand(0 , 20);
$realAnswer = $num1 + $num2;
// store them in session
$user->setAttribute('realAnswer', $realAnswer);
$user->setAttribute('num1', $num1);
$user->setAttribute('num2', $num2);
}
else
{
// the form is submitted, retrieve nums from the session
$num1 = $user->getAttribute('realAnswer', null);
$num2 = $user->getAttribute('num1', null);
$realAnswer = $user->getAttribute('num2', null);
}
//setup slot
$show = $num1 . " + " . $num2 . " = ";
echo $realAnswer . "-Actual<br>" . $request->getPostParameter('captcha[answer]') . "-User submitted";
$this->form = new UserForm();
if ($request->isMethod('post') && (($request->getPostParameter('captcha[answer]') == $realAnswer)))
{
$this->processForm($request, $this->form);
}
}
which should work. Looking at the variables, it looks like the page is pulling the session variable and not adding new random numbers on the second post. weird.
RESOLVED
It was a code error. I had the variables crossed up.
else
{
// the form is submitted, retrieve nums from the session
$num1 = $user->getAttribute('num1', null);
$num2 = $user->getAttribute('num2', null);
$realAnswer = $user->getAttribute('realAnswer', null);
../

Session is a good point.
If the form isn't posted, store the result in the session to be able to check it after.
public function executeIndex(sfWebRequest $request)
{
$user = $this->getUser();
if (! $request->isMethod('post'))
{
// first display of the form, generate nums
$num1 = rand(0 , 20);
$num2 = rand(0 , 20);
$realAnswer = $num1 + $num2;
// store them in session
$user->setAttribute('realAnswer', $realAnswer, 'captcha');
$user->setAttribute('num1', $num1, 'captcha');
$user->setAttribute('num2', $num2, 'captcha');
}
else
{
// the form is submitted, retrieve nums from the session
$num1 = $user->getAttribute('num1', null, 'captcha');
$num2 = $user->getAttribute('num2', null, 'captcha');
$realAnswer = $user->getAttribute('realAnswer', null, 'captcha');
}
$show = $num1 . " + " . $num2 . " = ";
$this->getResponse()->setSlot("displayNum", $show);
$this->form = new UserForm();
if ($request->isMethod('post') && ($request->getPostParameter('captcha[answer]') == $realAnswer))
{
$this->processForm($request, $this->form);
}
}
And don't forget to empty the related values in session if the form is valid.
protected function processForm(sfWebRequest $request, $form)
{
// bind form
if ($form->isValid())
{
// clear the session
$this->getUser()->getAttributeHolder()->removeNamespace('captcha');
}
}
Ps: if you are looking for a transparent captcha, I recommend you this method. I've tested it with really great success.

You could store the random numbers as session variables which will persist after reload:
session_start();
$_SESSION["num1"] = rand(0 , 20);
$_SESSION["num2"] = rand(0 , 20);

Related

How to echo/print within a fuction with undefined variables in php?

I am not the best at php but currently I am trying to learn. I can print fine outside of the function but the specific instructions I have been given require me to print the results within the function. I have tried
echo "$area";
echo "calculatearea ()";
ive searched but still cant figure out how to get a print within the function only outside of it.
<?php
if (isset($_POST['CalcBT'])) {
global $area;
function calculateCircumference () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$circ = $num1 + $num2;
return $circ;
}
function calculateArea () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$area = 2*($num1 + $num2);
return $area;
}
echo "Your rectangle circumference is: " . calculateCircumference() . '<br />' . "Your rectangle area is: " . calculateArea();
}
?>
<!---------------- Form---------------->
<div class="form">
<h3></h3>
<form action="PHP-sida4.php" method="POST">
<p>Length: <input type="text" name="Length"value=""></p>
<p>Width: <input type="text" name="Width"value=""></p>
<input type="submit" name="CalcBT" value="Calculate">
</form>
I need the return value of $area along with what I echo'd in the bottom to actually print within the first function ( calculateCircumference )
You can echo anything you want within the function but it won't show up until you call the function.
<?php
if (isset($_POST['CalcBT'])) {
global $area;
function calculateCircumference () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$circ = $num1 + $num2;
// return $circ;
echo "Your rectangle circumference is: " . $circ . '<br />' . "Your rectangle area is: " . calculateArea();
return;
}
function calculateArea () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$area = 2*($num1 + $num2);
return $area;
}
calculateCircumference();
}
?>
I hope this helps!
Okay if am getting your question right, to need to return the area and some other text along with the area.
Let's begin with some house cleaning, therefore the $area global variable could be renamed to something else like $results Which will be an array or object. Taking it simple.
Lets go with an associative array where e.g:
$results = [
'area' => null,
'text' = null
];
From that your will be updating $results['area'] from the calculate function and also update the $results['text'] before calling echo, so probably extract the echoed text to another variable.
And now you can access $results anywhere within the file with both the area and the text:
To just be more expressive under CalculateArea() function do something like:
$results['area'] = $area;
Same thing with the echoed text.
You can use echo instead of return in your functions. To call them, your can just use function(); without any additional keyword :
function calculateCircumference () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$circ = $num1 + $num2;
echo $circ;
}
function calculateArea () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$area = 2*($num1 + $num2);
echo $area;
}
echo "Your rectangle circumference is: " ;
calculateCircumference() ;
echo '<br />' ;
echo "Your rectangle area is: " ;
calculateArea();
You can echo anything anywhere, be it inside a function or outside of it. If an echo is not performing, then there was either an error, or the line where the echo can be found was not executed.
In our case you have removed the echo after your functions, which, coincidentally happened to be the only place where they were called.

Php using a function to add on a number to a outside variable

<form method="post">
<select name="racebox">
<option>select</option>
<option>human</option>
</select>
<input type="textbox" name="ability" value= "">
<input type="textbox" name="strength" value= "">
<input type="submit" name="submit" value="submit">
</form>
<?php
$ability=$_POST['ability'];
$strength=$_POST['strength'];
$racepick=$_POST['racebox'];
function race($racepick){
if ($racepick === "human"):
$strength +1;
endif;
}
function modifier($num){
$modifier= floor($num/2-5);
if ($modifier >= 0):
echo " ", "+","$modifier <br>";
elseif ($modifier < 0):
echo " ", $modifier, "<br>";
endif;
}
modifier($ability);
modifier($strength);
?>
Trying to make a dnd character sheet, I want to be able to pick human and have it add a set amount to the variables gotten from 'strength' these will be predetermined prior and be different to every selection box option.
Upon review, what you should do is pass $strength to your race() function and return it with the amount of strength added to it.
$ability = $_POST['ability'];
$strength = $_POST['strength'];
$racepick = $_POST['racebox'];
$strength = race($racepick, $strength) {
switch ($racepick) {
case 'human':
$strength = $strenght + 1;
break;
case 'otherrace':
$strength = $strength + 5;
break;
}
return $strength;
}
Additional information
Functions are generally used so that programmers can re use certain parts of code. It is only usefull to use functions if you are not planning on using this code again in some other script I would like to suggest dropping the function all together and just doing the following:
$ability = $_POST['ability'];
$strength = $_POST['strength'];
$racepick = $_POST['racebox'];
switch ($racepick) {
case 'human':
$strength = $strenght + 1;
break;
case 'otherrace':
$strength = $strength + 5;
break;
}

PHP compare values not working

i have a form that i've made a custom security question for.
It randomizes a question with the code
$rand1 = rand ( 1,20 );
$rand2 = rand ( 1,20 );
$randsvar = $rand1 + $rand2;
$securefråga = "Vad blir " . $rand1 . "+" . $rand2;
and i then parse it in to my code as
$_POST["secure"]
after that i convert them both to integers and compare both the converted $randsvar and the form value with eachother with the code
$intSecure = intval($secure);
$intRand = intval($randsvar);
if($intSecure == $intRand)
{
$errorNummer++;
}
else
{
$secureErr = "wrong answer";
}
however even if i type the correct answer it gives me the error message, what am i doing wrong?
You can use sessions to save the current operation. If submitted, compare the user input to the saved session total. Rough example:
if(!isset($_POST['submit'])) {
$_SESSION['rand1'] = rand(1, 20);
$_SESSION['rand2'] = rand(1, 20);
$_SESSION['randsvar'] = $_SESSION['rand1'] + $_SESSION['rand2'];
} else {
$input = $_POST['input'];
if($input == $_SESSION['randsvar']) {
echo 'correct';
} else {
echo 'incorrect';
}
exit;
}
?>
<form method="POST">
<label>
<?php echo $_SESSION['rand1'] . ' + ' . $_SESSION['rand2'] . ' = '; ?>
<input type="text" name="input" />
<input type="submit" name="submit" />
</label>
</form>

PHP calculator increase

I am creating simple calculator. I am just learning php and this is a small project.I have created a calculator with two inputs but I am now testing it with just one. It works but only if you type number+number. It doesn't work if it is number+number+number.
I would like that it would work if you inputted 2+2+2... or 2*2*2... or 6-2-2... and 2/2/2...
Code:
// Create Variables
$y = $_POST["input1"];
// Echo input value on screen
echo "<p>Operation: " . $y . "</p>";
// Validation
if(empty($y)){
?>
<script>
$(document).ready(function(){
$('#error').append('Error: Your Input is empty');
});
</script>
<?php
}elseif(preg_match("/[a-zA-Z]/", $y)){
?>
<script>
$(document).ready(function(){
$('#error').append('Error: You can only input numbers');
});
</script>
<?php
}else{
// Calculation Brain FOR + Operator
if (strpos($y,'+') !== false) {
$omega = substr($y, 0, strpos($y, '+'));
$alpha = substr($y, strpos($y, '+') + 1);
echo "<p>Omega: " . $omega . "</p>";
echo "<p>Alpha: " . $alpha . "</p>";
$gamma = $omega + $alpha;
// The Sum FOR + operator
echo "Calculation: " . $gamma;
}
}
That's usually a bad practice, but here you can use eval. But you have first to check that your string doesn't contains disallowed characters.
$allowedCharacters = "0123456789./*-+()% ";
if(preg_match('/^[^'.preg_quote($allowedCharacters).']+$/'), $y) {
eval('$result = '.$y.';');
echo "Calculation: " . $result;
}
The only problem is that you'll not be able to handle errors.
you could use this for the same operation
$test='2+2*3';
eval('$calc = '.$test.';');
echo "Calculation: " . $calc;
the out should be : 8

php can't add data to array

here's a question : After entering some data about students, i need to print them in top side of the page (form one). I've managed to print data for single student, but i can't make it to store data in $studenti array, so that it will print data for all students.
here's code that i used(i forgot to mention, i need to use sessions for this):
<?php
session_start();
$_SESSION['aindex'] = $_POST['index'];
$_SESSION['aime']= $_POST['ime'];
$_SESSION['aprosek'] = $_POST['prosek'];
//if ($index != "" && $ime != "" && $prosek !="")
//{
// = $index;
//= $ime;
//=$prosek;
//}
//print ($_SESSION['aindex']);
function inicijalizacija()
{
$studenti = array ();
$ind = $_SESSION['aindex'];
$im = $_SESSION['aime'];
$pr = $_SESSION['aprosek'];
$studenti[$ind]["ime"] = $im;
$studenti[$ind]["prosek"] = $pr;
return $studenti;
}
function dodaj($studenti)
{
$studenti[$_SESSION['aindex']]["ime"] = $_SESSION['aime'];
$studenti[$_SESSION['aindex']]["prosek"] = $_SESSION['aprosek'];
return $studenti;
}
function prikazi($studenti) //ovde u argumentu treba $studenti
{
print ("<h2> Lista Studenata: </h2>");
foreach ($studenti as $ind => $student)
{
if (empty($ind))
continue;
$n = $student["ime"];
$p = $student["prosek"];
print ("Index: " . $ind . " " . "Ime: " . $n . " " . "Prosek: " . $p );
}
print("<hr size ='1'>");
//Forma dodavanja
print (" <form action = 'index.php' method = 'post' >");
print ( " Indeks:&nbsp <input type = 'text' name = 'index' />");
print(" </br>");
print ( " Ime:&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp <input type = 'text' name = 'ime' >");
print(" </br>");
print ( " Prosek : <input type = 'text' name = 'prosek' />");
print(" </br>");
print (" <input type = 'submit' value = 'Dodaj' name = 'Dodaj' />");
}
$studenti = inicijalizacija();
?>
<html>
<head> <title> pokusaj </title> </head>
<body>
<?php
prikazi($studenti);
dodaj($studenti);
?>
</body>
</html>
It seems you're misunderstanding the way PHP works. For efficiency and security, all variables are destroyed when the script has ran and the variables used for this user aren't visible for the script when called by other users.
$_SESSION is an exception; data in $_SESSION will be preserved until the session expires, but it will still only be visible to one unique user (identified by a cookie).
If you want to save the data of a script for use when it is called again (using another session), you'll have to write data to a file or use a database.
PS, your script looks like it will introduce XSS and CSRF vulnerabilities; make sure you won't make the same mistakes that many people before you made.

Categories