how to display an alert after redirect to another page - javascript

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>';
}
}

Related

Automatic password error message on php BEFORE atempting to login

I have created a simple php login form which connects to a database and checks the validity of username and password. If they are correct it allows access if not an error message is displayed. My problem is that when I go to my login page it is automatically giving me an error message saying"invalid user etc" before i have even attempted to login in. Any suggestions as to why this might be?
<?php
session_start();
include('conn.php');
$theUserID = $_POST['userID'];
$theUserPassword = $_POST['password'];
$query = "SELECT userID, firstName, password FROM user INNER JOIN password ON user.passwordID=password.passwordID WHERE userID='$theUserID' AND password='$theUserPassword'";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
if(mysqli_num_rows($result)>0){
//let them in
$_SESSION['myuser40058058']=$theUserID;
Header("Location:index.php");
}
else{
$message = "Incorrect Username or Password";
echo "<script type='text/javascript'>alert('$message');</script>";
}
?>
<?php
session_start();
check if the form was posted and user and password are set
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['userID']) && isset($_POST['password'])){
THIS IS ABSOLUTE UNSECURE !!!
check Paths for include and test values of the form!!
include('conn.php');
$theUserID = $_POST['userID'];
$theUserPassword = $_POST['password'];
THIS IS UNSECURE !!!
use at least a $mysqli->real_escape_string($YOUR_VARIABLES) in the query
$query = "SELECT userID, firstName, password FROM user INNER JOIN password ON user.passwordID=password.passwordID WHERE userID='$theUserID' AND password='$theUserPassword'";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
if(mysqli_num_rows($result)>0){
//let them in
$_SESSION['myuser40058058']=$theUserID;
Header("Location:index.php");
}else{
$message = "Incorrect Username or Password";
echo "<script type='text/javascript'>alert('$message');</script>";
}
}
?>

PHP - Users links

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".

How to manage Php sessions in same page in php

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>

Popup alert script in a php file [duplicate]

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();
}
?>

php login form pass vars

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

Categories

Resources