Multiple conditions in PHP - php

I know this is embarrassing easy but I cannot get this to work right now, keep getting syntax errors, I just added in a jquery code that pre-fills in a form filed and when you select the form field it will clear the default value. The result though is if a user submits the form without changing the default value, I need to see if it exist in addition to my normal string sanitations
In this snippet below of PHP I need to run 2 conditions on $fname but below will not work, can someone help please
$fname = 'first name';
if (trim($fname) == '') && ($fname != 'first name') {
$err .= "error";
}else{
$err .= "all good";
}
For karim79
this code below from your example, exactly like this gives me this error
Fatal Error: Can't use function return value in write context on line 5
<?PHP
$fname = '';
if(empty(trim($fname))) {
echo "First name is empty";
}
?>

$fname = 'first name';
if (trim($fname) == '' || $fname != 'first name') {
$err .= "error";
} else {
$err .= "all good";
}
I would prefer to use strcmp:
if (trim($fname) == '' || strcmp($fname,'first name') !== 0) {
$err .= "error";
} else {
$err .= "all good";
}
If the case of the first name is not important, you should consider using strcasecmp instead. Also note you can use empty to test for the empty string:
$fname = '';
$fname = trim($fname);
if(empty($fname)) {
echo "First name is empty";
} else {
echo "Not empty";
}
When using empty, beware the following (from the manual):
Note: empty() only checks variables as
anything else will result in a parse
error. In other words, the following
will not work: empty(trim($name)).

$fname = 'first name';
if (trim($fname) == '' || $fname == 'first name') {
$err .= "error";
}else{
$err .= "all good";
}
PS: I assumed you want to raise an error if the string is either empty or the standard value. If that's wrong let me know.

I would NOT recommend using empty() for anything. It has some tricky return patterns, including telling you that a 0 is empty, and things of that nature. This, unfortunately, is a shortcoming of PHP.
Instead, try this algorithm (The following assumes your form POSTs):
<?php
$err = array();
// this is for sticklers..with E_STRICT on, PHP
// complains about uninitialized indexes
if( isset($_POST['name']) )
{
$name = trim($_POST['name']);
}
else
{
$name = '';
}
if( strlen($name) == 0 )
{
$err[] = "First name is required.";
}
// after validation is complete....
if( count($err) > 0 )
{
echo "There are errors!";
// probably something more elaborate here, like
// outputting an ordered list to display each error
print_r($err);
}
else
{
echo "It's all good!";
}
?>

Related

Form Validation of Multiple errors

What would be the best way to code for the following
To check if its empty
That its alpha
Length
I am wanting a way that I am able to combine the following if statements
Current Code
if (isset($_POST['submitButton'])) {
$fullName = $_POST['fullname'];
if(fullName != ' ')
{
$errorfullName .= 'Please Enter Your Name';
}
}
}
if statements that need to be included:
if (!ctype_alpha(str_replace(array("'", "-"), "",$fullName))) {
$errorfullName .= '<span class="errorfullName">*First name should be alpha characters only.</span>';
}
if (strlen($fullName) < 3 OR strlen($fullName) > 40) {
$errorfullName .= '<span class="errorfullName">*First name should be within 3-40 characters long.</span>';
}
Your are missing $ sign before fullName.Use empty function to check weather the string is empty or not. Use the below code
if (isset($_POST['submitButton'])) {
$fullName = $_POST['fullname'];
if(empty($fullName))
{
$errorfullName .= 'Please Enter Your Name';
}
}
If you need to combine more statements, you can do it with ( if{} elseif{} else{/*NO ERROR*/}. But I think there is a smarter solution:
function valide_fulname($fullname) {
if (isset($fullName) && trim($fullName)!='')
return 'Please enter your name.';
if (!ctype_alpha(str_replace(["'", "-"], "", $fullName)))
return 'First name should be alpha characters only.';
if (strlen($fullName)<3 || strlen($fullName)>40)
return 'First name should be within 3-40 characters long.';
// no error
return false;
}
if (isset($_POST['submitButton'])) {
$error = valide_fullname($_POST['fullname']);
if (!$error)
echo "It's OK!";
else
echo '<span class="errorfullName">' . $error . '</span>';
}

PHP - Check if one of two form fields is filled?

My form has Phone and Email fields.
Many people might not be wanting/able to put both,
so I thought, that the validator would require only
one of those two filled, instead of requiring the both filled.
I've tried thinking of different ways to do it but I'm pretty new to PHP,
so I couldn't come with any.
Would this be possible?
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["name"]))
{$nameErr = "Name is required";}
else
{$name = test_input($_POST["name"]);}
if (empty($_POST["email"]))
{$emailErr = "Email is required";}
else
{$email = test_input($_POST["email"]);}
if (empty($_POST["phone"]))
{$phone = "";}
else
{$website = test_input($_POST["website"]);}
if (empty($_POST["comment"]))
{$comment = "";}
else
{$comment = test_input($_POST["comment"]);}
}
Thank you.
As your title states, 1 / 2 form fields is filled in.
$i = 0; // PUT THIS BEFORE YOUR IF STATEMENTS
Inside of your statements:
if (empty($_POST["phone"])) {
$phone = "";
} else {
$i++; // PUT THIS IN ALL YOU WANT TO COUNT, IT WILL ADD 1 to $i EACH TIME YOU CALL IT
$website = test_input($_POST["website"]);
}
Now at the end, if
// YOU NEED TO CHANGE YOUR NUMBERS TO WHATEVER COUNT YOU WANT
if ($i < 2) { // IF $i IS LESS THAN 2
// YOUR CODE HERE
} else { // IF $i IS 2 OR MORE
// YOUR CODE HERE
}
Hope this is somewhat useful!
or as stated above, you can use an
if (#$A && #$B) { // REQUIRES BOTH TO BE TRUE
// YOUR CODE HERE
} elseif (#$A || #$B) { // REQUIRES ONLY ONE TO BE TRUE
// YOUR CODE HERE
} else { // NONE ARE TRUE
// YOUR CODE HERE
}
if you are wondering about the # signs above, they are simply checking if they are set, you could change the code to !empty($A) which is what you used above. Putting the ! before the empty function checks that it is false or that $A is actually set.
If i would have to check a form like you, i'd do it this way:
$res = '';
if(empty($_POST['name']))
$res .= 'The name is required.<br>';
if(empty($_POST['email']))
$res .= 'The email is required.<br>';
if(empty($_POST['phone']) && empty($_POST['email']))
$res .= 'You need to enter phone or email.<br>';
if(strlen($res) > 0) {
echo 'We have these errors:';
echo $res;
}
else {
echo 'No Errors!';
}
If you want to show only one error each time, use this code:
$res = '';
if(empty($_POST['name']))
$res = 'The name is required.<br>';
elseif(empty($_POST['email']))
$res = 'The email is required.<br>';
elseif(empty($_POST['phone']) && empty($_POST['email']))
$res = 'You need to enter phone or email.<br>';
if(strlen($res) > 0) {
echo $res;
}
else {
echo 'No Error!';
}
Even if i think it's very basic, i'll explain the mentioned part, even if you could look it up from php.net:
$res .= 'The name is required';
The ".=" operator adds the part 'The name is required' to the variable $res. If this happens the first time, the variable will be empty, because i initialized it as an empty string. With every ongoing line, another error Message will be added to the string.
if(strlen($res) > 0) {
strlen() will return the length of the string in $res. If no error occured, it would still be empty, so strlen() would return 0.

Dynamic if-statement with variables?

I'm trying to create a dynamic if-statement. The reason I want to do this, is because I need to check server-sided whether inputfields match my regex and are not empty. However, some of my inputfields can be removed in my CMS, meaning there would be more/less inputfields accordingly.
Ideally I would add variables in my if-statement but I'm not 100% sure if that's allowed, so perhaps I would need an other way to solve this problem. Here's what I tried:
if ($f_naw['streetname'] == 1)
{
$streetname= $_POST['streetname']; //Used in INSERT query
$cstreetname = " || $_POST['streetname'] == ''"; //Used to check if field is empty
$pstreetname = " || !preg_match($streetnameReg,$_POST['streetname'])"; //Used to check if it matches my regex
}
else
{
//These variables define variables if inputfields are not shown
$streetname= ''; //No streetname means it's excluded in INSERT query
$cstreetname = ''; //Not needed in check
$pstreetname = ''; //Also not needed in check
}
// more of these if/else statements
if ($_POST['firstname'] == '' || $_POST['lastname'] == '' || $_POST['email'] == '' $cstreetname $cpostalcode $chometown $ctelnr $csex $cdateofbirth)
{
echo 'One of the fields is empty.';
header('refresh:3;url=index.php');
}
else
{
//Regex check, after that more code
}
My idea was to check if a specific field is shown on the front-end and in that case I'm creating some variables that I want to paste in my if-statements.
I'm getting an error saying Server error meaning my php-code would be invalid.
Is it even possible at all to make a dynamic if-statement? If yes, at what part am I failing?
Help is much appreciated! Thanks in advance.
First of all, since it looks like you need to combine all of the conditionals with ||, you can correct your program by writing it like this:
if ($f_naw['streetname'] == 1)
{
$streetname= $_POST['streetname']; //Used in INSERT query
$cstreetname = $_POST['streetname'] == ''; //Used to check if field is empty
$pstreetname = !preg_match($streetnameReg,$_POST['streetname']); //Used to check if it matches my regex
}
else
{
//These variables define variables if inputfields are not shown
$streetname= ''; //No streetname means it's excluded in INSERT query
$cstreetname = false; //Not needed in check
$pstreetname = false; //Also not needed in check
}
if ($_POST['firstname'] == '' || $_POST['lastname'] == '' || $_POST['email'] == '' || $cstreetname || $cpostalcode || $chometown || $ctelnr || $csex || $cdateofbirth)
{
echo 'One of the fields is empty.';
header('refresh:3;url=index.php');
}
This would work, but it's unwieldy. A much better solution would be to use an array (let's name it $errors that gets dynamically populated with errors resulting from validating your fields. Like this:
$errors = array();
if ($f_naw['streetname'] == 1)
{
$streetname= $_POST['streetname']; //Used in INSERT query
if ($streetname == '') {
$errors[] = 'Streetname cannot be empty.'; // message is optional
}
if (!preg_match($streetnameReg,$streetname)) {
$errors[] = 'Streetname is invalid.'; // message is optional
}
}
And then:
if ($errors) {
echo 'There are errors with the data you submitted.';
header('refresh:3;url=index.php');
}
If you provided human-readable error messages you can also arrange for them to be displayed so that the user knows what they need to fix. And of course there are lots of variations of this technique you can use -- e.g. group the error messages by field so that you only show one error for each field.
If you want to check for empty $_POST fields you can do something like this
$error = False;
foreach($_POST as $k => $v)
{
if(empty($v))
{
$error .= "Field " . $k . " is empty\n";
}
}
if(!$error)
{
echo "We don't have any errrors, proceed with code";
}
else
{
echo "Ops we have empty fields.\n";
echo $error;
}
And after you are sure that all the fields are not empty you can do other stuff.

Better practice to throw custom PHP errors using procedural way

I know this question may be asked previously but I want to show my code and I would like to know that whether am doing a simple thing or complicating the code? Moreover answers say use try and catch but am going with procedural method so I would like to know that am I going right?
What I do it, for example a contact form
<?php
if(isset($_POST['contact'])) {
$throw_error = array();
//First Block Is Validation
if($_POST['first_name'] == '' || $_POST['last_name'] == '') {
$throw_error['field_blank'] = 'Fields Cannot Be Blank';
} elseif(strlen($_POST['first_name']) < 3) {
$throw_error['char_len'] = 'First Name Cannot Be Less Than 3 Characters';
}
//Second Block Is Process If No Errors Are Found
if(empty($throw_error)) {
$first_name = $_POST['first_name'];
//Don't worry about the sanitizing part, am doing it
//Process the form ahead and then redirect using header()
}
} elseif(!empty($throw_error)) { //Third Block To Throw Error If Any Errors Found
if(isset($throw_error['field_blank'])) {
echo $throw_error['field_blank'];
} elseif(isset($throw_error['char_len'])) {
echo $throw_error['char_len'];
}
}
?>
<form>
<input type="text" name="first_name" />
<input type="text" name="last_name" />
<input type="submit" value="Submit" name="contact" />
</form>
I would also recommend using Try/Catch. You can still use it in procedural blocks.
If you are dead set against it, this code looks like it will do what you want it to do, but it's over-engineered. Since the user can either have a field_blank or char_len error, you only need a single string error variable.
$error = NULL;
if($_POST['first_name'] == '' || $_POST['last_name'] == '') {
$error = 'Fields Cannot Be Blank';
} elseif(strlen($_POST['first_name']) < 3) {
$error = 'First Name Cannot Be Less Than 3 Characters';
}
...
if(!empty($error)) {
echo $error;
}
If you need to catch and display multiple non-exclusive errors, you can use the array you cited in your sample code and just iterate over the values rather than making a giant if/elseif block.
} elseif(!empty($throw_error)) { //Third Block To Throw Error If Any Errors Found
foreach($throw_error as $key => $message) {
echo $message.'<br>';
}
}
A try/catch you be great here. It eliminates all necessary for a throw_error array, as well as cuts down dramatically on the code.
try{
$first_name = '';
if(isset($_POST['contact'])) {
if($_POST['first_name'] == '' || $_POST['last_name'] == '') {
throw new Exception('Fields Cannot Be Blank');
} elseif(strlen($_POST['first_name']) < 3) {
throw new Exception('First Name Cannot Be Less Than 3 Characters');
}
$first_name = $_POST['first_name'];
}
}catch(Exception $e){
echo $e->getMessage();
}
If you were looking to pass an array to this catch statement, the easist way that I have found, is to serialize the array, then unserialize once complete. This will allow you to print all errors at once:
try{
$first_name = '';
if(isset($_POST['contact'])) {
if($_POST['first_name'] == '' || $_POST['last_name'] == '') {
$throw_error[] = 'Fields Cannot Be Blank';
}
if(strlen($_POST['first_name']) < 3) {
$throw_error[] = 'First Name Cannot Be Less Than 3 Characters';
}
if(isset($throw_error)){
throw new Exception(serialize($throw_error));
}
$first_name = $_POST['first_name'];
}
}catch(Exception $e){
$errors = unserialize($e->getMessage());
foreach($errors as $error){
echo $error.'<br>';
}
}

how to restrict the value entered in a textbox based on the value entered in the previous one in php

I have 2 textboxes one is for maximum marks and the other for the obtained marks..
The value to be entered in the second box must be restricted in such a way that it is less than or equal to the maximum marks.. Only numbers must be entered into those boxes..
Maximum Marks<input type=text name=maxmarks maxlength='2' >
Obtained marks<input type='text' maxlength='2' name='obtmarks'>
Please help me with this.. Thank you in advance..
Well if you want to do it client side, you will have to use Javascript. If you want to do it server-side, why don't you send them back the page with an error message if the second number exceeds the first. You might also might want to look into HTML5 input options if that is an available option for you. Those will automatically do the number validation.
You could try something like this...
$response_array = array();
if($obtained > $max){
$response_array['status'] = 'error';
$response_array['message'] = '<div class="alert alert-error">Obtained to big</div>';
}
if(!is_numeric($obtained){
$response_array['status'] = 'error';
$response_array['message'] = '<div class="alert alert-error">Obtained not a number</div>';
}
echo json_encode($response_array);
This is pseudo code, obviously you will need to tweak it for your purpose.
First you have to make checks in your php script that you submit the form, you can use javascript after to make it more user friendly but if someone change the source code or just turn javascript off he will be able to submit anyting.
In your process_form.php:
session_start();
$errors = array();
if (!isset($_POST['maxmarks']) || empty($_POST['maxmarks'])) {
$errors[] = 'The Maximum Marks field is required.';
}
else {
if (!is_int($_POST['maxmarks'])) {
$errors[] = 'The Maximum Marks field must be an integer.';
}
else {
$maxmarks= (int) trim($_POST['maxmarks']);
}
}
if (!isset($_POST['obtmarks']) || empty($_POST['obtmarks'])) {
$errors[] = 'The Obtained Marks field is required.';
}
else {
if (!is_int($_POST['obtmarks'])) {
$errors[] = 'The Obtained Marks field must be an integer.';
}
else {
$obtmarks= (int) trim($_POST['obtmarks']);
}
}
if (!empty($errors)) {
$_SESSION['form_errors'] = $errors;
header('Location: your_form.php');
die();
}
else if ($obtmarks > $maxmarks){
$errors[] = 'The Obtained Marks must be less or equal to Maximum Marks.';
$_SESSION['form_errors'] = $errors;
header('Location: your_form.php');
die();
}
else {
//process data
}
In your_form.php now:
session_start();
if (isset($_SESSION['form_errors']) && !empty($_SESSION['form_errors'])) {
$errors = $_SESSION['form_errors'];
unset($_SESSION['form_errors']);
}
echo '<ul>';
if (isset($errors)) {
foreach($errors as $error) {
echo '<li>' . $error . '</li>';
}
}
echo '</ul>';
//your form here

Categories