I have a Index page in Php and a login link. When user login to the site then i want to redirect to the same page (index.php). At the place of login link I want to show the username of the user or client. I have a php login code like this
$error = '';
if (isset($_POST['login']) && !empty($_POST['email'])
&& !empty($_POST['password'])) {
$email = $_POST['email'];
$password = $_POST['password'];
$sel_user = "select * from customer where email='$email' AND password='$password'";
$run_user = mysql_query($sel_user);
$check_user = mysql_num_rows($run_user);
if($check_user == 1){
$_SESSION['email']=$email;
echo "<script>window.open('userinfo.php','_self')</script>";
}
else {
$error = 'Invalid username or password';
}
}
in this code page is redirecting to another page after login but i want to redirect it to same page as index.php. And add links like my account and logout links instead of login link in index.php. I have a Php sessions page code like this
if(!isset($_SESSION))
{
session_start();
}
$login_session=$_SESSION['email'];
if(!isset($_SESSION['email']))
{
// not logged in
header('Location: login.php');
exit();
}
How can i make this for example like flipkart.com. Please help me.
You can do one thing:
Go for the code that you have already written for the login, i.e.,
$error = '';
if (isset($_POST['login']) && !empty($_POST['email'])
&& !empty($_POST['password'])) {
$email = $_POST['email'];
$password = $_POST['password'];
$sel_user = "select * from customer where email='$email' AND password='$password'";
$run_user = mysql_query($sel_user);
$check_user = mysql_num_rows($run_user);
if($check_user == 1){
$_SESSION['email']=$email;
echo "<script>window.open('userinfo.php','_self')</script>";
}
else {
$error = 'Invalid username or password';
}
}
After this you do a check of the session variable
if(!isset($_SESSION))
{
session_start();
}
$login_session=$_SESSION['email'];
if(!isset($_SESSION['email']))
{
// not logged in
header('Location: index.php'); //change the redirect page to index.php
//now customize the menu accoringly
echo "<nav class='your-class'>";
echo "<li>";
echo "<ul>Login</ul>";
//Some more menus
echo "</nav>";
exit();
}
else
{
header('Location: index.php'); //now configure the menu accordingly
//now customize the menu accoringly on login
echo "<nav class='your-class'>";
echo "<li>";
echo "<ul>My Account</ul>";
//Some more menus
echo "<ul>Logout</ul>";
echo "</nav>";
}
But as far as I know this is somewhat tiresome and please try to avoid the queries like this. Use PDO instead. Thanks.
Try this
header('location:'.$_SERVER['PHP_SELF']);
instead of
echo "<script>window.open('userinfo.php','_self')</script>";
and for manage links
<ul>
<?php if(isset($_SESSION['email'])){ ?>
<li><a href="logout.php" >Logout</a></li>
<?php }else{ ?>
<li><a href="index.php" >Home</a></li>
<?php }?>
</ul>
Related
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");
}
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>';
}
}
I have created a registration & login system, it is working properly.
But, I only knew how to make a register & login system, I don't know how to make a link for every registered user
like :
example.com/marwan
example.com/user/marwan
Here is my Register PHP Code :
<?php
error_reporting(0);
session_start();
if( isset($_SESSION['user_id']) ){
header("Location: /");
}
require 'includes/database.php';
$message = '';
if(!empty($_POST['email']) && !empty($_POST['password'])):
// Enter the new user in the database
$sql = "INSERT INTO users (full_name, email, password, phone, country) VALUES (:full_name, :email, :password, :phone, :country)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':full_name', $_POST['full_name']);
$stmt->bindParam(':email', $_POST['email']);
$stmt->bindParam(':password', password_hash($_POST['password'], PASSWORD_BCRYPT));
$stmt->bindParam(':phone', $_POST['phone']);
$stmt->bindParam(':country', $_POST['country']);
if( $stmt->execute() ):
header("Location: account-created.php");
else:
header("Location: failed.php");
endif;
endif;
?>
And my Login code is :
<?php
session_start();
if( isset($_SESSION['user_id']) ){
header("Location: /tregolapp/home");
}
require 'includes/database.php';
if(!empty($_POST['email']) && !empty($_POST['password'])):
$records = $conn->prepare('SELECT id,email,password FROM users WHERE email = :email');
$records->bindParam(':email', $_POST['email']);
$records->execute();
$results = $records->fetch(PDO::FETCH_ASSOC);
$message = '';
if(count($results) > 0 && password_verify($_POST['password'], $results['password']) ){
$_SESSION['user_id'] = $results['id'];
header("Location: /tregolapp/index.php");
} else {
header("Location: /tregolapp/failed");
}
endif;
?>
Can someone help me please?
What is your purpose in giving each user their "own URL"?
If you want each user to see their "own information" upon login, then after login go to a common "home page" while holding a session id. Use that id to pull "user specific" data from your database and display it on the "home page".
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