PHP rand() function - php

I want to make something like a anti spam system, I've got this HTML:
What is <?php echo $six; ?> + <?php echo $rand1; ?> <input type="text" name="human" id="human">
And for these variables:
$human = #$_POST['human'];
$rand1 = rand(1, 9);
$six = 6;
$res = $rand1 + $six;
Then I do:
if($human==$res){
echo "Correct";
}else{
echo "Incorrect";
}
This is not working! Any ideas?

Remember to provide your $res or $rand1 variable value via your html form - changing your php to something like this:
$human = #$_POST['human'];
$res = #$_POST['res'];
if($human==$res){
echo "Correct";
}else{
echo "Incorrect";
}
$rand1 = rand(1, 9);
$six = 6;
$res = $rand1 + $six;
Then adding:
<input type="hidden" name="res" value="<php echo $res;?>">
into your html form

Related

Increment number in php every time data is received from sql

I am trying to make a program that can get data from Sql using php. the received data is a number from 1 to 5 and each number presents a color. every time a number is received a counter adds 1 for that color in html. I have been able to code this but if the page is refreshed the counted value becomes 0.
<?php
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) {
echo $row['name'].", ".$row['color']";
$red = "5";
$pink = "4";
$yellow = "3";
$black = "2";
$white = "1";
$colorid = $row['color'];
if ($colorid == $red){
echo "Red";
$re = 1;
$re = ++;
} elseif ($colorid == $pink){
echo "Pink";
$pi = 1;
$pi = ++;
} elseif ($colorid == $yellow){
echo "Yellow";
$ye = 1;
$ye = ++$;
} elseif ($colorid == $black){
echo "Black";
$blk = 1;
$blk = ++;
} elseif ($colorid == $white){
echo "White";
$wh = 1;
$wh = ++;
} else {
echo "Cannot verify the color code";
}
}
?>
<div>
<span>White: </span><input name="white" value="<?php echo (isset($wh))?$wh:'';?>">
<span>Black: </span><input name="black" value="<?php echo (isset($blk))?$blk:'';?>">
<span>Yellow: </span><input name="yellow" value="<?php echo (isset($ye))?$ye:'';?>">
<span>Pink: </span><input name="pink" value="<?php echo (isset($pi))?$pi:'';?>">
<span>Red : </span><input name="red" value="<?php echo (isset($re))?$re:'';?>">
</div>

It always says Correct! What did I do wrong?

$number1 = mt_rand(1,9);
$number2 = mt_rand(1,9);
$total = $number1 * $number2;
echo "<form method='post'>";
echo $number1 . " x " . $number2 . " = <input type='number' name='num1' required /><br>";
echo "<input type='submit' value='submit!' name='done'>";
echo "</form>";
if (isset($_POST['done'])) {
if (isset($_POST['num1']) == $total) {
echo "Correct!";
} else {
echo "Wrong!";
}
}
It always says Correct! And I dont know why ( im a beginner ), I just want to check if num1 is equal to $total
You have many problems in your code :
you must first check if the post is submit then if its wrong type the form
if (isset($_POST['done'])) {
//your code
}
else {
//your form
}
save $total in session to reuse it when the form submit, in your case $total have different value every time
isset() return true or false you can't comparison true or false with integer value if you want to use isset your code must be like this:
if(isset($_POST['num1']) && $_POST['num1'] == $total) {
}
You're comparing isset($var) to $total. They're both truthy so the condition is always true as long as 'num1' is defined in your POST data.
Maybe you should do something like :
isset($_POST['num1']) && $_POST['num1'] == $total
You should also probably cast 'num1' to a number
As said by Tom Udding, every time you refresh the page it calls ALL of that code again, so number1 and number2 are being randomly selected again.
Your current code has no way of saving the previous variable values. An unconventional way would be to add a hidden form field with the answer to the question, like below:
<?php
if (isset($_POST['done']) && isset($_POST['num1']))
{
//Get answer from form.
$total = $_POST['answer'];
if ($_POST['num1'] == $total)
{
echo "Correct!";
}
else
{
echo "Wrong!";
}
}
$number1 = mt_rand(1, 9);
$number2 = mt_rand(1, 9);
$total = $number1 * $number2;
echo "<form method='post'>";
echo $number1 . " x " . $number2 . " = <input type='number' name='num1' required /><br>";
//Added hidden form with answer.
echo "<input type='number' hidden name='answer' value='$total' />";
echo "<input type='submit' value='submit!' name='done'>";
echo "</form>";
?>
HOWEVER...
In a realistic rich web application, you wouldn't put your answer in your form for users to see, this is where you can use sessions to track your user's information as they traverse (or in your case refresh) your page.
So a more practical answer to your question would be the following:
<?php
session_start();
if (isset($_POST['done']) && isset($_POST['num1']))
{
$answer = $_SESSION['answer'];
if ($_POST['num1'] == $answer)
{
echo "Correct!";
} else
{
echo "Wrong!";
}
}
$number1 = mt_rand(1, 9);
$number2 = mt_rand(1, 9);
$total = $number1 * $number2;
$_SESSION['answer'] = $total;
echo "<form method='post'>";
echo $number1 . " x " . $number2 . " = <input type='number' name='num1' required /><br>";
echo "<input type='number' hidden name='answer' value='$total' />";
echo "<input type='submit' value='submit!' name='done'>";
echo "</form>";
?>

PHP Factorial Issue

I am trying to learn PHP and compute the factorial of a number when given a input from a user, but I seem to be stumped. My first and last condition checkout but when I put a number bigger than 2 my result is always false, here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Factorial</title>
</head>
<body>
<form action="" method="GET">
Enter Number: <input type="text" name="num"><br>
<input type="submit" name ="submit">
</form>
Factorial Of Your Number:
<?php
function factorial($n){
if (ctype_digit($n))
{
if ($n <= 1)
{
echo "1";
}
else
{
echo $n * factorial($n - 1);
}
}
else
{
echo "false";
}
}
if(isset($_GET['submit']))
{
$s = $_GET["num"];
factorial($s);
}
?>
</body>
</html>
I have tried editing many variations of this line echo $n * factorial($n - 1); but all result in false or an error and I can't seem to crack this. Any ideas? Note that I am trying to keep the php in the internal body not an externalphp file.
For your recursive function to work, it needs to return a number. Otherwise your function will try to calculate $n * null which throws an error.
function factorial($n){
if ($n <= 1) {
return 1;
} else {
return $n * factorial($n - 1);
}
}
if (isset($_GET['submit'])) {
$n = intval($_GET["num"]);
echo factorial($n);
}
see this solution, find factorial of a given number in PHP?
<?php
function findFactorial($num){
$fact = 1;
for($i=1; $i<$num+1; $i++){
$fact = $fact*$i;
}
return $fact;
}
$num = 5;
print_r(findFactorial($num));
?>
Here you go:
<?php
$num = $_POST["num"];
$factorial_value = 1;
for ($x=$num; $x>=1; $x--)
{
$factorial_value = $factorial_value * $x;
}
echo "Factorial of $num is $factorial";
?>
<form method="post">
Enter a num:
<input type="text" name="num">
<input type="submit" Value="CALCULATE YOUR FACTORIAL">
</form>

PHP compare user input against multiple variables

I have 5 variables that generate a random number and a sixth variable which is the users input.
Then I check to see if users input $userNum matches any of the random numbers. I know it's a dumb game, but I'm just messing around to learn more PHP
There has to be an easier way to do this.
if(isset($_POST['submit']))
{
$userNum = $_POST['userNum'];
$spot1 = rand(1, 100);
$spot2 = rand(1, 100);
$spot3 = rand(1, 100);
$spot4 = rand(1, 100);
$spot5 = rand(1, 100);
echo $spot1 ."<br>" .$spot2 ."<br>" .$spot3 ."<br>" .$spot4 ."<br>" .$spot5;
if($userNum == $spot1)
{
echo "you hit a mine!";
exit();
}
if($userNum == $spot2)
{
echo "you hit a mine!";
exit();
}
if($userNum == $spot3)
{
echo "you hit a mine!";
exit();
}
if($userNum == $spot4)
{
echo "you hit a mine!";
exit();
}
if($userNum == $spot5)
{
echo "you hit a mine!";
exit();
} else {
echo "you lived!";
}
}
You don't need to store spots in an array or anything like that just use a simple loop.
<?php
if(isset($_POST['submit'])){
$userNum = (int) $_POST['userNum'];
$hitMine = false;
for($i = 1; $i <= 5; $i++){
$randNum = rand(1, 100);
echo $randNum . '<br />';
if($randNum == $userNum){
$hitMine = true;
}
}
if($hitMine == true){
echo "you hit a mine!";
}
}
?>
I would make an array of the spots
$spot1 = rand(1, 100);
$spot2 = rand(1, 100);
$spot3 = rand(1, 100);
$spot4 = rand(1, 100);
$spot5 = rand(1, 100);
// Make an array of the spots.
$spots = array($spot1, $spot2, $spot3, $spot4, $spot5);
if(in_array($userNum, $spots)) {
echo "you hit a mine!";
exit();
} else {
echo "you lived!";
}
For 50 or more spots you can dynamicaly insert the values in the array assuming you use the rand() function in the real php-code:
$spots = Array();
for ($i = 0; $i < 50; $i ++) {
array_push($spots, rand(1,100));
}
or:
for ($i = 0; $i < 50; $i ++) {
$spots[$i] = rand(1,100);
}
You can use Switch Case in place of if else to make it better and quick.
if(isset($_POST['submit']))
{
$userNum = $_POST['userNum'];
$spot1 = rand(1, 100);
$spot2 = rand(1, 100);
$spot3 = rand(1, 100);
$spot4 = rand(1, 100);
$spot5 = rand(1, 100);
echo $spot1 ."<br>" .$spot2 ."<br>" .$spot3 ."<br>" .$spot4 ."<br>" .$spot5;
Switch($userNum)
{
Case $spot1:
Case $spot2:
Case $spot3:
Case $spot4:
Case $spot5:
echo "you hit a mine!";
break;
default: echo "you lived!";
break;
}
}
Just store the valid spots in an array.
$myhashmap = array();
$myhashmap['spot1'] = true;
$myhashmap['spot2'] = true;
if(isset($myhashmap[$userNum] ) )
{
echo "you hit a mine!";
exit();
}
Here's a link for more info about PHP arrays: http://www.tutorialspoint.com/php/php_arrays.htm

Using PHP trying to convert str to int

I really don't get why this isn't working, so please help. I'm trying to convert a str to an int and do if statements with it, but I can't for some reason. The code jumps right over the if statement like it's not even there???
<?php
$cost = $_REQUEST['cost'];
$cost = (int) $cost;
if($cost < 2){
header('Location: page.php?say=numerror');
}
?>
<input name="cost" id="cost" type="text" class="tfield" />
I have a suspicion you need:
if ($cost < 2) {
exit(header('Location: page.php?say=numerror'));
}
why do you need a conversion just use this:
<?php
$cost = $_REQUEST['cost'];
if($cost < 2 or !is_numeric($cost)){
header('Location: page.php?say=numerror');
}
?>
<input name="cost" id="cost" type="text" class="tfield" />
Try this:
<?php
$cost = $_REQUEST['cost'];
$cost = intval($cost);
if($cost < 2){
header('Location: page.php?say=numerror');
}
?>
// HTML
<input name="cost" id="cost" type="text" class="tfield" />
Here is more about intval() function at intval() PHP reference manual. I hope, that will be helpful.
If this not help you. Here is PHP function where you from string can separate integers.
<?php
function str2int($string, $concat = true) {
$length = strlen($string);
for ($i = 0, $int = '', $concat_flag = true; $i < $length; $i++) {
if (is_numeric($string[$i]) && $concat_flag) {
$int .= $string[$i];
} elseif(!$concat && $concat_flag && strlen($int) > 0) {
$concat_flag = false;
}
}
return (int) $int;
}
// Callings
echo var_dump(str2int('sh12apen11')); // int(12)
echo var_dump(str2int('sh12apen11', false)); // int(1211)
echo var_dump(str2int('shap99en')); // int(99)
echo var_dump(intval('shap99en')); // int(0)
?>
P.S Function copied from link above. Isn't mine.

Categories