PHP code how to clean user input from $_POST - php

I have this PHP code:
<?php
$score11 = $_POST['passmarks12'];
if($_POST['passmarks12'] > 100){
$grade11 = "";
}
elseif ($_POST['passmarks12'] < 45){
$grade11 = "Fail";
}
$strg = " $grade11";
echo $strg;
?>
The code is always printing "Fail" regardless of what is sent in.
I want it so that if it passes in blank or invalid input it fails.
And how should I properly cleanse the input?

Try this:
<?php
//$_POST['passmarks12'] = '';
if(empty($_POST['passmarks12']) || $_POST['passmarks12'] > 100)
{
$grade11 = "";
}
else if ($_POST['passmarks12'] < 45){
$grade11 = "Fail";
} else{
$grade11 = "Pass";
}
$strg = " $grade11" ;
echo $strg;
?>

Points:
Check if $_POST['key'] exists using isset.
Check if $_POST['key'] has a valid data type, string.
It may come as array.
Check if $_POST['key'] has a valid numeric format.
Compare $_POST['key'](String) and 45(Integer), using intval.
Example:
<?php
switch (true) {
case !isset($_POST['passmarks12']):
case !is_string($score = $_POST['passmarks12']):
case !is_numeric($score):
$result = 'Error (Invalid parameter)';
break;
case (intval($score) < 45):
$result = 'Fail (Less than 45)';
break;
default:
$result = 'Success (No less than 45)';
}
echo $result;

I think you want
elseif ($_POST['passmarks12'] < 45 && !empty($_POST['passmarks12']))

This PHP code will make sure $_POST is not empty before comparing it to 100.
<?php
$score11 = $_POST['passmarks12'];
if(empty($_POST['passmarks12']) || $_POST['passmarks12'] > 100)
$grade11 = "";
elseif ($_POST['passmarks12'] < 45)
$grade11 = "Fail";
$strg = " $grade11" ;
echo $strg;
?>

Related

Why is this if condition not working fine?

$isPass should be "Go to hell", which should differ from 0, yet, the code proves otherwise. Why?
<?php
$marks = 35;
$passing_marks = 36;
$isPass = ($marks > $passing_marks) ? true : "Go to hell";
echo $isPass; // prints "Go to hell".
if($isPass == 0){
echo "Pass"; // prints "Pass", but why and how
}
?>
Just try this.
<?php
$marks = 35;
$passing_marks = 36;
if($marks > $passing_marks){
echo "Pass";
}
else {
echo "Go to hell";
}
?>
You don't need the other variable, just execute the check on one if-statement.

How to check different conditions into if statement based on different scenario

I want to check different conditions into if statement based on different scenario (Will get the $status value as 'Y' or 'N'). Please check the code below and let me know the issue here.
$fstrto = "10";
$cstrto = "7";
if($status == 'N')
{
$cond = "$fstrto <= $cstrto";
}
else
{
$cond = "$fstrto >= $cstrto";
}
if($cond)
{
echo "Success";
}
This code is not working as it takes the "$fstrto <= $cstrto" as variable.
Remove the quotes. Use intval/doubleval if the input is a string as in $fstrto = intval($fstrto);.
$fstrto = 10;
$cstrto = 7;
if($status == 'N')
{
$cond = $fstrto <= $cstrto;
}
else
{
$cond = $fstrto >= $cstrto;
}
if($cond)
{
echo "Success";
}
Why it works: $cond is being assigned the value of a boolean expression, the values of which can be true or false. if($cond) just checks whether $cond is true or false
what is need to do is when using string as a php code use
eval — Evaluate a string as PHP code
Use below code work like charm:
$fstrto = "10";
$cstrto = "7";
if($status == 'N')
{
$cond = "$fstrto <= $cstrto";
}
else
{
$cond = "$fstrto >= $cstrto";
}
if(eval("return $cond;"))
{
echo "Success";
}
IMPORTANT:
Use of eval is highly discouraged
NEVER EVER use eval with params by POST/GET without sanitize them
When is eval evil in php?
You "$fstrto <= $cstrto" is a string now a compare statement.
$fstrto = "10";
$cstrto = "7";
if( ($status == 'N' && $fstrto <= $cstrto) || ($status != 'N' && $fstrto >= $cstrto) )
{
echo "Success";
}
Potentially turn it into a function that funnels into a switch statement like so:
function evaluateCondition($status, $a, $b) {
switch ($status) {
case 'Y':
return $a >= $b;
break;
case 'N':
return $a <= $b;
break;
default:
// Error Log. Unknown Status.
}
}
Any future addition can be appended onto the switch statement as necessary, if it gets more convoluted have each case return a separate function() to improve readability.
In terms of the current version you could use it like so:
$result = evaluateCondition('Y', 5, 6);
var_dump($result); // bool(false)
Hope that helps.
$fstrto = "10";
$cstrto = "7";
$cond = false;
if($status == 'N')
{
if($fstrto <= $cstrto){
$cond = true;
}
}
else
{
if($fstrto >= $cstrto){
$cond = false;
}
}
if($cond)
{
echo "Success";
}

Is there any way something like this possible?

<?php
$division=$row['mark'];
$pass="Passed";
if($division>=80 && $pass==include "result.php")// Result.php has two value: one is `Pass` and the other is `Fail`.
{
echo "Letter";
}
elseif($division>=70 && $pass==include "result.php")
{
echo "First";
}
else
{
echo "Fail";
}
?>
What I want to output here is: if $division is equal to 80 and at the same time if $pass is equal to Passed, echo Letter. But if $division is less than 70, echo Fail; also $pass here equals to fail which is taken from result.php. I have been trying to output it with following code, but it does not work. It outputs FailFailFailFail when $division is less than 70.
Code for Result.php
<?php
$eng=40;
$mizo=40;
$hindi=40;
$maths=40;
$ss=40;
$science=40;
if ($eng>=40 && $mizo>=40 && $hindi>=40 && $maths>=40 && $ss>=40 && $science>=40)
{
echo "<font color=green>Passed</font>";
}
else
{
echo "<font color=red>Failed</font>";
}
?>
You are going about this all the wrong way. You can't compare the results of an include like that, not to mention they don't match properly anyway as you're comparing a single word string against a string with a whole bunch of HTML in it.
A better way to do it is to include results.php and store your answer in a variable. I have written an example below.
First off you need to change result.php to:
<?php
$eng=40;
$mizo=40;
$hindi=40;
$maths=40;
$ss=40;
$science=40;
if ($eng>=40 && $mizo>=40 && $hindi>=40 && $maths>=40 && $ss>=40 && $science>=40)
{
$test = "Passed";
}
else
{
$test = "Failed";
}
?>
Then you put the following in the first file:
<?php
$division=$row['mark'];
$pass="Passed";
include("result.php");// Result.php has two value: one is `Pass` and the other is `Fail`, store in $test.
if($division>=80 && $pass==$test)
{
echo "Letter";
}
elseif($division>=70 && $pass==$test)
{
echo "First";
}
else
{
echo "Fail";
}
?>
Something like this will do. For your result.php, use the following:
<?php
$eng= 40;
$mizo= 40;
$hindi= 40;
$maths= 40;
$ss= 40;
$science= 40;
// first group your variable into one array = $all
$all = array($eng, $mizo, $hindi, $maths, $ss, $science);
// second, just iterate over them till you find one value -40
for($i=0; $i < count($all); $i++){
if($all[$i] < 40) $sum = 1;
}
?>
For output:
<?php include "result.php";?>
<?php
$division=$row_['mark'];
$pass="Passed";
$test = (!empty($sum)) ? 'Failed' : 'Passed';
if($division>=80 && $pass==$test)
{
echo "Letter";
}
elseif($division>=70 && $pass==$test)
{
echo "First";
}
else
{
echo "Passed";
}
?>
You need to include the file first:
<?php
include "result.php"; //include the file
$division =$ row['mark'];
$pass = "Passed";
if($division == 80 && $pass == "Passed") {
echo "Letter";
}
elseif($division < 70) {
echo "Fail";
}
?>

Adding conditions dynamically in php if condtion

I am trying to add a condition dynamically in the if condition . But it is not working . Please help me to fix the issue.
I am trying a code like this
$day_difference = "some integer value";
if(sheduled_time == 'evening'){
$condition = '>';
}else{
$condition = '==';
}
then
if($day_difference.$condition. 0){
echo "something";
}else{
echo "h";
}
An alternative to gerald's solution; I would suggest that you use a function that validates the inputs using a switch-case operation:
function evaluate ($var1, $operator, $var2)
{
switch $operator
{
case: '<': return ($var1 < $var2);
case: '>': return ($var1 > $var2);
case: '==': return ($var1 == $var2);
}
return null;
}
What you need is the eval() method.
I.e.
$var1 = 11;
$var2 = 110;
$cond1 = '$var1 > $var2';
$cond2 = '$var1 < $var2';
if(eval("return $cond1;")){
echo $cond1;
}
if(eval("return $cond2;")){
echo $cond2;
}
As justly noted beneath, you should exercise the necessary precautions when using this method!
This is not the way to do this.
Just define a function which returns true if the desired conditions are met.
For example, we can define the function decide which receives two arguments, $day_difference and $scheduled_time:
function decide($day_difference, $scheduled_time)
{
if($scheduled_time == 'evening')
{
return $day_difference > 0;
}
else
{
return $day_difference == 0;
}
}
And use it like so:
if( decide($day_difference, $scheduled_time) )
{
echo "something";
}
else
{
echo "h";
}
according to your requirements this can be done using the PHP eval() function which i don't recommend using it only when necessary.
you can check When is eval evil in php?
you can use the below script instead:
if( $sheduled_time == 'evening' && $diff > 0 )
{
echo "This is the Evening and the Difference is Positive";
}
else if($diff == 0)
{
echo "This is not evening";
}
Thankyou for helping me solve my question
I solved this in another way
$day_difference = "some integer value";
$var1 = false ;
if($sheduled_time == 'evening_before'){
if($day_difference > 0 ){
$var1 = true ;
}
}else{
if($day_difference == 0 ){
$var1 = true ;
}
}
if($var1 === true){
echo "something";
}else{
echo "h";
}

PHP functions and if/else statements

I am trying to write a script that includes if/else statements and functions. some background
$parts first character should have the letter "N"
$desc is suppose to be at least one character long
$price needs to be positive (0 or higher)
if all three of theses requirements are met then it should say "data accepted" if something is not met (one or all) the "Invalid...." needs to show.
can someone tell me what part of my script I should look at.
<?php
$parts = $_POST["parts"];
$desc = $_POST["desc"];
$price = $_POST["price"];
$pa = substr($parts, 0, 1);
$de = strlen($desc);
if ($pa != "N")
{echo "Invalid Part Number";}
else
if ($de <= 1)
{echo "Invalid Description Length";}
else
if ($price <= 0)
{echo "Invalid Price";}
else
{echo "Data Accepted";}
?>
The second if should be if($de==1) $de=1 will always return true.
Also add semicolons after each statement.
Your requirement:-
$parts first character should have the
letter "N"
$desc is suppose to be at least one
character long
$price needs to be positive (0 or
higher)
Solution:-
$parts = $_POST["parts"];
$desc = $_POST["desc"];
$price = $_POST["price"];
$pa = substr($parts, 0, 1);
$de = strlen($desc);
if($pa != 'N') {
echo "Invalid Part Number";
} elseif($de < 1) {
echo "Invalid Description Length";
} elseif($price < 0) {
echo "Invalid Price";
} else {
echo "Data Accepted";
}
the second if should be if($de < 1) you can have if($de == 1) if its always going to be one character long but this will work if its 1 or more
$parts = $_POST["parts"];
$desc = $_POST["desc"];
$price = $_POST["price"];
<?php
$parts = '';
$desc = '';
$price = 0;
if ($_POST['parts'] != 'n')
{
echo 'Not equal to n<br>';
}
else {
'Accepted input<br>';
}
$desc = strlen($_POST['desc']);
if ($desc < 1)
{
echo 'Input less than 1<br>';
}
else {
echo 'Accepted input<br>';
}
if ($_POST['price'] < 0)
{
echo 'Input below 0<br>';
}
else {
echo 'Input accepted<br>';
}
?>

Categories