So this time I decided to go with a web programming language.
I always liked the way PHP worked, so I started learning it. I've started making a login page but I just don't know whats wrong with it. No errors if I use symbols.
I don't even think the form is processed. Is this the correct way to handle a form on the same page?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
session_start();
include("includes/connect.php");
if (isset($_SESSION['uid'])) {
header('Location:member.php');
}
if (isset($_POST['submit'])) {
$error = array();
//username
if (empty($_POST['username'])) {
$error[] = 'You cant have no username can you';
} else if (ctype_alnum($_POST['username'])) {
$username = $_POST['username'];
} else {
$error[] = 'Username cannot contain symbols';
}
//password
if (empty($_POST['password'])) {
$error[] = 'YOU NEED A PASSWORD';
} else {
$password = sha1(mysql_real_escape_string($_POST['password']));
}
//error
if (empty($error)) {
$result = mysql_query("SELECT * FROM user_info WHERE username='$username' AND password='$password'") or die(mysql_error());
if (mysql_num_rows($result) == 0) {
$error_message='Username or Password wrong';
} else {
$_SESSION['username'] = $username;
$_SESSION['user_id'] = mysql_result($result, 0, 'user_id');
}
} else {
foreach($error as $key => $values) {
$error_message.= "$values";
}
}
}
?>
<html>
<head>
<title>Login :)</title>
</head>
<body>
<div style="background-color:#A0A0A0" align="center">
<form method="post" action="<?php echo $_SERVER['PHP_SELF'] ?>">
<h3>Login</h3>
<div>
<label for="username">Username:</label>
<input type="text" name="username" maxlength="10"/>
</div>
<div>
<label for="password">Password:</label>
<input type="password" name="password" maxlength="20"/>
</div>
<div>
<input type="submit" name="submit "value="Login"/>
</div>
</form>
<?php echo $error_message; ?>
</div>
</body
</html>
your body tag isn't closed you forgot >
</body>
and delete the space in the submit button's name :)
Related
I wrote a code for a login page in PHP and MySQL. The code that I wrote is given below.
logintest.php:
<?php
session_start();
require_once('csrf.php');
?>
<?php
//session_start();
require_once('connect.php');
$csrf = new csrf();
// Generate Token Id and Valid
$token_id = $csrf->get_token_id();
$token_value = $csrf->get_token($token_id);
// Generate Random Form Names
$form_names = $csrf->form_names(array('email', 'password'), false);
if(isset($_POST[$form_names['email']], $_POST[$form_names['password']])) {
// Check if token id and token value are valid.
if($csrf->check_valid('post')) {
// Get the Form Variables.
$email = $_POST[$form_names['email']];
$password = $_POST[$form_names['password']];
// Form Function Goes Here
}
// Regenerate a new random value for the form.
$form_names = $csrf->form_names(array('email', 'password'), true);
}
if(isset($_POST) && !empty($_POST)) {
if(!isset($email) || empty($email)) {
$error[] = "email is required";
}
if(empty($email) && empty($password)) {
die("Please Enter your email and Password");
}
if(empty($email)) {
die("Please Enter your E-mail");
}
if(empty($password)) {
die("Please Fill in the password field");
}
if(!isset($password) || empty($password)) {
$error[] = "password is required";
}
if(!isset($error) || empty($error)) {
$sql = "SELECT email, password FROM loginsystem WHERE email = ? AND password = ?";
if($stmt = $connection->prepare("$sql")) {
$bound_params = $stmt->bind_param("ss", $email, $password);
$execute = $stmt->execute();
$storeResult = $stmt->store_result();
$rows = $stmt->num_rows();
} else {
"";
}
if($rows === 1) {
$_SESSION['email'] = $email;
header("location: home.php"); //redirects to home.php if everything's okay.
} else {
echo "Sorry $email, Wrong email & Password combination";
}
$stmt->close();
}
$connection->close();
}
?>
<html>
<head>
<title>Login System Test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
</head>
<body>
<div class="container">
<div class="row">
<form class="" method="post" >
<div class="form-group">
<input type="hidden" name="<?= $token_id; ?>" value="<?= $token_value; ?>" />
<label for="form-element">Email</label>
<input type="text" name="<?= $form_names['email']; ?>" class="form-control" id="email" placeholder="Email">
</div>
<div class="form-group">
<label for="form-element">Password</label>
<input type="password" name="<?= $form_names['password']; ?>" class="form-control" id="password" placeholder="Password">
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
</div>
</body>
</html>
Now the following is the code for home.php that I wrote:
<?php
session_start();
$email = $_SESSION['email'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<style type="text/css">
<!--
.style1 {
font-size: 36px;
font-weight: bold;
}
-->
</style>
</head>
<body>
<p><center>hello <?php echo $_SESSION['email'] ?></center></p>
<p align="center">logout</p>
</body>
</html>
Now by principle, we are allowed to enter the home.php file if and only if we provide the correct username and password and it does the same here too. But the problem is that if I go to home.php using this url : http://localhost/path/to/file/home.php , I come across this type of screen:
A Session ID is assigned and the login succeeds even if email or password are not provided through logintest.php. It clearly shows that I am missing out on some checkgates through which I can avoid happening that thing.
So, for avoiding this thing I want to make my code do a redirect to the logintest.php if anyone tries to access the home.php directly without providing proper credentials in the logintest.php file.
How can I achieve this? Early help will greatly be appreciated.
[P.S: I am new to PHP, so I often fall in such type of silly mistakes that ruin a day or two or my entire week.]
create a page called session.php and add this code
<?php
// check if the session is avilable if not go to login
$site = 'url address';// website address
if (!(isset($_SESSION['email']) && $_SESSION['email'] != '')) {
#header ("location: ".$site."login/");
}
// if you don't want any page redirection put this code to your page
session_start();
if (!(isset($_SESSION['email']) && $_SESSION['email'] != '')) {
//echo 'please login'; // heady login page
}else {
//echo 'logged in'; // go to member page
// logged in
// getting the logged in user - session
if($_SESSION['email']){
$welc = $_SESSION['email'].'';
}
//echo 'Welcome user:'.$welc. '<br>';
?>
Then call the page to every page you want to be accessed by the member. you may use require.
then to get the active session.
session_start();
if($_SESSION['email']){
$welc = $_SESSION['email'].'';
}
//echo 'Welcome user:'.$welc. '<br>';
update your login checks with this. i think it will help you
It was done right by setting a session variable and checking its presence in every page. This was easy and it consumed my whole week😡
I made a login that worked perfectly, but now im copying the original and editing it to work on another one of my web projects and it jsut dosnt seam to want to work, any help would be appreciated!
Here is the login that worked:
<?php
session_start();
include('../includes/connect-db.php');
if (isset($_SESSION['logged_in'])) {
?>
<html>
<head>
</head>
<body>
<div>Message would go here</div>
</body>
</html>
<?php
} else {
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) or empty($password)) {
$error = 'All fields are required!';
} else {
$query = $pdo->prepare('SELECT * FROM users WHERE user_username = ? 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 = 'Incorrect details!';
}
}
}
?>
<html>
<head>
</head>
<body>
<div>Login form would go here</div>
</body>
</html>
<?php } ?>
And here is the login im trying to get to work (some more info about it under the code):
<?php
//Start Session
session_start();
//Connect To DataBase
include($_SERVER['DOCUMENT_ROOT'].'includes/connect-db.php');
//Login
if (isset($_SESSION['logged_in'])) {
header('Location: http://localhost/logged-in.html');
} else {
if (isset($_POST['username'], $_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
if (empty($username) or empty($password)) {
$error = 'All fields are required!';
} else {
$query = $pdo->prepare('SELECT * FROM admins WHERE admin_username = ? AND admin_password = ?');
$query->bindValue(1, $username);
$query->bindValue(2, $password);
$query->execute();
$num = $query->rowCount();
if ($num == 1) {
$_SESSION['logged_in'] = true;
header('Location: http://localhost/techbite/logged-in.html');
exit();
} else {
$error = 'Incorrect details!';
}
}
}
//Page Content
$content = '<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Submit" />
</form>
<?php if (isset($error)) { ?>
<small style="color:#aa0000"><?php echo($error); ?></small>
<?php } ?>';
//Select Theme
include($_SERVER['DOCUMENT_ROOT'].'themes/theme-select.php');
}
?>
Keep in mind that database connection is successful, the login form appears but just dosnt seam to log in or show an error when nothing is entered/wrong credentials, everything else works perfect, including importing the form into the theme with $content.
Here is the connect-db.php:
<?php
//Connect To Database
try {
$pdo = new PDO('mysql:host=localhost;dbname=techbite', 'root', '');
} catch (PDOException $e) {
exit('Database error, could not connect.');
}
?>
What iv done here is included the theme:
include($_SERVER['DOCUMENT_ROOT'].'/themes/theme-select.php');
And inside the theme where i want the content i have:
<?php echo($content); ?>
and in the login php file i have this which will be put into the php theme file:
$content = '<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Submit" />
</form>
<?php if (isset($error)) { ?>
<small style="color:#aa0000"><?php echo($error); ?></small>
<?php } ?>';
I hope someone can help, hopefully its something small i have missed!
Thanks for any help and let me know if anything else is needed.
Kind Regards,
Hayden.
it's not showing an error because
$content = '<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Submit" /> </form>
<?php if (isset($error)) { ?>
<small style="color:#aa0000"><?php echo($error); ?></small>
<?php } ?>';
is all just a string, and the <?php ?> sections inside this string are never parsed by the php interpreter. View the page source of your login page and you should see them there.
If you're set on using this $content variable and the theme-select.php file, try changing it to this:
$content = '<form action="index.php" method="post" autocomplete="off">
<input type="text" name="username" placeholder="Username" />
<input type="password" name="password" placeholder="Password" />
<input type="submit" value="Submit" /> </form>';
if (isset($error)) {
$content .= '<small style="color:#aa0000">'.$error.'</small>';
}
As for why it's not logging in, it's a silly question, but have you created a table in your database named admins and a record there with a username and password set?
Try replacing
$num = $query->rowCount();
with
$num = count($query->fetchAll(PDO::FETCH_ASSOC));
UPDATE
Just noticed this...
if (isset($_POST['username'], $_POST['password'])) {
should be
if( isset($_POST['username']) && isset($_POST['password']) ) {
I would add an else condition here to display an error message of some description
UPDATE 2
Slight modification to your connect.php
try {
// create a new instance of a PDO connection
$pdo = new PDO('mysql:host=localhost;dbname=techbite', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
// if the connection fails, display an error message
echo 'ERROR: ' . $e->getMessage();
}
I fixed it!
i knew it would be something so small and simple, it was the form action which was set to the wrong file name, it was set to index.php instead of login.php.
Thank you to everyone for your help! :)
Im trying to integrate usercake onto my website. I installed it and registered an account. When i try to login with that account, the browser loads then nothing happens and i cant get into an account.
<?php
/*
UserCake
http://usercake.com
Developed by: Adam Davis
*/
require_once("models/config.php");
//Prevent the user visiting the logged in page if he/she is already logged in
if(isUserLoggedIn()) { header("Location: account.php"); die(); }
?>
<?php
/*
Below is a very simple example of how to process a login request.
Some simple validation (ideally more is needed).
*/
//Forms posted
if(!empty($_POST))
{
$errors = array();
$username = trim($_POST["username"]);
$password = trim($_POST["password"]);
//Perform some validation
//Feel free to edit / change as required
if($username == "")
{
$errors[] = lang("ACCOUNT_SPECIFY_USERNAME");
}
if($password == "")
{
$errors[] = lang("ACCOUNT_SPECIFY_PASSWORD");
}
//End data validation
if(count($errors) == 0)
{
//A security note here, never tell the user which credential was incorrect
if(!usernameExists($username))
{
$errors[] = lang("ACCOUNT_USER_OR_PASS_INVALID");
}
else
{
$userdetails = fetchUserDetails($username);
//See if the user's account is activation
if($userdetails["Active"]==0)
{
$errors[] = lang("ACCOUNT_INACTIVE");
}
else
{
//Hash the password and use the salt from the database to compare the password.
$entered_pass = generateHash($password,$userdetails["Password"]);
if($entered_pass != $userdetails["Password"])
{
//Again, we know the password is at fault here, but lets not give away the combination incase of someone bruteforcing
$errors[] = lang("ACCOUNT_USER_OR_PASS_INVALID");
}
else
{
//Passwords match! we're good to go'
//Construct a new logged in user object
//Transfer some db data to the session object
$loggedInUser = new loggedInUser();
$loggedInUser->email = $userdetails["Email"];
$loggedInUser->user_id = $userdetails["User_ID"];
$loggedInUser->hash_pw = $userdetails["Password"];
$loggedInUser->display_username = $userdetails["Username"];
$loggedInUser->clean_username = $userdetails["Username_Clean"];
//Update last sign in
$loggedInUser->updateLastSignIn();
$_SESSION["userCakeUser"] = $loggedInUser;
//Redirect to user account page
header("Location: account.php");
die();
}
}
}
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login</title>
<link href="cakestyle.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="wrapper">
<div id="content">
<div id="left-nav">
<?php include("layout_inc/left-nav.php"); ?>
<div class="clear"></div>
</div>
<div id="main">
<h1>Login</h1>
<?php
if(!empty($_POST))
{
?>
<?php
if(count($errors) > 0)
{
?>
<div id="errors">
<?php errorBlock($errors); ?>
</div>
<?php
} }
?>
<div id="regbox">
<form name="newUser" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<p>
<label>Username:</label>
<input type="text" name="username" />
</p>
<p>
<label>Password:</label>
<input type="password" name="password" />
</p>
<p>
<label> </label>
<input type="submit" value="Login" class="submit" />
</p>
</form>
</div>
</div>
<div class="clear"></div>
</div>
</div>
</body>
</html>
Its ok. The problem was with my web host and their php sessions configuration.
The database is set up correctly but I the error handler when I dont enter a username or password is not working. I always get Invalid username and/or password
The following code doesn't go the the "loginhandler.php" link
Any ideas to why?
No matter the input the code executes`
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="css/login.css">
</head>
<body>
<?php
$okay = FALSE;
$username = ($_POST['username']);
$password = ($_POST['password']);
$onError = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (empty($_POST['username'])) {
$onError = 'Please Enter your Username';
$okay = FALSE;
}
if (empty($_POST['password'])) {
$onError = 'Please Enter your password';
$okay = FALSE;
}
if($okay == FALSE)
{
$dbc = mysql_connect('localhost', 'user', 'pass');
mysql_select_db('db_name', $dbc);
$query = "SELECT * FROM signup WHERE username = '" . $username . "' AND password='" . $password . "'";
if ($result = mysql_query($query, $dbc)) {// Run the query.
while ($row = mysql_fetch_array($result)) {
$okay = true;
}
} else {
}
}
if ($okay) {
// session_start();
$_SESSION['username'] = $username;
header('Loction: loginhandler.php');
exit() ;
} else {
$onError = "Invalid username and/or password";
}
}
?>
<!-- Begin Page Content -->
<div id="container">
<form id='login' action='login.php' method='post' accept-charset='UTF-8'>
<div class="error"><?php echo $onError; ?></div>
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<div id="lower">
<input type="checkbox"><label class="check" for="checkbox">Keep me logged in</label>
<input type="submit" value="Login">
<p>Click here to Signup.</p>;
</div><!--/ lower-->
</form>
</div><!--/ container-->
<!-- End Page Content -->
</body>
</html>`
$onError = "Invalid username and/or password";
First, you are using session. add session_start() at the top of the page.
header('Location: loginhandler.php'); you wrote Location wrong.
if($okay == FALSE) Should be if($okay == TRUE)
And you alweyes getting the invalid message because you have "$onError = "Invalid username and/or password";" at the bottom of the code outside any PHP tags.
I have a login page where i have to : insert user and password (1 time); click the button(the login button) twice to actually login.I use Xamp with PHP 5.3 and HeidiSQL .If i'm already in session, it skips the login window and redirects to content page else the form is submitted(which is what i want it to do).This is my code :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
session_start();
include("../conect.php");
if(isset($_SESSION['name']))
{
$username = $_SESSION['name'];
$pass = $_SESSION['pass'];
$check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error());
while($info = mysql_fetch_array( $check ))
{
if ($pass != $info[2]){
header('.<?php $_PHP_SELF ?>.');
}
else
{ if($_SESSION['role']==0)
header("Location: content0.php");
if($_SESSION['role']==1)
header("Location: content1.php");
if($_SESSION['role']==2)
header("Location: content2.php");
}
}
}
//if the login form is submitted
if (isset($_POST['login'])) {
$nume=mysql_real_escape_string($_POST['username']);
$parola=md5(mysql_real_escape_string($_POST['pass']));
if((!$_POST['username']) || (!$_POST['pass'])) {
die('You did not fill in a required field.');
}
$check_pass = mysql_query("SELECT * FROM users WHERE username = '$nume'")or die(mysql_error());
$check2 = mysql_num_rows($check_pass);
if ($check2 == 0) {
die("That user does not exist in our database");
}
while($data = mysql_fetch_array( $check_pass )) {
//gives error if the password is wrong
if ($parola != $data[2]) {
die('Incorrect password, please try again.');
}
else {
$result = mysql_query("SELECT * FROM users WHERE username = '$nume'")or die(mysql_error());
while($data=mysql_fetch_row($result)){
$_SESSION['name']=$data[1];
$_SESSION['pass']=$data[2];
$_SESSION['role']=$data[3];
}
}
}
}
mysql_close($con);
?>
<html>
<head>
<title>Login</title>
<link rel="stylesheet" href="/css/butoane.css" type="text/css" />
<link rel="stylesheet" href="/css/admin_tools.css" type="text/css" />
<script>
</script>
</head>
<body id="login_background">
<div id="ambele">
<div class="form_box">
<form action="<?php $_PHP_SELF ?>" method="post">
<label for="username">Username</label><input type="text" id="username" name="username" maxlength="40"/>
<label for="password">Password</label><input type="password" id="password"name="pass" maxlength="20"/>
<input type="submit" name ="login" value="Login" class="button"/>
</form>
</div>
<div id="register">
Not registered yet? Go to Registration
</div>
</div>
</body>
</html>
I think you need to exit your script to do redirection.
<?php
header('Location: content.php');
die();
?>
Also, you put the PHP tag in the wrong position.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
[...]
?>
[...]
This will cause the Headers already sent error in PHP because you already send something to the client before you do redirection.