I'm new to php and I'm following a tutorial to make a login panel. It works fine on the demo website but when I download the code and run on my machine, 5 notices popped up. They all look like: "Notice: Undefined index: submit in C:\xampp\htdocs\myfolder\demo.php on line 24".
From other programming experiences I think that these means I didn't define the variables before using them. However, these variables seem to be existing in the system (from what I understand reading other questions >-<).
I attached my code below and marked the undefined index on the right. Can anyone help me explain what's wrong with the code and how can I solve it? Thanks a lot!
<?php
session_name('Login');
session_start();
if($_POST['submit']=='Login') //undefined submit
{
$err = array();
if(!$_POST['username'] || !$_POST['password'])
$err[] = 'All the fields must be filled in!';
if(!count($err))
{
$_POST['username'] = mysql_real_escape_string($_POST['username']);
$_POST['password'] = mysql_real_escape_string($_POST['password']);
// Escaping all input data
$row = mysql_fetch_assoc(mysql_query("SELECT id,user FROM writers WHERE user='{$_POST['username']}' AND pass='".md5($_POST['password'])."'"));
if($row['user'])
{
$_SESSION['user']=$row['user'];
$_SESSION['id'] = $row['id'];
// Store some data in the session
}
else $err[]='Wrong username and/or password!';
}
if($err)
$_SESSION['msg']['login-err'] = implode('<br />',$err);
// Save the error messages in the session
header("Location: demo.php");
exit;
}
$script = '';
if($_SESSION['msg'])
{
// The script below shows the sliding panel on page load
...
}
?>
<head>
......
</head>
<body>
<!-- Panel -->
<div id="toppanel">
<div id="panel">
<div class="content clearfix">
<?php
if(!$_SESSION['id']): //undefined id
?>
<div class="left">
<form class="clearfix" action="" method="post">
<h1>Writer Login</h1>
<?php
if($_SESSION['msg']['login-err']) //undefined login-err
{
echo '<div class="err">'.$_SESSION['msg']['login-err'].'</div>';
unset($_SESSION['msg']['login-err']);
}
?>
//Login form
</form>
</div>
<?php
endif;
?>
</div>
</div> <!-- /login -->
<!-- The tab on top -->
<div class="tab">
<ul class="login">
<li class="left"> </li>
<li>Hello <?php echo $_SESSION['user'] ? $_SESSION['user'] : 'Guest';?>!</li> //undefined user
<li class="sep">|</li>
<li id="toggle">
<a id="open" class="open" href="#"><?php echo $_SESSION['id']?'Open Panel':'Log In';?></a> //undefined id
<a id="close" style="display: none;" class="close" href="#">Close Panel</a>
</li>
<li class="right"> </li>
</ul>
</div> <!-- / top -->
</div> <!--panel -->
Sorry for the long code! I really not sure which ones will be relevant to the problem and do not dare to delete more. Thank you for your patience!
You need to check if that variable exists before you use it. You would use isset() for that:
if(isset($_POST['submit']) && $_POST['submit']=='Login')
If you're just checking to see if the form was submitted you could just check to see if the page was request via POST instead:
if('POST' === $_SERVER['REQUEST_METHOD'])
You can also put # in front of your array references that can be null, for example:
if(#$_POST['submit']=='Login')
This will supress the warning
Related
I want to make the logout li to be shown only if user is logged in. Menubar is under the leftsidebar.php file. The file is required by the index.php and the con_login.php does the verification.
I'm new to php so i'm not sure about how to do that. I tried some lines of code i find online but doesn't work
leftsidebar.php
<nav id="leftsidebar">
<ul class="menu">
<li>Home Page</li>
<li>Δημόσια Σελίδα</li>
<li>Σελίδα Χρήστη</li>
<li>Logout</li>
</ul>
</nav>
index.php
<?php session_start(); ?>
<?php
$title="Super eShop - Home Page";
require('part_header.php');
require('part_leftsidebar.php');
?>
<main id="main">
<h2>Home Page</h2>
<?php echo_msg(); ?>
<?php if(!isset($_SESSION['username'])) { ?>
<p>Please login:</p>
<form name="form1" method="post" action="con_login.php">
<p>username: <input type="text" name="username"/> </p>
<p>password: <input type="password" name="password"/> </p>
<p><input name="submit" type="submit"></p>
</form>
<?php } else echo '<p> Hello ' .$_SESSION['username'].'</p>';?>
</main>
<?php require('part_footer.php'); ?>
con_login.php
<?php
if (!isset($_SESSION['username']) && isset($_POST['username']) && isset($_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
$authorised=false;
if ($username=='test'){
$authorised=true;
session_start();
$_SESSION['username']=$username;
}
if ($authorised==true){
header("Location: page_user.php");
exit();}
else{
header("Location: index.php?msg=Αποτυχημένη διαπίστευση χρήστη!");
exit();}
}
else{
session_start();
session_destroy();
header("Location: index.php?msg=Πρόβλημα σύνδεσης. Ξαναδοκιμάστε!");
exit();
}
?>
I'm not quite sure if I get your question, but if $authorised says whether you're logged in or not, you could write s.th. like the following in your HTML / PHP file.
<nav id="leftsidebar">
<ul class="menu">
<li>Home Page</li>
<li>Δημόσια Σελίδα</li>
<li>Σελίδα Χρήστη</li>
<?php echo ($authorised ? '<li>Logout</li>' : ''); ?>
</ul>
</nav>
But this would require, that you set $authorised every time you call the page, alternatively, you could do it with a $_SESSION
If your code works as is, then you just need to set this in your sidebar
<?php if(isset($_SESSION['username'])) { ?>
<li>Logout</li>
<?php } ?>
Hey there stackoverflow users, i have come upon a very confusing problem that I cant seem to move past. I am creating a forum type web page and am currently working on the comments section. I have a form that uses the post method to send your comment as well as a hidden input to store the threads ID. I will post the entire php file below just to make sure nothing is left out.
<?php
session_start();
parse_str($_SERVER['QUERY_STRING'], $link);
$threadID = $link['ID'];
require("config.php");
$connection = mysqli_connect($host, $user, $password, $database);
$error = mysqli_connect_error();
if($error != null) {
$output = "<p>Unable to connect to database!</p>";
exit($output);
} else {
//Get Thread Data
$query = "SELECT username, title, content FROM threads, users WHERE threads.ID = $threadID AND users.ID = threads.makerID;";
$results = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($results);
//Get Comment Data
$query = "SELECT username, comment FROM comments, users WHERE threadID = $threadID AND users.ID = comments.makerID;";
$results = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($results);
}
?>
<!DOCTYPE html>
<html>
<head lang="en">
<title>BodyweightMate</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../css/styling.css"/>
</head>
<body>
<!--Top masthead-->
<header class="masthead" id="top">
<h1 class="masthead-title"> Welcome To BodyweightMate </h1>
</header>
<!--Navigation bar-->
<nav class="navbar">
<table class="navbar-table">
<tr>
<!--Logo-->
<td>
<a class="navbar-brand" href="main.php">
<img src="../images/logo.jpg" alt="BodyweightMate" height="30" width="30">
</a>
</td>
<!--Login/Profile-->
<?php if(isset($_SESSION['login_user'])) {
echo"<td><a class=\"navbar-profile\" href=\"profile.php\"> Profile </a></td>";
echo"<td><a class=\"navbar-logout\" href=\"logout.php\"> Logout </a></td>";
} else {
echo"<td><a class=\"navbar-login\" href=\"login.php\"> Login </a></td>";
}?>
</tr>
</table>
</nav>
<!--Main portion-->
<section class="content-section">
<article>
<h3><?php echo $row['username']. ": " .$row['title']; ?></h3>
<p><?php echo $row['content']; ?></p>
<br>
<h3>Comments</h3>
<p>Some annoying user: Gr8 B8 M8</p>
<p>Annoying users friend: I R8 8/8</p>
</article>
<div>
<!--If logged in, ability to comment-->
<?php if(isset($_SESSION['login_user'])): ?>
<form role="comment-form" method="POST" action="processcomment.php" id="mainForm">
<input type="hidden" value="$threadID" name="threadID">
<div class="form-group">
<label for="comment">Comment </label> <br>
<textarea class="comment-text" name="comment" rows="2" maxlength="255"></textarea>
</div> <br>
<input type="Submit" class="btn-newcomment" value="Submit Comment" name="submit">
</form>
<?php endif ?>
</div>
</section>
<!--Right portion-->
<aside class="content-aside">
<div>
<!--If logged in, be able to create a thread-->
<?php
if(isset($_SESSION['login_user'])) {
echo"<form method=\"post\" action=\"makethread.php\">";
echo"<input type=\"submit\" class=\"btn-newthread\" value=\"Create New Thread\" name=\"submit\">";
echo"</form>";
}
?>
</div>
<!--Info-->
<div>
<p> GOING TO NEED A SEARCH FUNCTION HERE
This is the cool little aside section. It will always be there to provide you with some very nice little details, helpful links, maybe a list of moderators? who knows! The uses are endless when you have a beautiful little aside like this one! Here are a few very useful bodyweight fitness links to get us started :D </p>
</div>
<br>
<div>
<ul class="content-aside-links">
<li>
Reddit's Bodyweightfitness Forum
</li>
<li>
Reddit's Bodyweightfitness RR
</li>
<li>
Antranik's Bodyweightfitness Routine
</li>
</ul>
</div>
<div></div>
</aside>
<!--Footer -->
<footer class="footer">
<div>
<p> Use of this site constitutes acceptance of our User Agreement © 2017 BodyweightMate inc. All rights reserved. </p>
</div>
</footer>
</body>
</html>
The error is occurring under the main portion where i check if a user is logged in, and if they are add a short form consisting of a message, a text area, and a submit button. This form sends the information to the following php file.
<?php
session_start();
if(!isset($_SESSION['login_user'])) { header("location: main.php"); }
?>
<!DOCTYPE html>
<html>
<body>
<?php
require("config.php");
$connection = mysqli_connect($host, $user, $password, $database);
$error = mysqli_connect_error();
if($error != null) {
$output = "<p>Unable to connect to database!</p>";
exit($output);
} else {
//Validation
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$comment = $_POST['comment'];
$threadID = $_POST['threadID'];
$user = $_SESSION['login_user'];
} else {
//Redirect back to register
echo"<p>Form must use post or input was bypassed.</p>";
echo" Return to home page. ";
mysqli_close($connection);
exit();
}
There is no issue with connecting to the database, and I don't believe the remainder of the code is necessary to help me with this error since that one if statement of checking if the form is using post is failing and the else statement is always called. Why is this? i have rewritten the form multiple times ensuring that its properly structured and using post yet it fails every time!
I am trying to create a log in form which allows user to log in, based on their registration details (which is saved in a flat file) and this what I have come up with so far.
At the moment the this code allow any user to log in even when there are not on the registration.
<html>
<body>
<table align="center">
<tr>
<th><h3>MY ACCOUNT</h3></th>
</tr>
<form action = "index.php" method = "POST">
<tr>
<td>Username:</br><input type="text" name="username"></br></td>
</tr>
<tr>
<td>Password:</br><input type="password" name="password"></br></td>
</tr>
<tr>
<td align = "center"><input type="submit" name = "submit"></td>
</tr>
</form>
</table>
<?php
if (isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
$file = file_get_contents("data.txt");
if(empty($_POST['username']) || empty($_POST['password'])){
die (print '<script> alert ("You must enter both your username and password to continue."); window.location="index.php"; </script>');
}
if(!strstr($file, "$username#$password")) {
die(print '<script> alert ("Wrong"); window.location="index.php"; </script>');
}
else {
header("Location: wacc.php");
}
}
?>
Please what is wrong with code
In your other post here you were given a suggestion to use a script called PHP Login. This would help solve a lot of your problems if you follow this suggestion.
I suggest you change the strstr to the strpos function, it's the desired function for checking if a string occurs, and works ok.
So:
if(!strstr($file, "$username#$password")) {
To:
if(strpos($file, "$username#$password") === false) {
Note the === , it needs to be false, not 0 or ''. See for more info http://www.php.net/function.strpos
Edit
The logging in always is most of the time true, because whats happening is that your searching for if the specified string is occurring in your text document. Now, incase that if you leave both fields $username and $password empty, it will be true ( is there a # in the text document? Yes. ) This also applies when you write a valid part username or password.
I would suggest you rethink this login system, and use a PHP array or database to match a valid username and password. If you just want a simple bump for visitors, try adding an delimiter.
In your username and password list for example:
#username#password#
And as strpos function
if(strpos($file, "#$username#$password#") === false) {
With adding the # before and after, your script always nows where the username must start and must end, and the same for the password. If the username was too short, too long, or empty the # gets added anyway and will the strpos will then be wrong (is there an ### in the list? No.).
you could use facebook login instead.
I dont think a flat file login could ever be totally secure. /shrug.
Facebook is really easy though and is a multi-billion dollar corporation that pays programmers to make it as secure as possible. No need to worry about security at all.
<?php
require 'fbconfig.php'; // Include fbconfig.php file
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>Login with Facebook</title>
<link href="http://www.bootstrapcdn.com/twitter-bootstrap/2.2.2/css/bootstrap-combined.min.css" rel="stylesheet">
</head>
<body>
<?php if ($user): ?> <!-- After user login -->
<div class="container">
<div class="hero-unit">
<h1>Hello <?php echo $fbuname; ?></h1>
<p>Welcome to "facebook login" tutorial</p>
</div>
<div class="span4">
<ul class="nav nav-list">
<li class="nav-header">Image</li>
<li><img src="https://graph.facebook.com/<?php echo $user; ?>/picture"></li>
<li class="nav-header">Facebook ID</li>
<li><?php echo $fbid; ?></li>
<li class="nav-header">Facebook Username</li>
<li><?php echo $fbuname; ?></li>
<li class="nav-header">Facebook fullname</li>
<li><?php echo $fbfullname; ?></li>
<div>Logout</div>
</ul></div></div>
<?php else: ?> <!-- Before login -->
<div class="container">
<h1>Login with Facebook</h1>
Not Connected
<div>
Login with Facebook</div>
</div>
<?php endif ?>
</body>
</html>
I have a login page which records the username that the user enters and adds it to a variable of $uname. However when the page after the login page loads, I cannot echo the $uname. For example, when i type
Welcome <?php echo $uname; ?>
it does not insert the username.
below is a copy of my login-validation code. but I am not sure if the $_SESSION variable is working correctly, or how to reference it in my profile.php file.
<?php
session_start();
$_SESSION['uname'] = $uname;
// Grab User submitted information
$uname = $_POST["uname"];
$pass = $_POST["pass"];
// Connect to the database
$con = mysql_connect("mysql.*********.co.uk","******","************");
// Make sure we connected succesfully
if(! $con)
{
die('Connection Failed'.mysql_error());
}
// Select the database to use
mysql_select_db("onedirectionaffection_members",$con);
$result = mysql_query("SELECT uname, pass FROM users WHERE uname = $uname");
$row = mysql_fetch_array($result);
if($row["uname"]==$uname && $row["pass"]==$pass)
header("Location: ../../profile/profile.php");
else
echo"Sorry, your credentials are not valid, Please try again.";
?>
If anyone could help I would be hugely thankful. Also, I am an absolute beginner at all of this so if you need anymore details I'll try my best to answer.
profile.php
<?php
session_start();
echo $_SESSION['uname'];
?>
<html>
<head>
<title>1D Affection</title>
<link rel="stylesheet" Type="text/css" href="../css/stylesheet.css" />
<link rel="stylesheet" Type="text/css" href="../css/font.css" />
<link rel="stylesheet" Type="text/css" href="../css/profile.css" />
</head>
<body bgcolor="white">
<div id="wrapperhead">
<div id="headcont">
<div class="logo">
<img src="../images/1DA logo ripped.png" height="150px">
</div>
<div class="subheading">
<img src="../images/1d subheading.png" height="150px">
</div>
</div>
</div> <!--END OF HEADER-->
<div id="nav">
<div class="navigation">
<ul>
<li><a class="nav" href="../index.html">Home</a></li>
<li><a class="nav" href="#">News</a></li>
<li><a class="nav" href="#">Fan-fiction</a></li>
<li><a class="nav" href="#">Gallery</a></li>
<li><a class="nav" href="#">Testimonials</a></li>
<li><a class="nav" href="http://www.onedirectionstore.com/" target="_blank">Store</a></li>
</ul>
</div> <!-- END OF MENU-->
<!-- END OF NAVIGATION-->
</div>
<div id="wrappercontent">
<div class="content">
<div class="maincont">
<div class="profcust">
<div class="profpic">
</div>
<div class="profinfo">
</div>
</div>
<div class="username">
Welcome <?php session_start(); echo $uname; ?>
</div>
<div class="story">
</div>
</div>
<div class="sidenav">
Coming Soon
</div>
</div><!--end of content-->
</div>
</body>
</html>
Seems like you haven't added session_start(); on top of your profile.php page.
Try like this
//profile.php
<?php
session_start();
echo $_SESSION['uname'];
This is probably a good part of the issue.
$_SESSION['uname'] = $uname;
$uname = $_POST["uname"];
Your setting your session's uname to blank on every load of that page. Put $_SESSION['uname'] = $uname; at the end of the code when it's validated.
1) You need to add a value to $uname first, then assign its value to $_SESSION element, so it's better be like this:
$uname = $_POST['uname'];
$_SESSION['uname'] = $uname;
or even like this:
$_SESSION['uname'] = $_POST['uname'];
2) As already mentioned, At profile.php you should also have session_start();
3) Make a clean exit like this:
header("Location: ../../profile/profile.php");
exit();
My bet is that it should be working fine after.
Some how, this is now working. From what I can figure out, the solution was to call in the $_SESSION variable, and then wrap that inside another variable. so
<?php
session_start();
$uname = $_SESSION['uname'];
?>
Thanks for all the help :D
session_start(); needs to be inside all pages using sessions.
I tested the following:
<?php
session_start(); // page_2.php
echo "Welcome " . $_SESSION['uname'];
?>
In conjunction with my test page: page_a.php
<?php
session_start();
$uname = "FRED";
$_SESSION['uname'] = $uname;
?>
CLICK
Echo'ed Welcome FRED on page 2.
I also noticed you have another instance of session_start(); in your page profile.php, remove it because you will be starting a new session while overwriting your first.
<div class="username">
Welcome <?php session_start(); echo $uname; ?>
</div>
Therefore you should be using:
$uname = $_SESSION['uname'];
in conjunction with:
<div class="username">
<?php echo "Welcome " . $_SESSION['uname']; ?>
</div>
As berkes stated in this comment you have a security issue:
$uname = $_POST["uname"];
$pass = $_POST["pass"];
Change it to:
$uname = mysql_real_escape_string($_POST['uname']);
$pass = mysql_real_escape_string($_POST['pass']);
MySQL_ functions are deprecated, therefore using MySQLi_ with prepared statements is highly suggested or PDO.
Do read the following articles:
How can I prevent SQL injection in PHP?
On owasp.org
I'm currently learning PHP and am creating a small CMS feature that includes a login area. I have used the code below which includes an include header file that contains the doctype/head info and the opening tag. It also includes the header content. I also have a connection file for connecting to the db.
My header include code is:
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title><?php echo $pagetitle ?></title>
<link rel="stylesheet" href="../stylesheets/foundation.css">
<link rel="stylesheet" href="../stylesheets/app.css">
<style>#import url(http://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700,800); #import url (http://fonts.googleapis.com/css?family=Kreon:100,200,300,400);</style>
<script src="../javascripts/modernizr.foundation.js"></script>
</head>
<body>
<div class="subHeader">
<div class="row">
<div class="four columns logo">
<img src="../images/logo.png" alt="logo" />
</div>
<div class="eight columns navigation right">
<ul class="navigationMain">
<li class="<?php if($navcurrent == "home"){echo "navigationActive";} ?>">Home</li>
<li class="<?php if($navcurrent == "services"){echo "navigationActive";} ?>">Services</li>
<li class="<?php if($navcurrent == "work"){echo "navigationActive";} ?>">Recent Work</li>
<li class="<?php if($navcurrent == "about"){echo "navigationActive";} ?>">About</li>
<li class="<?php if($navcurrent == "contact"){echo "navigationActive";} ?>">Contact</li>
</ul>
</div>
<div class="twelve columns titlesection">
<h2><?php echo $headTitle ?></h2>
<h4><?php echo $headsubTitle ?></h4>
</div>
</div><!--End Feature Row-->
</div><!--End Feature-->
<div class="underbar">
<div class="bordertriangle"></div>
<div class="row">
<div class="eight columns"> </div>
<div class="three columns right socialcontainer">
<ul class="socialicons">
<li><a><img id="linkedinIcon" src="../images/socialli.png" alt="linkedin icon" /></a></li>
<li><a><img id="twitterIcon" src="../images/socialtw.png" alt="twitter icon" /></a></li>
<li><a><img id="facebookIcon" src="../images/socialfb.png" alt="facebook icon" /></a></li>
</ul>
</div>
</div>
When I open the admin page, the username password form, header and footer appear as they should. If I test the errors, they return as they should. However, when I successfully log in using a valid username and password, no content appears except the what is included in the header file. Can anyone point me in the direction of what i might be doing wrong? Any help would be much appreciated. I am a relative noob to PHP...
<?php
$pagetitle = "Admin";
$navcurrent = "home";
$headTitle = "ADMIN AREA";
$headsubTitle = "SITE ADMINISTRATION AREA";
include_once('../includes/connection.php');
include_once('../includes/headeradmin.php');
if (isset($_SESSION['logged_in'])) {
echo('Successfully Logged In');
} else {
if (isset($_POST['username'], $_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) or empty($password)){
$error = 'An Error Has Occurred - All Fields Are Required';
}
else{
$query = $pdo->prepare('SELECT * FROM users WHERE user_name = ? AND user_password = ?');
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->execute();
$num = $query->rowCount();
if ($num == 1) {
$_SESSION['logged_in'] = true;
header('location: index.php');
exit();
}
else{
$error = 'The username/password you entered was incorrect - Please try again';
}
}
}
?>
<div class="row">
<div class="four columns centered">
<?php if (isset($error)) { ?>
<h5 style="color: #e63333;"><?php echo $error; ?></h5>
<br />
<br />
<?php } ?>
<form action="index.php" method="post">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Login" />
</form>
</div>
</div>
You can't use the header('location: index.php'); line if you've already output content (i.e - html code) to the browser when you included the header in this line include_once('../includes/headeradmin.php');
read the documentation of header - Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP
you need to redirect the user with the header() function before you output the head html of the admin page