Creating some kind of validation rule - php

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>

Related

Unknown issue with $_SERVER["REQUEST_METHOD"] returning false when it should be true

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!

PHP variables not declaring?

I found a tutorial for a mysqli and php login page to add to a website, i followed that tutorial step by step, spent at least 7 hours trying to figure out why it won't work, searching Google endlessly but nothing.
The code seems to be working but it seems two variables won't declare and it's skipping over them, I'll enter an email and password, hit log in, then ill get the notification 'Email or password are incorrect' the database is setup correctly and linked it just seems like it's one line of code and i can't figure it out.
Any input is welcome even if it's something basic, i am only learning this stuff hence the tutorial i was following, just want to know what is wrong and why.
Thanks.
Html Code
<!DOCTYPE html><?php session_start();?>
<html>
<head>
<title>Sign In</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="css/style.css"/>
</head>
<body>
<div id="container">
<header>
<img src="images/Header.jpg" alt="logo" />
</header>
<header>
<img src="images/login.jpg" alt="login" />
<img src="images/Facebook.jpg" alt="FB" />
<img src="images/Twitter.jpg" alt="Twitter" />
</header>
<div class="menu">
<div align="center">
<ul class="list">
<li class="item">Home
<li class="item">Gallery
<li class="item">Videos
<li class="item">Discography
<li class="item">Register
<li class="item">About
<ul class="list">
<li>Alex Turner</li>
<li class="list">
Matt Helders
<ul class="list">
Jamie Cook
<ul class="list">
Nick O'Malley
<ul class="list">
Andy Nicholson
<ul class="list">
</ul>
</li>
</div>
</div>
<div align="center"><BR><BR><BR><BR>
<body id="body-color">
<div id="Sign-In">
</head>
<form action="login.php" method="post">
<table width="500" align="center">
<tr align="center">
<td colspan="3"><h2>User Login</h2></td>
</tr>
<tr>
<td align="right"><b>Email</b></td>
<td><input type="text" name="email" required="required"/></td>
</tr>
<tr>
<td align="right"><b>Password:</b></td>
<td><input type="password" name="pass" required="required"></td>
</tr>
<tr align="center">
<td colspan="3">
<input type="submit" name="login" value="Login"/>
</td>
</tr>
</table>
</form>
<br><br>
<br><br>
<H3>If you do not have an account please register HERE<br>otherwise access is restricted to member pages<h3>
</div>
</body>
</html>
Here's the php code
<!DOCTYPE html><?php session_start();?>
//Forgot this line when first posting //
<?php
// establishing the MySQLi connection
$con = mysqli_connect("localhost","root","","info");
if (mysqli_connect_errno())
{
echo "MySQLi Connection was not established: " . mysqli_connect_error();
}
// checking the user
if(isset($_POST['login'])){
$email = mysqli_real_escape_string($con,$_POST['email']);
$pass = mysqli_real_escape_string($con,$_POST['pass']);
$sel_user = ("select * from users where user_email='$email' AND user_pass='$pass'");
//This is where i think my problem is, $email and $pass are highlighted grey
instead of how normally declared variables would look. //
$run_user = mysqli_query($con, $sel_user);
$check_user = mysqli_num_rows($run_user);
if($check_user>0){
$_SESSION['user_email']=$email;
echo "<script>window.open('home.php','_self')</script>";
}
else {
echo "<script>alert('Email or password is not correct, try again!')</script>";
}
}
?>
Here is a link to screenshots they might give more clarity [http://imgur.com/bX6HSmD,qFvyTGK,xEEiBi6,yAEvqAR,OdgRYFZ,U48OWkh]
Your screenshot's password column is user_password but your column is user_pass in your query.
AND user_pass='$pass'
^^^^^^^^^
Having checked for errors would have signaled that, unknown column.
As I mentioned in comments to add or die(mysqli_error($con)) to mysqli_query().
Edit:
It has been mentioned but I am including this here, should some of those comments get deleted in regards to password storage and prepared statements.
Since you appear to be new at this, it's good to start learning about using proper hashing and safe queries.
Storing passwords in plain text isn't safe, not for online use anyway or should anyone hack into your own PC; it is highly discouraged.
I recommend you use CRYPT_BLOWFISH or PHP 5.5's password_hash() function. For PHP < 5.5 use the password_hash() compatibility pack.
Plus, in regards to SQL injection, use mysqli with prepared statements, or PDO with prepared statements, they're much safer.
use if(session_id() == "")
{session_start();} at the top of the page, anything before
You need to start a session in all your PHP Scripts which use sessions. Use: session_start();before calling $_SESSION and then set the $_SESSION with the desired value.

Creating a simple "Logged In As" line on my page

<?php
session_start();
if(isset($_SESSION['login']))
{
include_once('includes/header.php'); ?>
<!DOCTYPE html>
<html>
<body>
<div id="mainframe">
<img src="img/header.png">
<div id="menu">
<?php include_once('includes/navbar.php'); ?>
</div>
<div id="content">
<h3>Shopping Cart</h3>
</div>
</div>
<?php include_once('includes/footer.php'); ?>
</body>
</html>
<?php }
else
{
header('location: login.php');
}
?>
Here is my small PhP code I've got at the moment, my login session is $_SESSION['login'].
And I'd like to display : Logged in As on my page when they are logged in, I've tried several things but it didn't work out.
Does anyone know a simple method / solution for this?
Put this somewhere in your if statement.
It will show Logged in as User at right top corner of page
<div style="position:absolute; right:0px; top:0px;">
<?php echo "Logged In as". $_SESSION['login']; ?>
</div>
U need to pass username using SESSION variable for the same
write a simple sql query to get the username from any variable you are taking from user to make sure that the particular user is the correct user.i am taking password.
$query = "SELECT name FROM users WHERE password='$password'";
$username = mysql_result(mysql_query($query),0);
$_SESSION['username'] = $username;
than proceed as you are doing
<?php
session_start();
if(isset($_SESSION['login']) && isset($_SESSION['username']))
{
echo "logged in as".$_SESSION['username'];
}

PHP use a variable from a different file

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

Undefined index in php (_SESSION['id'] and ['user'])

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

Categories