Verify form field with isset() - php

Having issues with verifying that my form fields are not empty. I thought I used isset in the past but I am having issues with it below. I know I can do it with =="" but want to figure it out this way.
if(isset($_POST['submit'])){
$error= false;
if (isset($_POST['name'])){$name=$_POST['name'];}else{$error=true; $error_message="enter a name"; echo "no name";};
if(!$error){
//SUBMIT TO DATABASE
}else{ echo $error_message;
}
}
But I keep getting the error that error_message is not set.

Isset() just test if the variable exists. It's almost always the case in a POST form (even if variable is empty). To be sure they're not, use the empty() test.
Here is the code :
if(count($_POST) > 0){
$error = false;
if (!empty($_POST['name']))
$name = $_POST['name'];
else{
$error = true;
$error_message = "enter a name";
echo "no name";
}
if(!$error)
//SUBMIT TO DATABASE
else
echo $error_message;
}
you also had a syntax error with the semicolon after your first else.
Be careful, a variable set to 0 is detected as being empty. Check http://php.net/manual/en/function.empty.php

First, I'd recommend -not- using this method to determine if there was a post. I generally use one of the following:
if($_POST)
OR
if(count($_POST) > 0)
The second isset() call (to check for the name) is fine. Try using full caps to set TRUE or FALSE to the $error variable. You can also use 0 and 1 for TRUE and FALSE respectively; they work fine with if($error) and if(!$error). I believe this is where your problem lies. That is, $error was never set properly, so it is in fact not TRUE, but 'false'. However, because $_POST['name'] wasn't set, and $error_message was not either. Let me know if this works for you. I'll look into it further if it doesn't.

An empty PHP string is not null:
$a = '';
echo isset($a); //true
echo $a == ''; //true
use == instead
You could also use empty($var) function

Related

Check if variable is set in PHP

So I'm trying to see if the user inputted anything:
$test = $_GET["restaurantName"];
if(isset($test))
{
echo "you inputed something";
echo "$test";
}
if(!isset($test))
{
echo "you did not input anything";
echo "$test";
}
die("The End");
For some reason even when I don't input anything it still passes the first if statement and says that something has been inputted even when I don't I looked up the documentation about isset() and I'm pretty sure that this is how you are supposed to use it.
You should do it this way if you want to keep the same layout style.
if(isSet($_GET["restaurantName"])) {
$test = $_GET["restaurantName"];
}
if(isset($test))
{
echo "you inputed something";
echo "$test";
} else { //!isset($test)
echo "you did not input anything";
echo "$test";
}
Your problem is that you are setting the variable, even if the GET doesn't exist.
How I would do it personally, as it makes the code much shorter with the same outputs:
if(isSet($_GET["restaurantName"])) {
$test = $_GET["restaurantName"];
echo "Your input: ".$test;
} else {
echo "No Input";
}
You are setting it: $test = $_GET["restaurantName"];
the isset checks whether a variable has been set, not whether the variable contained is null or empty, you could use !empty
you can also check isset($_GET["restaurantName"];) but beware even if you have the get variable in your url as ?restaurantName= than it's still set, it's just empty
Best thing to do would be to check if it's set and not an empty string:
if(isset($_GET["restaurantName"]) && $_GET["restaurantName"] != "")
{
echo "you inputed something";
echo $_GET["restaurantName"];
} else {
echo "you did not input anything";
}
die("The End");
i also removed the second if, cause you can just use an else clause instead of checking twice.
Some links to read:
http://php.net/manual/en/function.isset.php
http://php.net/manual/en/function.empty.php
If this $_GET['restaurantName'] comes from a submitted (GET) form input rather than a query string in a link (which may or may not be present), it will always be set. If the user did not enter anything, it will be set to an empty string. You can check it using empty instead of isset (empty includes a check for isset).
if (!empty($_GET['restaurantName'])) {
echo "you input " . $_GET['restaurantName'];
} else {
echo "you did not input anything";
}
It may be a good idea to also check the trimmed entry in case it is something like ' ', which you can do with
if (!empty($_GET['restaurantName']) && trim($_GET['restaurantName'])) { ...
But that is starting to get more into form validation, which is another topic in itself.

PHP remember url parameter value using $_SESSION

I made a script that shows the value of "school_id" in url parameter.
http://mywebsite.com/mygrade?school_id=00000
I use $_GET['school_id'] to display the ID number.
<?php echo $_GET['school_id']; ?>
But I what I want is if the parameter "school_id" is empty, I want to display the previous data entered.
Example, the user already browse http://mywebsite.com/mygrade?school_id=00000 then he browse http://mywebsite.com/mygrade?school_id= which id has no value. It will still display 00000 which is the previous ID he used.
I used this code below but doesn't work.. :(
<?php
session_start();
$_SESSION['schoo_id'] = $_GET['school_id'];
if ($_GET['school_id'] === null || $_GET['school_id'] == ""){
echo $_SESSION['schoo_id'];
}
else{
$_GET['school_id'];
}
?>
Anyone who get my point and could help me?
I'm going to break this down line by line, please let me know in the comments if I need to explain anything further:
Self explanatory:
<?php
session_start();
There is a typo here:
$_SESSION['schoo_id'] = $_GET['school_id'];
But! Fixing it won't resolve your problem. What happens if $_GET['school_id'] is not defined/blank? Guess what, $_SESSION['school_id'] is now blank. Obviously you don't want this behavior, so you'll want to only set $_SESSION['school_id'] if $_GET['school_id'] is defined
accessing $_GET['school_id'] will throw an E_NOTICE error if it isn't defined, so you'll want to instead check its existence, rather than checking to see if it is null.
if ($_GET['school_id'] === null || $_GET['school_id'] == ""){
Oh, that typo was intended. Why misspell school though? No need! :)
echo $_SESSION['schoo_id'];
What is this doing? Nothing! No echo, nothing. Just accessing a variable and doing nothing with it.
}
else{
$_GET['school_id'];
}
?>
Here's what your code should look like, or at least I believe is what you intend:
<?php
session_start();
if (isset($_GET['school_id']) && $_GET['school_id'] !== ""){
$_SESSION['school_id'] = $_GET['school_id'];
}
// $_SESSION['school_id'] will be guaranteed to be what $_GET['school_id'] is (if set)
// or whatever it was last time it was defined
// always echo it.
echo $_SESSION['school_id'];
?>
<?php
session_start();
if ($_GET['school_id'] === null || $_GET['school_id'] == ""){
echo $_SESSION['schoo_id'];
}
else{
$_GET['school_id'];
$_SESSION['schoo_id'] = $_GET['school_id']; //here set the session
}
?>
I agree with Salman A, the simplest way:
<?php
session_start();
if (is_int($_GET['school_id'])) $_SESSION['school_id'] = $_GET['school_id'];
// further use $_SESSION['school_id'] for your needs.
?>
what you need to do here is save the GET value in SESSION only if it is set for later use so this should work
<?php
session_start();
if (!isset($_GET['school_id']) || $_GET['school_id'] === null || $_GET['school_id'] == ""){
echo $_SESSION['schoo_id'];
}
else{
$_SESSION['schoo_id'] = $_GET['school_id'];
echo $_GET['school_id'];
}
?>
You almost have it.
<?php
session_start();
if (isset($_GET['school_id']) && trim($_GET['school_id']) !== '') {
// its a fair assumption to make that 'school_id' is intended to be an integer,
// however I will not make that assumption on the OP's behalf.
$_SESSION['school_id'] = $_GET['school_id'];
}
if (isset($_SESSION['school_id']) {
echo $_SESSION['school_id'];
}
else {
echo 'have not entered a school id yet';
}
?>

Ternary Operator on form action

I am new to PHP, but what I want is for the page to self-process (contact.php) if there's an error, but go to another PHP page (contactconfirm.php) if it passes validation. Can someone tell me what's wrong with this code?
if(isset($_POST['submit'])){
if(empty($name)) {
$errors ++ ;
echo "<p>You did not enter a name.</p>";
} else {
$errors = 0;
}
if(empty($email)) {
$errors ++ ;
echo "<p>You did not enter an e-mail.</p>";
} else {
$cleanEmail = filter_var($email, FILTER_SANITIZE_EMAIL);
if (!filter_var($cleanEmail, FILTER_VALIDATE_EMAIL)){
$errors ++;
echo "<p>Invalid e-mail. Please try again.</p>";
} else {
$errors = 0;
}
}
} //closes isset
?>
<div class="contact-form">
<div class="inputArea">
<form action="<?php echo ($errors > 0) ? 'contact.php' : 'contactconfirm.php' ?>" method="post">
Every time you pass a verification stage, you reset $errors to 0.
e.g.
check if "foo" is correct: nope, increments $errors -> `1`
check if "bar" is correct: yep, reset $errors to 0
if ($errors == 0)
everything is perfect! happy joy joy!
}
but oops, "foo" was wrong, and now you've said everything was ok, because your error counter got reset. Simply remove ALL of the $errors = 0 from inside your verification/validation stages.
See Marc B's answer to point out the first initial problem.
You reset your $errors = 0 in the else of each check. You must remove these statements, otherwise if the later check statements are valid, the $errors variable will be reset.
Also, it would be much better to not print the errors during the checks, but rather to append to an error array, and check the errors variable after all of the error checking has occurred.
e.g.
if($errors>0){
print_r($errorArray);
}
or
if($errors>0){
foreach($errorArray as $error){
echo $error;
}
}
Also, it is unclear without the rest of your code, but it seems like the top half is validation after being redirected to this page, but that will never occur, because you are automatically setting the form action to contactconfirm.php in the first place, since $errors will not have a value on first page load. I may be misinterpreting your code without the full page though.
You should consider removing the turnary operator in your form, and having the action always be contact.php.
Then you can use conditional logic to check if there are no errors, and if not, redirect using header("Location: contactconfirm.php"). See this documentation on header for more info.

PHP IF Statements Error is_string

I've been studying PHP using only the internet, so I've been experiencing errors.
<?php
$name = $_POST['name'];
$lg = $_POST['lg'];
if (is_string($name) && is_numeric($lg)) {
header( "Location: portal.php?ejhbusbhdubr=nennuncuiecbdhbcvhebchebcdjebcdsjhbcebhfcvebhdchebhcvhervbhecbvecveh" ) ;
}
if (empty($name) && is_numeric($lg)) {
echo "Please enter your name.";
}
else {
header ("Location: index.php?invalid=true");
}
?>
I'm having problems with the second if statement. What I'm trying to do is that I'm trying to make an error message appear when the $name variable is left empty, and the $lg variable isn't. I think the is_string variable handler's the problem here. Perhaps a string can be empty. But as I said, since I don't have a book, I don't know what to change it too.
In case you still don't get what I mean,
Name: ""
LG: "1234"
I want the above to return as error. Help would be appreciated.
Try to write you condition like this:
if (empty($name) && !empty($lg))
Try it like this, I just moved your if over the first one, and changed it a bit. You have to test if the string is empty before testing, if it is a string. I mean is_string will return true even if the string is empty.
<?php
$name = $_POST['name'];
$lg = $_POST['lg'];
if (empty(trim($name)) && is_numeric($lg)) {
echo "Please enter your name.";
}
elseif(is_numeric($lg)) {
header( "Location: portal.php?ejhbusbhdubr=nennuncuiecbdhbcvhebchebcdjebcdsjhbcebhfcvebhdchebhcvhervbhecbvecveh" ) ;
die();
}
else {
header ("Location: index.php?invalid=true");
die();
}

php custom error message shown incorrectly

i'm working on a php assignment for log in function using .txt file instead of db, but i'm facing with some sort of problem here. supposedly the "invalid email or password" to be shown after a non exist details key in, but when the page load, the msg showed by default, below is my code
<?php
$lines= file("customers.txt");
$matchFound=false;
$errmsg = 'Invalid email or password';
for($i=0;$i<count($lines);$i++)
{
if ($i!=0)
{
$line=trim($lines[$i]);
$cells=explode("\t",$line);
$_SESSION['email'] = isset($_POST['email'])? $_POST['email'] : null;
$_SESSION['password'] = isset($_POST['password']) ? $_POST['password'] : null;
if ($_SESSION['email']==$cells[2] && $_SESSION['password']==$cells[3])
{
$matchFound=true;
break;
}
}
}
if ($matchFound == true)
{
header('Location: login2.php');
}
else
{
echo $errmsg;
}
?>
This is because you're not checking if the user submitted the form input correctly. The value of $matchFound is FALSE by default, and the error message will always be displayed when the script is ran.
Specify a name attribute for your form submit button, and then add an if block to make sure the form was correctly submitted:
if (isset( $_POST['submitButton'] )) {
# code...
}
That way, the code inside the if block won't be run if the user input wasn't received and you could avoid the error being displayed every time you load the page.
Also, you're missing the session_start() statement at the top of your script. This is required if you want the sessions to work properly.
Try:
if ($matchFound == true)
{
header('Location: login2.php');
}
else if(isset($_POST['email']))
{
echo $errmsg;
}
Also you need session_start to use $_SESSION array

Categories