I am making a panel with PHP. It contains a login script. It's working good, just what I expect. The next step is: Echo the username.
With $_POST you can echo the username what the person has typed. So, just like: Welcome, $username.
The problem now is, that I can't echo the $_POST. It's not possible because you will redirect to another page. My question is: How can I echo a username.
My login script:
<?php
//DATABASE CONNECTION
session_start();
$host = "localhost";
$username = "root";
$password = "root";
$database = "test_tutorial";
$message = "";
try {
$connect = new PDO("mysql:host=$host; dbname=$database", $username, $password);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$fname = $_POST["fname"];
//LOGIN CHECK
if(isset($_POST["login"])) {
if(empty($_POST["fname"]) || empty($_POST["lname"])) {
echo 'All fields required';
}
else
{
$query = "SELECT * FROM users WHERE fname = :fname AND lname = :lname";
$statement = $connect->prepare($query);
$statement->execute(
array(
'fname' => $_POST["fname"],
'lname' => $_POST["lname"]
)
);
$count = $statement->rowCount();
if($count > 0)
{
//VISITED
header("Refresh:0; url=veilig.php");
//END
}
else
{
echo 'Wrong data';
}
}
}
}
catch(PDOException $error) {
$message = $error->getMessage();
}
?>
My form:
<form action="" method="post">
<label>fname</label>
<input type="text" name="fname" class="form-control" />
<br />
<label>lname</label>
<input type="password" name="lname" class="form-control" />
<br />
<input type="submit" name="login" value="Login" />
</form>
So, how can I echo a post if someone is redirected to another page?
You've already called session_start so you're ready to use the $_SESSION superglobal which will persist data for the user across all pages that call session_start first.
For example, here on index.php
<?php
session_start();
$_SESSION['username'] = 'Prabhjot.Singh';
header('Location: veilig.php');
Then later on veilig.php
<?php
session_start();
echo $_SESSION['username'];
Prabhjot.Singh
Related
Why do i get this when i print my session :
Array ( [name] => [pass] => ) ?
Below is my code
My main page for user to input, login.php:
<form action="" method="post">
<div class="imgcontainer">
<img src="KBR2xN6.jpg" alt="Avatar" class="avatar">
</div>
<div class="container">
<label><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="name" required>
<br />
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="pass" required>
<button type="submit">Login</button>
<button type="reset" class="cancelbtn">Reset</button>
</div>
</form>
To connect to local server, connections.php:
$host = "localhost";
$username = "root";
$password = "";
$database = "netbook 1 malaysia";
try {
$connect = new PDO("mysql:host=$host; dbname=$database", $username, $password);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $ex) {
echo 'Connection Failed : '.$ex->getMessage();
}
My session page, session.php:
session_start();
include('connections.php');
$username = $_POST['name'];
$password = $_POST['pass'];
$sql = "SELECT * FROM pengguna WHERE username = '$username' AND password = '$password'";
$result = $connect->query($sql);
if($result->rowcount()>0){
foreach($result AS $data){
$_SESSION['name'] = $data['name'];
$_SESSION['pass'] = $data['pass'];
echo "<script>alert('Login Success');
window.location.href='view.php';
</script>";
}
}
else {
echo "<script>alert('Login Failed');
window.location.href='login.php';
</script>";
}
Maybe my database failed ?
$result contains a resource, not database data directly.
When we expected just one row form database, no loop is needed. Using a loop you'll have just on name/pass in session, it'll be overwritten in your code for the last one.
$data = $result->fetch_assoc();
$_SESSION['name'] = $data['name'];
$_SESSION['pass'] = $data['pass'];
print_r($_SESSION);
Note that there is no reason to store password in session, the same as store password in database as a plaintext.
Where you print session array? if you print session on view.php file then make sure to start session on view.php file.
<?php
if(isset($_POST["submit"])){
require 'Config.php';
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$Name = $_POST['Name'];
$Password = $_POST['Password'];
$message ="";
$stmt = $conn->prepare("SELECT COUNT(*) FROM user WHERE Name='$Name' and Password='$Password'");
$stmt->execute();
$result = $stmt->fetchcolumn();
if($result > 0)
{
$_SESSION['Logged In'] = $Name;
$_SESSION['Logged In'] = $Password;
if(isset($_SESSION['Logged In']))
{
echo $result;
session_start();
header('Location: Main.php');
exit();
}
}
elseif($result == 0)
{
echo $result;
echo "Invalid Username or Password";
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$conn = null;
}
?>
i need help with this simple login system if i comment out the header redirect the echo result shows i am only getting 1 result as expected when i put the redirect in the page just refreshes instead of going to the next page.
There are a few simple issues in this code
First you must start the session before you do anything with it. In fact its best to start it at the top of every script before doing anything else.
Also because you have echoed something to the browser before you have run the header, this will be a probelm. Headers have to be sent before any page data.
Also your code is liable to SQL Injection so use prepared and parameterised queries to avoid this.
You also appear to be storing a plain text password in the database. another big No No
PHP provides password_hash()
and password_verify() please use them.
And here are some good ideas about passwords
If you are using a PHP version prior to 5.5 there is a compatibility pack available here
<?php
session_start();
if(isset($_POST["submit"])){
require 'Config.php';
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try {
$stmt = $conn->prepare("SELECT Password
FROM user
WHERE Name=:name");
$params = array(':name'=>$_POST['Name'])
$stmt->execute($params);
$hashedPassword = $stmt->fetchcolumn();
if(password_verify($_POST['Password'], $hashedPassword) ) {
$_SESSION['Logged In'] = $_POST['Name'];
// bad idea putting password in a session
//$_SESSION['Logged In'] = $Password;
// you just set this data so the if is unnecessary
//if(isset($_SESSION['Logged In'])) {
// cannot echo anything before doing a header()
// any way if the header works you wont see this data
// anyway as a new page will be being loaded
//echo $result;
header('Location: Main.php');
exit;
} else {
echo $result;
echo "Invalid Username or Password";
}
catch(PDOException $e) {
echo $e->getMessage();
}
$conn = null;
}
?>
As this now uses a hashed password, you will have to recreate your users and when tou do, use
$passwordToPutOnDatabase = password_hash($thepassword);
There are may issues with your code, you are storing passwords in plain text which is completely wrong, you should use password_hash() and password_verify()
I have made you a simple login/register script which will show you how to use the password_hash and password_verify()
simple_register.php
<?php
require 'db_config.php';
if(isset($_POST['register'])){
//validate email and password I'm not gonna do that for you
$password = $_POST['upass']; // when u done with validation
$email = $_POST['username'];
$hash = password_hash($password,PASSWORD_DEFAULT); //hash password
try {
$stmt = $conn->prepare("INSERT INTO users (username,password) VALUES ( ?,?)");
if($stmt->execute(array($email,$hash))){
echo "user registered";
}else{
echo "could not register"; // something wrong with your query check error log
}
} catch (Exception $e) {
error_log($e->getMessage());
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Simple PDO Registration</title>
</head>
<body>
<form method="POST" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<p><input type="email" name="username" placeholder="Enter your email"></p>
<p><input type="password" name="upass" placeholder="Enter password"></p>
<button type="submit" name="register">Register</button>
</form>
</body>
</html>
login.php
<?php
ob_start();
session_start();
require 'db_config.php';
if (isset($_SESSION['loggedin'])) {
header("location:users/dashboard.php");
} else {
$loginMessage = "";
$msg_class = "";
if (isset($_POST['login'])) {
if (empty($_POST['email']) || empty($_POST['upass'])) {
$loginMessage = "Enter username and password";
$msg_class = "error";
} else {
$username = $_POST['email'];
$password = $_POST['upass'];
try {
$stmt = $conn->prepare("SELECT userID,username,password FROM users where username = ? ");
$stmt->execute([$username]);
$results = $stmt->fetchall(PDO::FETCH_ASSOC);
if (count($results) > 0) {
foreach ($results as $row):
if (password_verify($password, $row['UserPassword'])) {
$_SESSION['loggedin'] = $row['userID'];
$loginMessage = "Login Successfully! Redirecting...";
$msg_class = "success";
header("refresh:5; url=dashboard");
} else {
$loginMessage = "Password and username does not match";
$msg_class = "error";
}
endforeach;
} else {
$loginMessage = "Invalid username";
}
}
catch (PDOException $e) {
error_log($e);
}
}
}
}
?>
</head>
<body>
<div id="main">
<h1>User Login</h1>
<div class="row">
<div class="large-6 columns large-centered" id="box">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<label>Email</label>
<input type="text" name="email" class="input" >
<label>Password </label>
<input type="password" name="upass" class="input" id="password"/><br/>
<div class="large-6 columns pull-2">Forgot Password</div>
<button type="submit" class="button" name="login" disabled="true" id="long">Login</button>
<div class="<?php echo $msg_class;?>">
<?php
echo $loginMessage;
?>
</div>
</form>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#password').keyup(function(e){
$('#long').prop('disabled', false);
});
});
</script>
</div>
db_config.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "samedicalspecialists";
try {
$conn= new PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
error_log($e);
}
?>
I've been looking at my code for days, but can't seem to find the problem. I'm new in PHP, so I'm not really familiar with all of it.
Below is my code. No errors. No registered session variable values.
db-config.php
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'mcsh';
$conn = mysqli_connect($host, $user, $pass, $db);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
login.php
<form id="user-login" action="index.php" method="POST">
<h1>Administrator Login</h1>
<input type="text" name="username" placeholder="Username" required/>
<input type="password" name="password" placeholder="Password" required/>
<button type="submit">Login</button>
Forgot your password?
</form>
<?php
if (!empty($_POST)) {
if (!empty($_SESSION['username'])) {
header("Location: index.php");
}
$username = $_POST['username'];
$password = $_POST['password'];
include("../config/db-config.php");
$sql = "SELECT `userid`, `password` FROM users WHERE userid = '" . $username . "' AND userlevel = '99'";
$result = mysqli_query($conn, $sql);
if ($row = mysqli_fetch_assoc($result)) {
if (password_verify($password, $row['password'])) {
$_SESSION['username'] = $row['userid'];
header("Location: index.php");
exit;
}
else {
?>
<p class="msg" id="error">Invalid username or password. Please try again.</p>
<?php
}
}
else {
?>
<p class="msg" id="error">Invalid username or password. Please try again.</p>
<?php
}
}
?>
index.php
<?php
session_start();
include("../config/config.php");
if (empty($_SESSION['username'])) {
header("Location: login.php");
}
else {
//the rest of the index page...
?>
Your form in login.php submits to index.php. In index.php, if the username is not yet in the session, you are redirected back to login.php. There you check if (!empty($_POST)) { at the beginning of your PHP code.
$_POST will be empty, because you have redirected to that page, not POSTed to it, so the PHP code will not be executed.
Remove the action="index.php" and that form will submit to itself (login.php). Also, move the HTML form code below the PHP code so that you will not have output before the redirect header if the login is successful.
I have a little problem with my Login & Register System but I don't know where the problem is. When I press "Login" or "Register", the next page is white. I see only my message: "Try again!". I made 3 PHP files:
1) index.php
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="logreg.php" metodh="post" accept-charset="utf-8">
<label>Username:</label><input type="text" name="username" placeholder="Username">
<br>
<label>Password:</label><input type="password" name="password" placeholder="Password">
<br>
<input type="submit" name="login" value="Login">
<input type="submit" name="register" value="Register">
</form>
</body>
</html>
I think the problem is in the next file:
2) logreg.php
<?php
$servername = "localhost";
$username = "alex";
$password = "calamar28";
$database = "register/login";
$conn = mysqli_connect($servername, $username, $password, $database );
if(!$conn){
die("Connection failde:".mysqli_connect_error());
}
if(isset($_POST["login"])) {
$user = $_POST['username'];
$pass = $_POST['password'];
$sql = "SELECT * FROM users WHERE username='$user' AND password='$pass';";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if ($count == 1)
{
header("Location: personal.php");
}
else
{
echo "Username or password is incorrect!";
}
}
else if(isset($_POST["register"])) {
$user = $_POST['username'];
$pass = $_POST['password'];
$sql = "INSERT INTO users (id, username, password) VALUES ('', '$user', '$pass')";
$result = mysqli_query($conn, $sql);
}
else
{
echo "Try again!";
}
?>
3) personal.php
<?php
if(isset($_POST["login"])){
echo "Welcome to you personal area !";
echo 'Your proiect';
}
else
{
echo "You are not logged in!";
}
?>
You will also need to set some session variables to carry through onto the personal.php page... This will help determine if the user has logged in successfully or not as the original posted data won't be transferred through when you redirect to this page... You'll want your logreg.php to be the following:
<?php
if (!isset($_SESSION)) {session_start();}
$servername = "localhost";
$username = "alex";
$password = "calamar28";
$database = "register/login";
$conn = mysqli_connect($servername, $username, $password, $database );
if(!$conn){
die("Connection failde:".mysqli_connect_error());
}
if(isset($_POST["login"])) {
$user = $_POST['username'];
$pass = $_POST['password'];
$sql = "SELECT * FROM users WHERE username='$user' AND password='$pass';";
$result = mysqli_query($conn, $sql);
$count = mysqli_num_rows($result);
if ($count == 1)
{
$_SESSION['loggedIn'] = 1;
header("Location: personal.php");
}
else
{
echo "Username or password is incorrect!";
}
}
else if(isset($_POST["register"])) {
$user = $_POST['username'];
$pass = $_POST['password'];
$sql = "INSERT INTO users (id, username, password) VALUES ('', '$user', '$pass')";
$result = mysqli_query($conn, $sql);
}
else
{
echo "Try again!";
}
?>
And then your personal.php page will change to the following:
<?php
if (!isset($_SESSION)) {session_start();}
if(isset($_SESSION["loggedIn"]) && ($_SESSION["loggedIn"] == 1) ){
echo "Welcome to you personal area !";
echo 'Your proiect';
}
else
{
echo "You are not logged in!";
}
?>
The Default Method for HTML Forms is GET. And in your HTML Code you wrote metodh instead of method. This would be ignored and then your method would automatically default to GET. Other than this, your PHP Code is fine.
Change your HTML Code to look something like below and everything should work fine as expected:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="logreg.php" method="post" accept-charset="utf-8">
<label>Username:</label><input type="text" name="username" placeholder="Username">
<br>
<label>Password:</label><input type="password" name="password" placeholder="Password">
<br>
<input type="submit" name="login" value="Login">
<input type="submit" name="register" value="Register">
</form>
</body>
</html>
My script doesn't saves the value into a $_SESSION, how is that possible?
Whenever my users login, i try to place their username into a session.
My only problem is when i use var_dump($_SESSION['user_name']); to debug and reveal the current value on the end page, i just keep receiving NULL.
Could someone help me out?
Here is my code:
<? php
include_once('../db/config.php');
session_start();
$error = '';
if (isset($_POST['submit'])) {
if (empty($_POST['isamp_username']) || empty($_POST['isamp_password'])) {
$error = "Username or Password is invalid!";
} else {
$isamp = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$username = stripslashes($username);
$password = stripslashes($password);
$username = $isamp - > real_escape_string($username);
$password = $isamp - > real_escape_string($password);
$username = $_POST['isamp_username'];
$nopassword = $_POST['isamp_password'];
$password_hash = hash('whirlpool', $nopassword);
$password = strtoupper($password_hash); // <- Also for the Register!
$sql = "select * from users where password='$password' AND username='$username'";
$result = $isamp - > query($sql) or trigger_error($isamp - > error." [$sql]"); /* i have added the suggestion from MY Common Sence */
if ($result - > num_rows == 1) {
$_SESSION['user_name'] = $username;
header("Location: ../../index.php");
} else {
$error = "Username or Password is invalid!";
}
$isamp - > close();
}
} ?>
My HTML:
<?php
include('login.php');
?>
<h2>iSAMP</h2>
<hr/>
<form action="" method="post">
<label>Username :</label>
<input type="text" name="isamp_username" id="name" placeholder="Username"/><br /><br />
<label>Password :</label>
<input type="password" name="isamp_password" id="isamp_password" placeholder="*******"/><br/><br />
<input type="submit" value=" Login " name="submit"/><br />
<span><?php echo $error; ?></span>
</form>
In your first php script, move the session_start() above the include statement.
In your html file, add session_start(); above the include statement.