is this right the code will redirect a person to the login page when they try to access it using without going into the login page
<?php
$pass = 'password';
?>
<html>
<head>
<title></title>
</head>
<body>
<?php
if ( $_POST["pass"] == $pass){
?>
Congrats you have log in!
<?php
}else{
header("Location: http://signin.com/");
}
?>
</body>
</html>
i ended up having a "Server error
The website encountered an error while retrieving http://www.test.com It may be down for maintenance or configured incorrectly."
You can't call header after you've already outputted some HTML. Do your password checks & redirect. above the HTML
Eg:
<?php
$pass = 'password';
if ( $_POST["pass"] != $pass){
header("Location: http://signin.com/");
exit;
}
?>
<html>
<head>
<title></title>
</head>
....
So the HTML will only show if they're successful.
You can't send a header() after any output to the user:
<?php
$pass = 'password';
if ( $_POST["pass"] == $pass)
{
?>
<html>
<head>
<title></title>
</head>
<body>
Congrats you have log in!
</body>
</html>
<?php
}
else
{
header("Location: http://signin.com/");
}
?>
Something like this would work better:
<?php
$pass = 'password';
if ($_POST["pass"] != $pass){
header("Location: http://signin.com/");
exit;
}
?>
<html>
<head>
<title></title>
</head>
<body>
Congrats you have log in!
</body>
</html>
You need to check if the user is logged in. If not, redirect and exit. If so, display the message.
Put ob_start(); at the top and ob_end_flush(); and that might fix it.
You can't output html before make a redirect with header. Code all logic before:
<?php
$pass = 'password';
if ($_POST["pass"] == $pass)
{
$message = "Congrats you have log in!";
}
else
{
header("Location: http://signin.com/");
}
?>
<html>
<head>
<title></title>
</head>
<body>
<?php echo $message; ?>
</body>
Related
I'm building a simple login system.
Registration is working with password_default:
So, now the login. This is my login class:
<?php
include("../Controllers/DatabaseController.php");
class LoginModel extends DatabaseController
{
protected $dbconn;
public function __construct()
{
$this->dbconn = DatabaseController::instance();
}
public function Login()
{
$db = $this->dbconn->pdo;
try {
$username = $_POST['username'];
$passwordAttempt = $_POST['user_password'];
//Retrieve the user account information for the given username.
$sql = "SELECT * FROM user WHERE username = :username";
$stmt = $db->prepare($sql);
//Bind value.
$stmt->bindParam(':username', $username);
//Execute.
$stmt->execute();
//Fetch row.
$user = $stmt->fetch(PDO::FETCH_ASSOC);
//If $row is FALSE.
if ($user === false) {
//Could not find a user with that username!
?>
<script type="text/javascript">
alert("username not found!");
window.location.href = "../Views/login.php";
</script>
<?php
} else {
//User account found. Check to see if the given password matches the
//password hash that we stored in our users table..
$validPassword = password_verify($passwordAttempt, $user['user_password']);
//If $validPassword is TRUE, the login has been successful.
if ($validPassword) {
//Provide the user with a login session.
$_SESSION['id'] = $user['id'];
$_SESSION['logged_in'] = time();
//Redirect to our protected page, which we called home, to see if we are provided a session.php
?>
<script type="text/javascript">
alert("You're logged in!");
window.location.href = "../index.php";
</script>
<?php
header('Location: home.php');
exit;
} else {
//$validPassword was FALSE. Passwords do not match.
?>
<script type="text/javascript">
alert("Password is incorrect!");
window.location.href = "../Views/login.php";
</script>
<?php
}
}
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
}
}
Now I know, it isn't proper OOP, but I'm learning.
When I press login, passwords do match:
But when redirecting to home.php, it seems the log in didn't provide me with a session_id...
Home.php:
<?php
/**
* Start the session.
*/
session_start();
/**
* Check if the user is logged in.
*/
if(!isset($_SESSION['id']) || !isset($_SESSION['logged_in'])){
//User not logged in. Redirect them back to the login.php page.
?>
<script type="text/javascript">
alert("You're not logged in!" );
</script>
<?php
exit;
}
/**
* Print out something that only logged in users can see.
*/
echo 'Congratulations! You are logged in!';
I hope somebody has a solution, because I don't see one unfortunately.
For completion my partial login.php:
<?php
include "../Models/LoginModel.php";
$login = new LoginModel();
?>
<?php
if (isset($_POST["submit"])) {
$login->Login();
}
?>
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<title>Title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="../style-registration.css">
</head>
<body>
<?php
include 'header.php';
?>
<div class="signup-form">
<form action="" method="post">
And my partial header.php:
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<title>Scores Website</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="../style-index.css">
</head>
<body>
<nav class="navbar navbar-expand-xl bg-light">
Try to end with that kind of structure :
<?php
include "../Models/LoginModel.php";
session_start();
if ($_POST) {
//execute login method
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
//set title, meta, call needed css files
</head>
<body>
//your form etc...
//end with javascript calls
</body>
</html>
In this order everything should works as expected.
Problem :
User is already logged in
so when I type
local.test_php.com/form/
It takes me to Login page. local.test_php.com/form/index.php
But i want it to take it to my home page instead.(http://local.test_php.com/form/home.php)
what i want is like what facebook does when we type facebook.com (already logged in before) we r redirected to the news feed ... but in my case i get redirected to Login page(even if i'm already logged in) so i have to login again or type the url to get to the home page
I don't know how to customize sessions to always redirect to home page whenever user is logged in. It should not take me to login page in any condition.
Home page looks like this:
<!DOCTYPE html>
<html>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<head>
<title>My first PHP Website</title>
</head>
<body>
<h2 align="center">Home Page</h2>
<?php
session_start();
if(isset($_SESSION['user'])){
}else{
header("location: index.php");
}
$user = $_SESSION['user'];
echo "<br>";
echo "WELCOME ".$user." ";
echo "<br>";
echo "Do you want to ";
print 'logout';
echo " ?";
echo "<br>";
?>
</body>
</html>
I rewrote your code a littlebit, so it's more readable now.
First of all, when you want to use header function on your page, or start a session, you should do it before anyhing in the output buffer.
As you see, I removed the echo things, if you use an IDE as an editor, syntax highlighting help you to read the code, and be sure, it is valid.
The second thing, if you want to "remember" for user, when user closes all the browsers what stored the session variables, then you need to give a shot for cookies. But first, fix the code.
<?php
session_start();
if (!isset($_SESSION['user'])) {
header("location: index.php");
}
?><!DOCTYPE html>
<html>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<head>
<title>My first PHP Website</title>
</head>
<body>
<h2 align="center">Home Page</h2>
<?php
if (!empty($_SESSION['user'])) {
?>
<p>WELCOME <?php echo $_SESSION['user']; ?></p>
<p>Do you want to logout?</p>
<?php
}
?>
</body>
</html>
try this:
<?php
session_start();
if(isset($_SESSION['user'])){
}else{
header("location: index.php");
}
$user = $_SESSION['user'];
echo "<br>";
echo "WELCOME ".$user." ";
echo "<br>";
echo "Do you want to ";
print 'logout';
echo " ?";
echo "<br>";
?>
<html>
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<head>
<title>My first PHP Website</title>
</head>
<body>
<h2 align="center">Home Page</h2>
the problem with your code is that you want the header function after html output
I wrote some simple login script for a school assignment. I need to ask the user to log in redirect them to the main page, and display their username on top of the main page. I've been following the instructions I found online, but the username is not shown in the main page after the user logged in. Can someone take a look at my PHP code and give me some hints on how to resolve this? Thanks!
Here is my main php:
<?php
session_start();
echo "You are logged in as " .$_SESSION['username'];
echo "<p>Click here to logout</p>";
//Turn on error reporting
ini_set('display_errors', 'On');
//Connects to the database
$mysqli = new mysqli("abc", "edf","xyz", "123");
if($mysqli->connect_errno){
echo "Connection error: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Test</title>
<meta charset="UTF-8">
<style type="text/css">
body {font-family:sans-serif;}
h1 {color: #0000FF;text-align: center;}
.fieldset-auto-width {display: inline-block;}
</style>
</head>
<body>
<div id="header" style="background-color:#FFA500;">
<h1>Restaurant Review</h1>
</div>
//DO SOMETHING HERE
<div id="content">
<form method="post" action="addreview.php">
</div>
</form>
</body>
</html>
Here is my login php
<?php
ob_start();
$username = $_POST['username'];
$password = $_POST['password'];
//Turn on error reporting
ini_set('display_errors', 'On');
//Connects to the database
$mysqli = new mysqli("abc", "edf","xyz", "123");
if($mysqli->connect_errno){
echo "Connection error " . $mysqli->connect_errno . " " . $mysqli->connect_error;
}
$username = mysqli_real_escape_string($mysqli, $username);
$query = "SELECT password, salt FROM member WHERE username = '$username';";
$result = mysqli_query($mysqli, $query);
// User not found. So, redirect to login_form again.
if (mysqli_num_rows($result) == 0)
{
header('Location: login.html');
}
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);
$hash = hash('cs494', $userData['salt'] . hash('cs494', $password));
//Incorrect password. Redirect to login form again
if ($hash != $userData['password'])
{
header('Location: login.html');
}else {
//redirect to main page after successful login
session_start();
$_SESSION['username'] = $username;
header('Location: main.php');
}
?>
You are echo-ing outside of the HTML document, and it is probably on the page where you cannot see it. If you click View > Source you might see it printed at the top of the document before the <!DOCTYPE> declaration.
Instead of:
echo "You are logged in as " .$_SESSION['username'];
echo "<p>Click here to logout</p>";
<!DOCTYPE html>
<html>...</html>
You should move the echo inside the document like:
<!DOCTYPE html>
<html>
<head>...</head>
<body>
<?php
echo "You are logged in as " .$_SESSION['username'];
echo "<p>Click here to logout</p>";
?>
...
</body>
</html>
header("Location: …" ); does not seem to be working:
<?php
session_start();
if (isset($_SESSION['user'])){
?>
<html>
<head>
<title>
Admin Panel
</title>
</head>
<body>
</body
</html>
<?php
} else {
header("Location: http://echo2.site40.net/cms/admin/login.php" );
}
?>
Seems to be working if I exactly copy paste the code...
Still look for the empty white-spaces before start of the <?php
I have a simple page in HTML/CSS/PHP that connects to MySQL DB.
"index.php" is loaded and "mainPage::showSectionLogin($_SESSION['login'])" shows logging form
<?php session_start(); ?>
<?php require_once 'clMainPage.php'; ?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<HTML>
<HEAD>
<?php mainPage::setSectionHEAD() ?>
<LINK rel="stylesheet" type="text/css" href="style.css">
</HEAD>
<BODY>
<DIV id="sidebar">
<?php mainPage::showSectionLogin($_SESSION['login']) ?>
<?php mainPage::showSidebarMenu($_SESSION['login']) ?>
</DIV>
<DIV id="main">
<?php mainPage::showActualNews(5) ?>
</DIV>
</BODY>
</HTML>
"login.php" is executed after the logging form was filled
<?php session_start(); ?>
<?php require_once 'clMainPage.php'; ?>
<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
$dblink = mainPage::openDBconn();
$result = mainPage::checkIfUserCanLogIn($dblink, $_POST['inpLogin'], $_POST['inpPassw']);
if (mysql_num_rows($result) == 1) {
$row = mysql_fetch_array($result);
mainPage::logUserIn($row['login'], $row['passw']);
}
else
{
die("error checking user: there is no such user in a database");
}
mainPage::closeDBconn($dblink);
header("refresh:1;url=index.php");
} ?>
I don't inderstand why, during logging in, "header("refresh:1;url=index.php");" (line:18) says that "require_once 'clMainPage.php';" in file "login.php" (line:2) sends headers. How is it possible that "require_once 'clMainPage.php';", that is a class declaratin containing only static functions, actually sends headers?
There is white space after your closing php tag on line 1, that's what sends the headers
<?php
session_start();
require_once 'clMainPage.php';
if($_SERVER["REQUEST_METHOD"] == "POST") {
Do you have any whitespace / output before / after your < ?php. This is often the cause.
What does 'clMainPage.php' contain?