i have been trying to prevent user that are logged in not to go back to the login page.
please i need your help.
i've tried different method, but yet to no avail. i will be much grateful if anyone can help me. Thanks.
here is my php code for login
<?php
require 'connection.php';
session_start();
$_SESSION['message'] = '';
if(isset($_POST['login']))
{
if(empty($_POST['student']) || empty($_POST['pass']))
{
$_SESSION['message'] = " student id and password is required";
}
else
{
$password = md5($_POST['pass']);
$student = $_POST['student'];
$query= "select studentid, password, status from student_register where studentid='$student' and password='$password'";
$result=mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
if($row)
{
$_SESSION['user']=$_POST['student'];
$_SESSION['stat'] = $row['status'];
$_SESSION['message'] =" Login successfully";
header("refresh:5;url= Welcome.php");
}
else
{
$_SESSION['message'] =" Student id or password is incorrect";
}
}
}
else
{
}
?>
You can add a small code into you login.php file to check the user already login or not.
if (isset($_SESSION['user']))
{
header("LOCATION: Welcome.php");
}
If session is already set, redirect it back to welcome.php.
Use this code for those pages which require login to access the page.
if (!isset($_SESSION['user']))
{
header("LOCATION: login.php");
}
Related
I'm trying to implement Google Signin onto my site. How can I redirect users to logged in members page?
I'm now able to verify the token, after the verification, user should be redirected to loggedin members page, I've tried to use javascript to do so, but it seems to be not working.
I've tried manually type the javascript in the console, login is successful.
<?php
...
require_once 'vendor/autoload.php';
$client = new Google_Client();
$client->setScopes('email');
$payload = $client->verifyIdToken($id_token);
if ($payload == true) {
$userid = $payload['sub'];
//check user existance
if ($check_googleuser_result->num_rows == 1) {
$_SESSION['loggedin_userlogin'] = $email;
//redirect user
echo '<script>window.location = "loggedin.php";</script>';
} else {
echo 'No matched user';
//signout user
echo '<script>location.replace("gsignout.php");</script>';
}
} else {
echo 'error';
//signout user
echo '<script>location.replace("gsignout.php");</script>';
}
?>
Expected to redirect the user after successful check existence of user.
Actual output is that the session is created, but javascript not performing redirection.
UPDATE:Screenshot of background1
Screenshot of background2
As you are trying to redirect in your php code, you should also use the php provided functions for that.
For this there is a function called header()
So your code would look like this:
<?php
...
require_once 'vendor/autoload.php';
$client = new Google_Client();
$client->setScopes('email');
$payload = $client->verifyIdToken($id_token);
if ($payload == true) {
$userid = $payload['sub'];
//check user existance
if ($check_googleuser_result->num_rows == 1) {
$_SESSION['loggedin_userlogin'] = $email;
//redirect user
header('Location: loggedin.php');
} else {
echo 'No matched user';
//signout user
header('Location: gsignout.php');
}
} else {
echo 'error';
//signout user
header('Location: gsignout.php');
}
?>
login form (index.php) was already created. when form is submitted username and password are passed in to another page (login-controller.php). after verifying, if username or password is incorrect user was redirected to login form(index.php) after display the alert box in login-controller.php.but i want to display an alert box like "invalid login credentials" after redirect to login form(index.php). how can i solve this. code of login-controller.php are given bellow.
<?php
session_start();
if (isset($_SESSION['username'])) {
header('Location: ../service/index.php');
}
include '../include/conn.php'; //database connection
if (isset($_POST["submit"])) {
if (empty($_POST["username"] && $_POST["password"])) {
header('Location: index.php');
} else {
$username = mysqli_real_escape_string($conn, $_POST["username"]);
$password = mysqli_real_escape_string($conn, $_POST["password"]);
$password = md5($password);
$sqli = "SELECT * FROM user WHERE name = '$username' AND password = '$password'";
$result = $conn->query($sqli);
$count = mysqli_num_rows($result);
if ($count == 1) {
$_SESSION['username'] = $username;
header('Location: ../service/index.php');
} else {
include '../include/bootstrap.php'; //bootstrap js and css
echo '<div class="alert alert-danger"><strong>Oops!</strong> Invalid Login Credentials.</div>';
echo "<script>setTimeout(\"location.href = 'index.php';\",3000);</script>";
}
}
}
?>
Using session variables you can display alerts:
$_SESSION['alerts'][] = "Test Alert";
$_SESSION['alerts'][] = "Another Test Alert";
Then in your config, or any other .php file that gets executed on every page that you have ( If you have a templating system, do that in the template) do this:
if(isset($_SESSION['alerts'])){
foreach($_SESSION['alerts'] as $alertmessage){
echo '<div class="alert">' . $alertmessage . '</div>';
}
}
So I am using AJAX in a hybrid app to authenticate a user and also start a php session.
The app has public sections and a user account section. I wanted that when someone logs in they can go to the public sections and return to the user sections without being logged out.
So I wrote an AJAX request that is triggered when a user clicks the user section icon to check for sessions. If there is one then the js must load the user home page. If there is none the js must load the login page.
However when the user logs in and tries to return to the user home page the session checking script says the server says there is no session variable set. Below is the code.... First the login then the session checking code.
login.php
<?php
require("session.php");
header('Access-Control-Allow-Origin: *');
if($_SERVER['REQUEST_METHOD'] == "POST")
{
require("dbconnect.php");
$inv = sanity($_POST['inv']);
$acc = sanity($_POST['acc']);
$pass = sanity($_POST['pass']);
$query = "SELECT loginid FROM login WHERE institution_id = '$inv' AND username = $acc AND password = '$pass'";
$result = mysqli_query($db_conn, $query);
if(mysqli_num_rows($result) > 0)
{
$row = mysqli_fetch_assoc($result);
$_SESION['id'] = $row['loginid'];
echo "1";
}
else
echo "0";
}
function sanity($data)
{
$var = htmlspecialchars($data);
$var = trim($var);
return $var;
}
?>
confirm.php
<?php
require("session.php");
header('Access-Control-Allow-Origin: *');
if($_SERVER['REQUEST_METHOD'] == "GET")
{
if(isset($_SESSION['id']))
echo "1";
else
echo "0";
}
?>
the confirm script is returning zero though the login script returns 1
note that the session.php file does exist
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am trying to let a user log in. If the password and username is wrong, I want a popup to appear alerting the user on the error. When they close the alert, it goes back to index.php which is back to login screen.
But when it is wrong password/username, ends up going back to index.php without any popup messages first. My browser setting is not blocking any popups. Can I know what I'm doing wrong please.
<?php
if($login == true){
//Do login process
//this portion works as long as correct username and password
}
else{
echo '<script language="javascript">alert("Please enter valid username and password");</script>';
header("location:index.php");
}
?>
//login.php
<?php
$username = "exampleuser";
$password = "examplepass";
$host = "localhost";
$dbHandle = mysql_connect($host, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("database_name", $dbHandle);
$myUserName = $_POST['user'];
$myPassword = $_POST['pass'];
if(ctype_alnum($myUserName) && ctype_alnum($myPassword)){
$query1 = "SELECT * FROM users WHERE username='$myUserName'";
$result1 = mysql_query($query1);
$count1 = mysql_num_rows($result1);
if($count1 == 1){
$query2 = "SELECT password FROM users WHERE username='$myUserName'";
$result2 = mysql_query($query2);
$row = mysql_fetch_array($result2, MYSQL_ASSOC);
$pass = $row['password'];
if(password_verify($myPassword, $pass)){
$seconds = 120 + time();
setcookie(loggedIn, date("F js - g:i a"), $seconds);
header("location:mysite.php");
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
?>
If you send headers to php it goes directly on index.php after the page goes in your condition.
If you try this code:
<?php
if($login == true){
//Do login process
//this portion works as long as correct username and password
}
else{
echo '<script language="javascript">
alert("Please enter valid username and password");
window.location.href = "http://index.php";
</script>';
die();
}
you will see that your code is correct. You need to track an event on popup closing to redirect to index.php via ajax or via http redirect.
EDIT 1:
Here you have a complete page with pdo. This is not the best way to do the job but it works. As you will see in the comments you have to avoid xss attacks and you should change database structure saving password hashed and salt to hide the users' clear password.
Here's the code.
<?php
//login.php
//connection via PDO
try{
$pdo = new PDO ('mysql:host=localhost; dbname=database_name', 'exampleuser' , 'examplepass', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
//alert errors and warnings
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
exit('Database Error.');
}
//prepared statements sanitize input binding parameters, for you but you can use some libraries to prevent sql injection
$myUserName = trim(filter_var($_POST['user'], FILTER_SANITIZE_STRING));;
$myPassword = trim(filter_var($_POST['pass'], FILTER_SANITIZE_STRING));;
if(!empty($myUserName) && ctype_alnum($myUserName) && !empty($myPassword) && ctype_alnum($myPassword)){
$query1 = $pdo->prepare("SELECT password FROM users WHERE username = :username_param");
//bind parameter avoiding principal injection (pdo does not cover xss attacks, avoid it with other methods)
$query1->bindParam("username_param", $myUserName);
$result = $query1->fetch();
// or you can do $result = $query1->fetchColumn(); to get directly string instead of array
if($result['password']){
//you should use password_verify() if you have an hash stored in database, you should not save password in database.
//please google about best practice storing password, it's full of beautiful guides
//bad practice but will do the work
if($myPassword == $result){
$seconds = 120 + time();
setcookie('loggedIn', date("F js - g:i a"), $seconds);
header("location:mysite.php");
}else{
printAlert("Password incorrect");
}
}else{
printAlert("Username not valid");
}
}
else{
printAlert("Invalid data");
}
function printAlert($text){
echo "<script language='javascript'>
alert('$text');
window.location.href = 'http://index.php';
</script>";
die();
}
?>
i have a page login
in page have html form with textboxes and submit button
and in top of page i have PHP code thet chacke if name and password in database
if name and password in database page go to new page and pass the name and password to next page
i can do it with get metod like the vars in the URL
but i want to pass and go to new page with Post metod
how i can do it??
pleas help me with code....
in code html :
form name="frmlogin"action="<?= $_SERVER['PHP_SELF'] ?>" method="post" >
and in top of the page have PHP code:
$msg = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST["name"];
$password = $_POST["password"]; if ($name == '' || $password == '') {
$msg = "You must enter all fields";
} else {
$sql = "SELECT * FROM tbluser WHERE fldUsername = '$name' AND fldPass = '$password'";
$query = mysql_query($sql);
if ($query === false) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($query) > 0) {
/*header('Location: YOUR_LOCATION');
exit;*/
$msg = "Username and password match";
echo '<script type="text/javascript">
window.location.href = "smartphon100.php?name='. $name .'&password='. $password .'";
}
if (mysql_num_rows($query) <= 0) {
$msg = "Username and password do not match";
}
}
}
help me to change the javascript window.location to post metod
You can go for php redirect also.
header('location:smartphon100.php?name='. $name .'&password='. $password) ;
BTW: you are passing password in browser?
If I understand correctly, you're trying to redirect a user after successfully logging in.
I see that your current code attempts to redirect using Javascript, the issue seems to be with the quotes on the value you tried to enter.
Try to change this line:
window.location.href = "smartphon100.php?name='. $name .'&password='. $password .'";
to this:
window.location.href = "smartphon100.php?name='.$name.'&password='. $password";
Overall you should read about security as the code you presented is very vulnerable.
PHP: SQL Injection - Manual
If you're trying to pass the values to another page in a POST method using Javascript, you could take a look at this answer:
JavaScript post request like a form submit
Although as I don't see a reason for posting the values more than once,
I recommend you to read about PHP sessions, cookies, and encryption, which allow you to store values that you can use across the website securely.
A simple example to using session:
<?php
//Starts the session, you need to use this line in every PHP file that'll need to access session variables
session_start();
$_SESSION['user'] = "Donny"; //Storing a user name
?>
A simple example of session use with your code:
Foo.php
session_start();
$msg = "";
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST["name"];
$password = $_POST["password"]; if ($name == '' || $password == '') {
$msg = "You must enter all fields";
} else {
$sql = "SELECT * FROM tbluser WHERE fldUsername = '$name' AND fldPass = '$password'";
$query = mysql_query($sql);
if ($query === false) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($query) > 0) {
$_SESSION['user'] = $name;
$_SESSION['pass'] = $password;
$msg = "Username and password match";
echo '<script type="text/javascript">window.location.href = "smartphon100.php";</script>';
}
if (mysql_num_rows($query) <= 0) {
$msg = "Username and password do not match";
}
}
}
Bar.php
<?php
session_start();
//Accessing the values:
echo $_SESSION['user'];
echo $_SESSION['pass'];
?>
NOTE:
It's not good to store values like that as again, they're not secure, please read about hashing passwords.
PHP: Password Hashing