I have a small login system on my site. I want the user to be redirected to the home page after the successful login. After several attempts with many possibilities, I still do not succeed.
This is my login script:
<?php
if (isset($_POST["submit"])) {
require("mysql.php");
$stmt = $mysql->prepare("SELECT * FROM $accounts WHERE email = :email");
$stmt->bindParam(":email", $_POST["email"]);
$stmt->execute();
$count = $stmt->rowCount();
if ($count == 1) {
$row = $stmt->fetch();
if (password_verify($_POST["password"], $row["password"])) {
$_SESSION['username'] = $row['username'];
?>
<div class="alert alert-emerald text-center mb-50">
You have been successfully registered
</div>
Continue
<?php
} else {
?>
<div class="alert alert-red-ncs text-center mb-50">
The specified password is incorrect
</div>
<?php
}
} else {
?>
<div class="alert alert-red-ncs text-center mb-50">
An account with this email address was not found
</div>
<?php
}
}
?>
I have already had these attempts:
header("Location: index.php");
exit;
header("Location: index.php");
header('Location: login.php?redirect=index.php');
I'm really looking forward to an answer as I've been stuck on the solution for several hours now!
Related
I currently have 2 different navbars. One with Login and Sign up at the top and one with Account. I want the navbar to change to the one with Account after a user is logged in. My registration and login system is already working, so that won't have to change (connected to a database). Don't mind the names, it's for a school project.
These are my 2 navbars:
<div class="navbar">
<a class="active" href="Boomba.php">Boomba</a>
<div class="dropdown">
<button class="dropbtn">Boomba News
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
New News
Dead News
</div>
</div>
Boomba Store
Contact
<div class="floatr">
Sign Up
Login
Account
</div>
</div>
I currently have this at the top of the page:
<?php
session_start();
?>
Please let me know if there's an easier way overall to make this happen as well, this is my first website.
Thanks in advance :)
Edit:
My config file:
<?php
define('DB_SERVER', '-');
define('DB_USERNAME', '-');
define('DB_PASSWORD', '-');
define('DB_NAME', '-');
$link = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
?>
My Login file:
<?php
session_start();
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
header("location: welcome.php");
exit;
}
require_once "0config.php";
$username = $password = "";
$username_err = $password_err = "";
if($_SERVER["REQUEST_METHOD"] == "POST"){
if(empty(trim($_POST["username"]))){
$username_err = "Please enter username.";
} else{
$username = trim($_POST["username"]);
}
if(empty(trim($_POST["password"]))){
$password_err = "Please enter your password.";
} else{
$password = trim($_POST["password"]);
}
if(empty($username_err) && empty($password_err)){
$sql = "SELECT id, username, password FROM users WHERE username = ?";
if($stmt = mysqli_prepare($link, $sql)){
mysqli_stmt_bind_param($stmt, "s", $param_username);
$param_username = $username;
if(mysqli_stmt_execute($stmt)){
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
if(mysqli_stmt_fetch($stmt)){
if(password_verify($password, $hashed_password)){
session_start();
$_SESSION["loggedin"] = true;
$_SESSION["id"] = $id;
$_SESSION["username"] = $username;
header("location: welcome.php");
} else{
$password_err = "The password you entered was not valid.";
}
}
} else{
$username_err = "No account found with that username.";
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
mysqli_stmt_close($stmt);
}
mysqli_close($link);
}
?>
You are duplicating a lot of code for your navbar here. You could do something like this if the other parts of your navbar don't need to change :
<div class="navbar">
<a class="active" href="Boomba.php">Boomba</a>
<div class="dropdown">
<button class="dropbtn">Boomba News
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
New News
Dead News
</div>
</div>
Boomba Store
Contact
<div class="floatr">
<?php if (isset($_SESSION['loggedin']) && $_SESSION['loggedin']): ?>
Account</li>
<?php else: ?>
Sign Up</li>
Login</li>
<?php endif; ?>
</div>
</div>
After the login operation, you must load the user-specific data to $_SESSION array. Imagine you have stored the user data to $_SESSION then you can check the $_SESSION value exist or not.
A sample code is given below. If you don't understand please let me know.
<?php
session_start();
if (isset($_SESSION["loggedin"]) && ($_SESSION["loggedin"] == TRUE)) {
//write a nav menu html code here
?>
<div>
nav-1
</div>
<?php
} else {
//write another nav menu html code here
?>
<div>
nav-2
</div>
<?php
}
?>
When user logged in, the login link on nav bar should be gone and logout link should appear how should i do it?
index.html:
<nav>
<p class="menu">Home</p>
<p class="menu">Products </p>
<p class="menu">Login</p>
<p class="menu">Logout</p>
</nav>
Login.php file:
<?php
require 'db.php';
session_start();
$password = $mysqli->escape_string($_POST['Pass']);
$email = $mysqli->escape_string($_POST['EmailAdd']);
$result = $mysqli->query("SELECT * FROM Account WHERE Usermail='$email'");
//check email in db
if ($result->num_rows == 0)
{
$_SESSION['message'] = "Email does not exist";
print '<script type="text/javascript">alert("' . $_SESSION['message'] .
'");
</script>';
header("Location: ../register.html");
}
else
{
//get user array
$user = $result->fetch_assoc();
if ($password == $user['password'])
{
$box = "Login successful";
$_SESSION['email'] = $user['Usermail'];
$_SESSION['logged_in'] = true;
echo ("<SCRIPT LANGUAGE='JavaScript'>
window.alert('Login Successful')
window.location.href='../index.html';
</SCRIPT>");
}
else
{
$_SESSION['message'] = "Wrong password";
header("Location: ../account.html");
echo "failed";
echo '<script language="javascript">';
echo 'alert("Wrong password")';
echo '</script>';
}
}
?>
I've gone through some of the post in stack overflow and apply things like if (!isset($_SESSION['email'])) and else statement on my index.php but its not working and i don't know what's the prob
Ps Previously was using index.php, since its not working so i change it back to index.html
<?php
if(!isset($_SESSION['logged_in'])){?>
<p class="menu">Login</p>
<?php }
else
{?> <p class="menu">Logout</p>
<?php } ?>
try the above code, Hope this helps
Assuming your code is correctly validating the credential and setting the auth state in the session $_SESSION['logged_in'] = true;
You can do something like this:
<nav>
<p class="menu">Home</p>
<p class="menu">Products </p>
<?php if (isset($_SESSION['logged_in']) && $_SESSION['logged_in'] == true): ?>
<p class="menu">Logout</p>
<?php else: ?>
<p class="menu">Login</p>
<?php endif; ?>
</nav>
Try this in your nav:
<?php
if($_SESSION['logged_in'] == "true"){
echo '<p class="menu">Login</p>';
}
else {
echo '<p class="menu">Logout</p>';
}
?>
It is not working because you use the .html extension instead of .php
<nav>
<p class="menu">Home</p>
<p class="menu">Products </p>
<?php if(empty($_SESSION['logged_in'])){ ?>
<p class="menu">Login</p>
<?php } else{ ?>
<p class="menu">Logout</p>
<?php } ?>
</nav>
This should work:
<nav>
<p class="menu">Home</p>
<p class="menu">Products</p>
<p class="menu">
<?php if(isset($_SESSION['logged_in]) && $_SESSION['logged_in]) {?>
Logout
<?php } else { ?>
Login
<?php } ?>
</p>
</nav>
I have a problem with the register page in PHP language. When I click the submit button the form is submitting but no data is storing in the database. And can not use the registered user to login into the site. The same codes are working properly in the local server (Wampp server) but not working in the website.
these are the codes:
<?php
require_once("../includes/functions.php");
$sess_start->start_session(false);
if(check_login(1, $sess_start->get_dbhandler()) == true)
{
header('Location: userportal.php');
}
else
{
if (!empty($_POST['RegisterFname']) || !empty($_POST['RegisterLname']) || !empty($_POST['RegisterEmail']) || !empty($_POST['RegisterUsername']) || !empty($_POST['RegisterPassword']) || !empty($_POST['RegisterRPassword']) || !empty($_POST['RegisterDob']) || !empty($_POST['RegisterAddress']) || !empty($_POST['RegisterRegion']) || !empty($_POST['RegisterCountry']) || !empty($_POST['RegisterPhone']))
{
if (!empty($_POST['RegisterFname']) && !empty($_POST['RegisterLname']) && !empty($_POST['RegisterEmail']) && !empty($_POST['RegisterUsername']) && !empty($_POST['RegisterPassword']) && !empty($_POST['RegisterRPassword']) && !empty($_POST['RegisterDob']) && !empty($_POST['RegisterAddress']) && !empty($_POST['RegisterRegion']) && !empty($_POST['RegisterCountry']) && !empty($_POST['RegisterPhone']))
{
if (($_POST['RegisterPassword'] == $_POST['RegisterRPassword']))
{
if (strlen($_POST['RegisterRPassword']) >= 8)
{
$registeruser = new user();
$registeruser->nickname = clean_string($sess_start->get_dbhandler(), $_POST['RegisterUsername']);
$registeruser->sql = mysqli_query($sess_start->get_dbhandler(), "SELECT * FROM `users` WHERE n_name = '$registeruser->nickname'");
if (mysqli_num_rows($registeruser->sql) == 0)
{
$registeruser->fname = clean_string($sess_start->get_dbhandler(), $_POST['RegisterFname']);
$registeruser->lname = clean_string($sess_start->get_dbhandler(), $_POST['RegisterLname']);
$registeruser->email = clean_string($sess_start->get_dbhandler(), $_POST['RegisterEmail']);
$registeruser->password = $_POST['RegisterRPassword'];
$registeruser->password = hash('sha512', $registeruser->password);
$registeruser->dob = clean_string($sess_start->get_dbhandler(), $_POST['RegisterDob']);
$registeruser->addr = clean_string($sess_start->get_dbhandler(), $_POST['RegisterAddress']);
$registeruser->state = clean_string($sess_start->get_dbhandler(), $_POST['RegisterRegion']);
$registeruser->country = clean_string($sess_start->get_dbhandler(), $_POST['RegisterCountry']);
$registeruser->phone = clean_string($sess_start->get_dbhandler(), $_POST['RegisterPhone']);
$registeruser->regtime = time();
$registeruser->sql = mysqli_query($sess_start->get_dbhandler(), "INSERT INTO `users` (f_name, l_name, email, n_name, password, age, addr, state, country, phone, l_login, r_time) VALUES ('$registeruser->fname', '$registeruser->lname', '$registeruser->email', '$registeruser->nickname', '$registeruser->password', '$registeruser->dob', '$registeruser->addr', '$registeruser->state', '$registeruser->country', '$registeruser->phone', '0', '$registeruser->regtime')");
if (!empty($_GET['RegisterPromo']))
{
$registeruser->coupon = clean_string($sess_start->get_dbhandler(), $_POST['RegisterPromo']);
$registeruser->sql = mysqli_query($sess_start->get_dbhandler(), "UPDATE `users` SET promo = '$registeruser->coupon' WHERE n_name = '$registeruser->nickname'");
}
$_SESSION['RegisterUserError'] = 5;
header('Location: register.php');
}
else
{
$_SESSION['RegisterUserError'] = 4;
header('Location: register.php');
}
}
else
{
$_SESSION['RegisterUserError'] = 3;
header('Location: register.php');
}
}
else
{
$_SESSION['RegisterUserError'] = 2;
header('Location: register.php');
}
}
else
{
$_SESSION['RegisterUserError'] = 1;
header('Location: register.php');
}
}
else
{
echo '
meta tages and links for the stylesheets
';
?>
<?php
?>
<div class="container" id="registration-form">
<div class="image"></div>
<form role="form" class="form-signin" method="post" action="<?php echo clean_url($_SERVER['PHP_SELF']); ?>">
<section class="panel">
<div class="panel-body">
<?php
if (isset($_SESSION['RegisterUserError']))
{
if ($_SESSION['RegisterUserError'] == 1)
{
?>
<div class="alert alert-block alert-danger fade in">
<strong>Fill all mandatory fields(*) for completing user registeration</strong>
</div>
<?php
}
else if ($_SESSION['RegisterUserError'] == 2)
{
?>
<div class="alert alert-block alert-danger fade in">
<strong>Entered passwords do not match</strong>
</div>
<?php
}
else if ($_SESSION['RegisterUserError'] == 3)
{
?>
<div class="alert alert-block alert-danger fade in">
<strong>Passwords must be 8 or more character longer</strong>
</div>
<?php
}
else if ($_SESSION['RegisterUserError'] == 4)
{
?>
<div class="alert alert-block alert-danger fade in">
<strong>There is already a user exist with this same username</strong>
</div>
<?php
}
else if ($_SESSION['RegisterUserError'] == 5)
{
?>
<div class="alert alert-success fade in">
<strong>Successfully completed the user registeration. However, your account is not verified unless you complete "Know your customer" process after login to your account.</strong>
</div>
<?php
}
else
{
?>
<div class="alert alert-block alert-danger fade in">
<strong>Unexpected error occured</strong>
</div>
<?php
}
unset($_SESSION['RegisterUserError']);
}
else
{
?>
<div class="alert alert-success fade in">
<strong>Fields indicated using * are mandatory in registeration</strong>
</div>
<?php
}
?>
<div class="frm">
inputs here
</form>
<div class="form-footer">
<div class="row">
<div class="col-xs-5 col-sm-5 col-md-5">
<i class="fa fa-check"></i> Sign In
</div>
</div>
</div>
</div>
</div>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
<?php
}
}
?>
if it is working on your local server, then check your web hosting service. Most Service provider will ask you to the these three things :
1.Create the database
2.Create a database user
3.Assign the user to the database
These steps could be confusing depending on your host and is usually carried out in your cpanel database page or use the database creation wizard if available.
This is not a duplicate of Maximum execution time in phpMyadmin; this has nothing to do with phpmyadmin.
On my site, there is a form which sends POST data to a PHP script and loads a new page. When you submit the form, the page loads forever and then results in:
The XXX.XXX page isn’t working XXX.XXX is currently unable to handle
this request. HTTP ERROR 500
I thought it may be a traffic issue so I upgraded my hosting SSD and made the website only available to me to test it, but the problem still persisted. Here is my script:
<?php
$used_file = 'used.txt';
$codes_file = 'codes.txt';
# Generates a random unused code from the code file
function genCode() {
global $used_file, $codes_file;
$codes = file_get_contents($codes_file);
$codes = explode("\n", $codes);
$used = file_get_contents($used_file);
$used = explode("\n", $used);
foreach($codes as $code) {
if(!in_array($code, $used))
return $code;
}
}
# Generate error string from error code
function getError($err) {
switch($err) {
case 1: return 'No submit';
case 2: return 'Wrong password';
case 3: return 'No password';
}
}
# Adds generated code to the 'used' codes file
function append_used($code) {
global $used_file, $codes_file;
$str = $code . '\n';
file_put_contents($used_file, $str, FILE_APPEND);
}
# Get user's IP (for cookie handling)
function getIP() {
if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
# Cookie handling
# Set a cookie for how many times the form has been submitted by user
$used = 0;
if(isset($_COOKIE['used_twice'])) {
$used = 3;
}
if(isset($_COOKIE['used_once']) && !isset($_COOKIE['used_twice'])) {
setcookie('used_twice', getIP(), time()+18000);
$used = 2;
}
if(!isset($_COOKIE['used_once'])) {
setcookie('used_once', getIP());
$used = 1;
}
# Check if all the POST data is correct
$password = $_POST['inputPassword'];
$submit = $_POST['submit'];
if(isset($password)) {
if($password == 'test123') {
if(isset($submit)) {
$code = genCode();
}
else
$err = 1;
} else
$err = 2;
} else
$err = 3;
# Now generate the new page
include 'web_functions.php';
getHead('Generated', 'Generated code');
getBody('Generated code');
?>
<img src="goback.png"></img>
<h2>Code Generated</h2>
<br/>
<?php
if(!isset($err) && isset($thecode) && $used == 1) {
?>
<center>
<div class="bs-component">
<div class="alert alert-dismissible alert-success">
<p>Your code is: </p> <strong> <?php echo $thecode; append_used($thecode); ?> </strong>
</div>
</div>
</div>
</center>
<?php
} elseif(isset($err)) {
?>
<center>
<div class="bs-component">
<div class="alert alert-dismissible alert-danger">
<p>There was an error:</p> <strong><?php echo getError($err); ?></strong>
</div>
</div>
</div>
</center>
<?php
} elseif(!isset($err) && $used != 1){
?>
<center>
<div class="bs-component">
<div class="alert alert-dismissable alert-danger">
<p>You can only use the code generator once every 5 hours. Please try again later.</p>
</div>
</div>
</div>
</center>
<?php } else { ?>
<div class="bs-component">
<div class="alert alert-dismissable alert-danger">
<p>There was an unexpected error. Please try again.</p>
</div>
</div>
</div>
<?php } ?>
<br/>
<br/>
<br/>
<?php closeTags();
getFooter(); ?>
</div>
</div>
</div>
</div>
What could be causing this issue?
Edit: The error log says:
PHP Fatal error: Maximum execution time of 60 seconds exceeded on line 13
Line 13 is within the foreach loop.
This is what i have for headers.php anyway it is suppose to be my navigation bar. Here's the problem, when I login with a user as Member the whole header does not come out. But when I login with admin the navigations will "magically" come out!
<?php
if(!isset($_SESSION['sRole'])){
?>
<div id="header">
<div id="fb-root"></div>
<div id ="inthebox">
<b>LOGIN</b>|
<b>REGISTER</b>
</div>
<div id ="outthebox">
HOME|
BOOKSHELF|
SHOPPING CART|
ABOUT|
ABOUT|
</div>
</div>
<?php
}
else{
if($_SESSION['sRole'] == "member"){
?>
<div id="header">
<div id ="inthebox">
<b>LOGOUT</b>
</div>
<div id ="outthebox">
HOME|
BOOKSHELF|
SHOPPING CART|
ABOUT|
PROFILE
<?php
echo("You have Login as :" . $_SESSION['sUsername']);
?>
</div>
</div>
<?php
}else{
if($_SESSION['sRole']=="admin"){
?>
<div id="header">
<div id ="inthebox">
<b>LOGOUT</b>
</div>
<div id="outthebox">
HOME|
BOOKSHELF|
SHOPPING CART|
ABOUT|
Manage Account|
Manage Books|
Manage Orders|
<?php
echo("You have Login as :" . $_SESSION['sUsername']);
?>
</div>
</div>
<?php
}
}
}
?>
This is my doLogin.php page , maybe it might help anyone here to solve this. I store the id, username, firstname and last name into the session. Inside have alr . The website hor when I go in is no error one . no html code error or whatsoever. Just that it does not appear. However the words below the nav links will still come out.
<?php
//connect to database
include ('dbfunction.php');
if (!isset($_POST['Login'])) {
if (isset($_POST['username'])) {
//retrieve form data
$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM users WHERE username='" . $username . "'AND password = '" . $password . "'";
$result = mysql_query($query) or die('The error :' . mysql_error());
$num_rows =mysql_num_rows($result);
if($num_rows == 0){
header('Location:login.php');
exit();
}
//if record is found, store id and username into session
else{
$row = mysql_fetch_array($result);
$_SESSION['sUsername'] = $row['username'];
$_SESSION['sRole'] = $row['role'];
$_SESSION['sFirst_name'] = $row['first_name'];
$_SESSION['sLast_name'] = $row['last_name'];
header('location:successful_login.php');//redirect to this page
exit();
}
}
else {
}
} else {
header('Location:successful_login.php');
exit();
}
mysql_close();
?>
I think the problem here is you are using } else { conditions, but then nesting an if statement inside of them. In fact it looks like you had some broken closing braces. Here is the revised code:
<?php if(!isset($_SESSION['sRole'])){ ?>
<div id="header">
<div id="fb-root"></div>
<div id ="inthebox">
<b>LOGIN</b>|
<b>REGISTER</b>
</div>
<div id ="outthebox">
HOME|
BOOKSHELF|
SHOPPING CART|
ABOUT|
ABOUT|
</div>
</div>
<?php } else if($_SESSION['sRole'] == "member") { ?>
<div id="header">
<div id ="inthebox">
<b>LOGOUT</b>
</div>
<div id ="outthebox">
HOME|
BOOKSHELF|
SHOPPING CART|
ABOUT|
PROFILE
<?php
echo("You have Login as :" . $_SESSION['sUsername']);
?>
</div>
</div>
<?php }else if($_SESSION['sRole']=="admin"){ ?>
<div id="header">
<div id ="inthebox">
<b>LOGOUT</b>
</div>
<div id="outthebox">
HOME|
BOOKSHELF|
SHOPPING CART|
ABOUT|
Manage Account|
Manage Books|
Manage Orders|
<?php
echo("You have Login as :" . $_SESSION['sUsername']);
?>
</div>
</div>
<?php
}
try this:
<?php if( (!isset($_SESSION['sRole'])) || (empty($_SESSION['sRole'])) || (is_null($_SESSION['sRole'])) ): ?>
<html>your code</html>
<?php else: ?>
<?php switch($_SESSION['sRole']) {
case 'admin': { // admin code } break;
case 'member': { // member code } break;
default: { // something happened } break;
}
?>
<?php endif; ?>
check and diagnose the issue