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'];
}
}
Related
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';
}
The code is like:(It is the last page of the web-app I have made)
<?php
if(isset($_GET['var'])
{
session_start();
$a=$_SESSION['prev_defined'];
#more use of session variable
session_destroy();
$_SESSION = array();
unset($_GET);
unset($_POST);
}
?>
Now when i execute the web application it runs fine , when i refresh the last page whose code is given above the warning message shows of undefined symbol because the $_SESSION variables as well as $_GET and $_POST have been deleted. I want to display message "SESSION OVER" on refresh. How to do it? Where to put if condition? I have tried to put the above code in
if($_SESSION)
{
#entire code above
}
else
{
echo"SESSION OVER";
}
but it displayes message undefined variable _SESSION
<?php
if(isset($_GET['var'])
{
if(isset($_SESSION))
{
session_start();
$a=$_SESSION['prev_defined'];
#more use of session variable
session_destroy();
$_SESSION = array();
unset($_GET);
unset($_POST);
}
else
{
echo"SESSION OVER";
}
}
?>
Try this one. If session is set it will do the conditions.
EDIT
if(isset($_GET['var'])
{
....
}
else
{
echo"SESSION OVER";
}
Using this, If $_GET['var'] is not set then echo the else part
EDIT 2
<?php
if (isset($_GET) || isset($_SESSION)) {
//Put all your codes here
} else {
echo "Session Over";
}
$_SESSION is a global variable, an array. And it will be allways around.
check if session feature is active like so:
if (session_status() == PHP_SESSION_NONE) {
session_destroy();
echo "session over";
}
Also note to check if arrays key isset, before checking it's value, to avoid notices:
if(isset($_SESSION['login'])&&$_SESSION['login']==1){//pass}
EDIT:
as stated here: For versions of PHP < 5.4.0
if(session_id() == '') {
session_start();
}
I have page called account_settings.php and it's consist of change password, change profile pic, change user details (name, bio etc.). My question is how to write message with echo() after redirecting page with header().
Something like this:
if (true)
{
Do_Some_MySQL();
header("Location: account_settings.php");
echo "Success!";
}
else
{
echo "Error!";
}
Thank you for all replies. ;-)
You can't actually do something after sending a Location header - it is impossible.
Instead, you could use $_SESSION array value to perform your task. Like:
if (true)
{
Do_Some_MySQL();
$_SESSION['message'] = 'Error!';
header("Location: account_settings.php");
}
else
{
echo "Error!";
}
And then on your account_setting.php:
<?php echo $_SESSION['message'] ?>
This would be nice if the account_settings.php is not the same page as you currently are. Otherwise, you could use the following code:
if (true)
{
Do_Some_MySQL();
$error = 'Success!';
header("Location: account_settings.php");
}
else
{
$error = "Error!";
}
And on the same page:
<?php if($error) echo $error; ?>
Also don't forget to include session_start() on both pages if you didn't it yet.
I would use a SESSION variable:
on redirect-page:
<?php
#session_start();
if(true){
$_SESSION['success'] = 1;
header("Location: account-settings.php");
}
?>
and on account-settings.php:
<?php
#session_start();
if(isset($_SESSION['success'])){
echo "Success!";
unset($_SESSION['success']);
}
You cannot echo anything after you just redirected. The browser is already processing the request to redirect to another page, so it doesn't bother about displaying the message anymore. What you seem to be looking for is something called flash message. You can set a temporary message in the session and have it display on the new page. For example, in your account_settings.php page:
// Make sure you have an actual session
if (!session_id()) {
session_start();
}
if (true) {
Do_Some_MySQL();
$_SESSION['flashMessage'] = 'Success!';
header('Location: account_settings.php');
}
Then in your template file for account_settings, check if there is any flash message and display it accordingly (and unset it to avoid a loop):
if (isset($_SESSION['flashMessage'])) {
echo $_SESSION['flashMessage'];
unset($_SESSION['flashMessage']);
}
These people are correct...you can't send headers after a redirect. Although I think this would be a beneficial alternative. To send a GET request in your header and process it on the receiving page. They are suggesting to use $_SESSION vars, but you can use GET vars. Ex:
if (true)
{
//Do_Some_MySQL();
header("Location: account_settings.php?message=success");
//above has GET var message = Success
}
else
{
header("Location: account_settings.php?message=error");
}
On your account_settings.php page have this code:
if (isset($_GET['message'])) {
$message = $_GET['message'];
if ($message == "success") {
echo "Success";
} else {
echo "Error";
}
}
This removes the need of CONSTANT SESSION vars. and gives you plenty of flexibility.
header("Location: account_settings.php?message=No%20results%20found");
//%20 are URL spaces. I don't know if these are necessary.
If you need you can add more then one.
header("Location: account_settings.php?message=error&reason=No%20Results×tamp=" . Date());
then account_settings.php can be:
if (isset($_GET['message'])) {
$message = $_GET['message'];
$reason = $_GET['reason'];
$time = $_GET['timestamp'];
if ($message == "success") {
echo "Success";
} else {
echo "Error: <br/>";
echo "Reason: $reason";
}
}
But remember GET exposes your messages in the browsers URL. So DON'T send sensitive information unless you secure it. Hope this helps.
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
When checking that variables passed via GET and POST are correct, I might have something like this:
<?php
//Controller
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(!isset($_POST['new_email']))
header('Location: somepage.php');
else if(empty($_POST['new_email']))
//Report error to user and prompt to try again
else
$newEmail = $_POST['new_email'];
if(!isset($_POST['full_name']))
header('Location: somepage.php');
else if(empty($_POST['full_name']))
//Report error to user and prompt to try again
else
$newName = $_POST['full_name'];
if(!isset($_POST['new_password_a']))
header('Location: somepage.php');
else if(empty($_POST['new_password_a']))
//Report error to user and prompt to try again
else
$newPasswordA = $_POST['new_password_a'];
if(!isset($_POST['new_password_b']))
header('Location: somepage.php');
else if(empty($_POST['new_password_b']))
//Report error to user and prompt to try again
else
$newPasswordB = $_POST['new_password_b'];
//Do some things with the variables
}
else
{
header('Location: somepage.php');
}
//View
//Display relevant view here
?>
How would you check GET and POST variables in your PHP script? I wonder if there is a better way?
Maybe creating a function to avoid the repeated code?
function check($varname,$destination,$message) {
if (!isset($_POST[$varname])) {
header("Location: $destination");
} else if (empty($_POST[$varname])) {
//Do something with $message
} else {
return $_POST[$varname];
}
return NULL;
}
And then,
<?php
//Controller
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$newEmail = check('new_email','somepage.php','Error message');
$newName = check('new_name','somepage.php','Error message');
$newPasswordA = check('new_password_a','somepage.php','Error message');
$newPasswordB = check('new_password_b','somepage.php','Error message');
//Do some things with the variables
//Checking for NULL values (although if some var was null,
//it should have either redirected or reported an error)
}
else
{
header('Location: somepage.php');
}
//View
//Display relevant view here
?>
What The Pixel Developer says is true though, you should sanitize the inputs at least against SQL injection (if you will use the data in a database) and CSRF attacks.
<?php
//Controller
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
foreach ($_POST as $key => $value) {
if (empty($value)) {
echo 'whoops, remember to set ', $key;
} else {
switch($key) {
case 'new_password_a':
$newPasswordA = $value;
break;
//etc
}
}
}
if (isset($newPasswordA) && isset($newPasswordB)) { //check all vars have been set or whatever
header('Location: somepage.php');
} else {
header('Location: somepage.php');
}
Sorry I couldn't be more specific with the code, your sample code was kinda vague. I hope that helps.
Your code is a wild mess for a start. Please use brackets, better code comments and classes / functions.
You're not checking for anything correct other than if the key has a value. You might want to add a CSRF token to make sure the request has come from the form you are expecting.
Look at CSRF on Wikipedia.