Check if variable is set in PHP - 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.

Related

session is works locally but not online [duplicate]

I'm new to PHP and am even more of a beginner when it comes to sessions. I have my index.php page, which is where users can register and login. The forms are posting to validate.php and loginvalidate.php pages, respectively for registering and logging in.
I have these errors on index.php when I load it:
1) Notice: Undefined index: registered
2) Notice: Undefined index: neverused
I have tried modifying my text in many ways but I never got to solve the errors.
Index.php
<?php
if ($_SESSION['registered'] != NULL){
echo $_SESSION['registered'];
}
if ($_SESSION['badlogin'] != NULL){
echo $_SESSION['badlogin'];
}
if ($_SESSION['neverused'] != NULL) {
echo $_SESSION['neverused'];
}
?>
Validate.php (after submitting register form)
if (mysqli_num_rows($result) > 0) { //IF THERE IS A PASSWORD FOR THAT EMAIL IN DATABASE
$_SESSION['registered'] = "Email is already registered.";
mysqli_close($db_handle);
header('Location: index.php');
exit();
}
Loginvalidate.php (after submitting login form)
if ($numrows!=0) //IF THERE IS A PASSWORD FOR THAT EMAIL IN THE DATABASE
{
if ($row['password'] == $password) { //IF THE PASSWORD MATCHES USER INPUT
header('Location: homepage.php');
echo "lol";
exit();
}
else{
$_SESSION['badlogin'] = "Email/password combination not valid.";
mysqli_close($db_handle);
header('Location: index.php');
exit();
}
}
else { //THERE IS NO PASSWORD FOR THAT EMAIL, SO THAT EMAIL IS NOT REGISTERED
$_SESSION['neverused'] = "Email is not registered.";
mysqli_close($db_handle);
header('Location: index.php');
exit();
}
Okay so my script does what it is intended to do. The only thing that I can't solve is these session errors. Do you see any misuse of sessions? Of course, I have started the sessions in all of my .php files.
Also, note that I am aware that there is no protection from hackers. This is only for a future prototype that won't contain any important data.
The reason for these errors is that you're trying to read an array key that doesn't exist. The isset() function is there so you can test for this. Something like the following for each element will work a treat; there's no need for null checks as you never assign null to an element:
// check that the 'registered' key exists
if (isset($_SESSION['registered'])) {
// it does; output the message
echo $_SESSION['registered'];
// remove the key so we don't keep outputting the message
unset($_SESSION['registered']);
}
You could also use it in a loop:
$keys = array('registered', 'badlogin', 'neverused');
//iterate over the keys to test
foreach($keys as $key) {
// test if $key exists in the $_SESSION global array
if (isset($_SESSION[$key])) {
// it does; output the value
echo $_SESSION[$key];
// remove the key so we don't keep outputting the message
unset($_SESSION[$key]);
}
}
If you're getting undefined index errors, you might try making sure that your indexes are set before you try comparing the values. See the documentation for the isset function here:
http://php.net/manual/en/function.isset.php
if (isset($_SESSION['registered']))
if ($_SESSION['registered'] != NULL){
echo $_SESSION['registered'];
}
}
if (isset($_SESSION['badlogin']))
if ($_SESSION['badlogin'] != NULL){
echo $_SESSION['badlogin'];
}
}
if (isset($_SESSION['neverused']))
if ($_SESSION['neverused'] != NULL) {
echo $_SESSION['neverused'];
}
}

Why my cookies are not saving?

I have a problem with cookies. In my login script i have the following line of code:
if($_GET['keep'] == "true"){
setcookie('id',$id,time()+3153600);
}
The problem I'm facing is that the cookies are not saving at all ( not even if i don't quit the browser). I'm quite a beginer in this respect and I think I'm not doing it right.
EDIT:
If i print_r all the Cookies it only gives me PHPSESSID after the cookie is set. I printed on index.php and i set the cookie on login.php
SOLUTION: Cookies are saved by default with the path of the file they were created in. To change the path there is another atribute. So by setcookie('id',$id,time()+3153600,'/'); you make the cookie available for the entire domain.
There is no issue in your code
if($_GET['keep'] = "true"){
setcookie('id',$id,time()+3153600);
}
This will may cause to
No data passing to $_GET['keep']
Or if data passing $_GET['keep'] value in not Matched ("true").
Both Works then $id is empty in setcookie method
Improve your code
if(isset($_GET['keep']){
if($_GET['keep'] == "true"){
if(isset($id))
{
#all perpect
$cokkie_id = 'id';
setcookie('id',$id,time()+3153600);
echo "I'm Set. And My value is ".$cokkie_id;
}
else
{
echo "Opzz My ID is also empty";
}
}
else
{
echo 'Get method is Set. But Value is not "true". Actual value is '. $_GET['keep'];
}
}
else
{
echo 'I cant reach Get method Buddy';
}
I think you miss "=" sign
if ($_GET['keep'] == "true") {
if (!isset($_COOKIE['id'])) {
setcookie('id',$id,time()+3153600);
}
}
use isset or ==
if (isset($_GET['keep']) && $_GET['keep'] == "true") {
setcookie('id', $id,time()+3153600);
}else{
echo 'keep is empty';
}

PHP Harmful URL protection

I've made this script, but the 4th line isn't right and I have really no clue how to solve this. I really appriciate if someone helps me. This is my code:
<?php
$url = $_GET["url"];
$badsite = array("http://check.com", "http://hotmail.com");
if($url == $badsite) {
echo "This URL is harmful.";
} else {
echo "Not harmful";
header("Location: " . $_GET["url"]);
}
?>
So the thing which doesn't work is the following line
if($url == $badsite) {
How can I make it so it checks if the GET contains a $badsite?
You don't want to check if the value equals the array, you want to check if it's in the array. Perhaps something like this:
if (in_array($url, $badsite)) {
// ...
}
Side note, you don't need (or want, really) this echo statement:
echo "Not harmful";
header("Location: " . $_GET["url"]);
You might get an error by emitting output before sending a header. But even if you buffer output or in some other way suppress that error, there's no reason to emit output when returning a redirect response. The browser would display it for only an instant, if at all. A redirect by itself is a complete HTTP response, no output is required.
In this case you can use the function in_array:
http://php.net/manual/en/function.in-array.php
<?php
$url = $_GET["url"];
$badsite = array("http://check.com", "http://hotmail.com");
if(in_array($url, $basite)) {
echo "This URL is harmful.";
} else {
echo "Not harmful";
header("Location: " . $_GET["url"]);
}
?>

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.

Verify form field with isset()

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

Categories