when I click login it loads home.php on index.php and looks very strange.. is it possible to make it redirect or erase everything on index.php then load home.php
function login(){
var name = $('input#answer').val();
var pass = $('input#password').val();
if( $(name) == '' || $(pass) == '' )
$('#output').html('Please enter both username and password.');
else
$.post( ('php/login.php'), $('#myForm :input').serializeArray(),
function(data){
$('#output').html(data);
});
$('#myForm').submit(function(){
return false;
});
};
<?php
session_start();
if(isset($_SESSION['users']) != ""){
header("Location: ../php/home.php");
}
require '../php/dbConnect.php';
$username = $_POST['username'];
$password = $_POST['password'];
$query = ("SELECT * FROM `accounts` WHERE username = '$username'")or die(mysql_error());
$response = mysql_query($query);
$row = mysql_fetch_array($response);
if($row['password'] == md5($password))
{
$_SESSION['user'] = $row['username'];
header("Location: ../php/home.php");
}
else{
echo("Wrong Credentials");
}
?>
Perhaps try:
$_SESSION['user'] = $row['username'];
header("Location: ../php/home.php");
die();
You usually need to issue a die() command after the header() statement.
Related
I'm doing a login with ajax, html and php.
I've already debbuged the php, it's ok and it's returning the json variable I need in the ajax call.
I have this ajax function:
$(document).ready(function(){
$('#login').submit(function() {
var username=$("#username").val();
var password=$("#password").val();
$.ajax({
url: 'login.php',
data: {
username: username,
password: password
},
type: 'post',
dataType: 'json',
success:function(response){
alert(response);
if(response.validacion == "ok"){
alert("Bienvenidos"),
localStorage.loginstatus = "true",
window.location.assign("home.php");
}
if(response.validacion == "error"){
window.location.assign("login.html"),
alert("Datos de usuario incorrectos, inténtelo nuevamente");
}
}
});
});
});
This is the login.php code: (I know it's really bad save password in cookies, but this is my solution for now)
<?php
session_start();
?>
<?php
include 'conexion.php';
if(isset($_POST['username'] && $_POST['password'])){
$username = $_POST['username'];
$password = $_POST['password'];
}
$sql = "SELECT * FROM User WHERE username = '$username' OR Email ='$username'";
$result = $connection->query($sql);
if ($result->num_rows > 0) {
$row = $result->fetch_array(MYSQLI_ASSOC);
$hash = $row['password'];
if (password_verify($password, $hash)) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $row['username'];
$_SESSION['start'] = time();
setcookie("COOKIE_INDEFINED_SESSION", TRUE, time()+31622400);
setcookie("COOKIE_DATA_INDEFINED_SESSION[username]", $username, time()+31622400);
setcookie("COOKIE_DATA_INDEFINED_SESSION[password]", $password, time()+31622400);
echo "Sesión abierta indefinidamente.<br/>";
$respuesta["validacion"] = "ok";
$respuesta["id"] = $row["idUser"];
$respuesta["username"] = $row["username"];
}else{
$respuesta["validacion"] = "error";
$respuesta["mensaje"] = "Contraseña incorrecta";
}mysqli_close($connection);
}else{
$respuesta["validacion"] = "error";
$respuesta["mensaje"] = "Usuario incorrecto";
}mysqli_close($connection);
// encoding array to json format
echo json_encode($respuesta);
?>
I did and inspect element, the username and password are ok, login.php is called, but when I continue the inspection from the line 20, this works until the line 25 aprox and skips to the line 44, the success:function(function) is skipped and the "response" variable is undefined but the login.php is returnint this variable ok:
What am I doing wrong? (sorry for my english, I'm spanish speaker)
Ok, I've solved the problem so I'm going to post what I've done for those who have the same problem:
the function success:function(response) is taking ALL the "echo" from the login.php, so the first "echo" when the login is ok, is the trouble and response become an undefined var.
When I post with the wrong credentials, I only have one echo (the json_encode) and I had not problem with the ajax. So the solution will be this, in the php, after the if(password_verify):
if (password_verify($password, $hash)) {
$_SESSION['loggedin'] = true;
$_SESSION['username'] = $row['username'];
$_SESSION['start'] = time();
setcookie("COOKIE_INDEFINED_SESSION", TRUE, time()+31622400);
setcookie("COOKIE_DATA_INDEFINED_SESSION[username]", $username, time()+31622400);
setcookie("COOKIE_DATA_INDEFINED_SESSION[password]", $password, time()+31622400);
$respuesta["validacion"] = "ok";
$respuesta["id"] = $row["idUser"];
$respuesta["username"] = $row["username"];
}else{
$respuesta["validacion"] = "error";
$respuesta["mensaje"] = "Contraseña incorrecta";
}
}else{
$respuesta["validacion"] = "error";
$respuesta["mensaje"] = "Usuario incorrecto";
}
mysqli_close($connection);
// encoding array to json format
echo json_encode($respuesta);
?>
In order to get the value from the response, you need to JSON.parse() it first to allow your self to use response.validacion
index.php
<script>
$(document).ready(function(){
$("#login").click(function(e){
e.preventDefault();
email = $("#cs-username-1").val();
password = $("#cs-login-password-1").val();
if(email=='' || password=='')
{
$("#loginsuccess").html("<p id='red'>All fields are mandatory!<p>");
}
else
{
$.ajax({
type:"POST",
data:{"email":email,"password":password},
url:"login.php",
success: function(data)
{
if (typeof data !== 'object') {
data = JSON.parse(data);
}
if (data.redirect) {
window.location.replace(data.redirect);
} else {
$("#loginsuccess").html('<p id="red">' + data.error + '</p>');
}
}
});
}
});
});
</script>
login.php
<?php
include("config.php");
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = md5($_POST['password']);
$sql = mysqli_query($con,"select student_id from student where email='".$email."' and password='".$password."' and status='1'");
if (mysqli_num_rows($sql) > 0)
{
$results = mysqli_fetch_array($sql);
$_SESSION['student'] = $results['student_id'];
if (!isset($_POST))
{
header ("Location: dashboard.php");
}
else
{
echo json_encode(array('redirect' => "dashboard.php"));
}
}
else
{
echo json_encode(array('error' => 'Wrong email or password or may be your account not activated.'));
}
?>
dashboard.php
<?php
session_start();
echo $_SESSION['student'];
/*if(!isset($_SESSION['student']))
{
header("location: index.php");
}*/
include('assets/db/config.php');
?>
In this code I am simply create login module. Here, what happen I am create login via jQuery where I have login.php file and I am storing student_id inside the session variable but when I redirect to dashboard.php and echo $_SESSION['student'] then it throw an error i.e. Notice: Undefined index: student in C:\xampp\htdocs\test\dashboard.php on line 3 I don't know why where am I doing wrong? Please help me.
Thank You
Please start the session in login.php file :
include("config.php");
session_start();
$email = mysqli_real_escape_string($con, $_POST['email']);
$password = md5($_POST['password']);
Or put the session_start in config.php file
my PHP code was working fine until I decided to use jquery for my signup page to handle and check the fields, it's working there is no error, everything is submitted to the server correctly so there is no problem with the code PHP nor jquery, but the header("location: ../****.php") no longer send me to another page after I hit submit, instead it loads the new page on top of the old one without refreshing.
This is my jquery code for the signup page:
<script>
$(document).ready(function() {
$("#myForm").submit(function(event){
event.preventDefault();
var username = $("#signup-username").val();
var pwd = $("#signup-pwd").val();
$(".form-message").load("includes/user-signup.inc.php",{
username: username,
pwd: pwd
});
});
});
</script>
and this is my PHP code in my include page:
<?php
if (isset($_POST['submit'])){
include_once 'dbh.inc.php';
$username= mysqli_real_escape_string($conn, $_POST['username']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
$errorEmpty = $errorValid = false;
if(empty($username)|| empty($pwd)){
echo "Fill in all Fields!";
$errorEmpty = true;
}
else{
$stmt = $conn->prepare("SELECT * FROM users WHERE username=?");
$stmt->bind_param("s", $uid);
$uid = $username;
$stmt->execute();
$result = $stmt->get_result();
$usernamecheck = mysqli_num_rows($result); // check if the results
$rowNum = $result->num_rows;
if($rowNum > 0){
echo "Username is taken!";
$errorValid = true;
}
else{
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
$stmt = $conn->prepare("INSERT INTO users (username, pwd) VALUES (?, ?)");
$stmt->bind_param("ss",$uid, $password);
$uid = $username;
$password = $hashedPwd;
$stmt->execute();
$result = $stmt->get_result();
header("location: ../user-login.php");
}
}
}else{
header("location: ../user-signup.php");
exit();
}
?>
<script>
$("#signup-username, #signup-pwd").removeClass("input-error");
var errorEmpty = "<?php echo $errorEmpty; ?>";
var errorValid = "<?php echo $errorValid; ?>";
if (errorEmpty == true $$ errorValid == true){
$("#signup-username, #signup-pwd").addClass("input-error");
if (errorFEmpty == false && errorValid == false){
$("#signup-username, #signup-pwd,").val("");
}
</script>
how do I fix this?
$(".form-message").load("includes/user-signup.inc.php",{
username: username,
pwd: pwd
});
When the above code gets to the point where header("Location: file.php");
It'll fetch that file into $(".form-message")
To Avoid this you can use ajax to post data and javascript inbuilt redirection
$.ajax({
type: "POST",
url: "includes/user-signup.inc.php",
data: "username="+ username +"&pwd="+ pwd,
success: function(data) {
window.location.href = "../****.php";
}
});
Hope this answer was helpful.
Your code operates exactly as it should.
$(document).ready(function() {
$("#myForm").submit(function(event){
// THIS LINE RIGHT HERE
event.preventDefault();
******************
$(".form-message").load("includes/user-signup.inc.php",{
******************
});
});
});
Event prevent default stops the redirect action. Additionally you then use jquery to load the contents of the file into the DOM element with the class:
.form-message
Remove event.preventDefault();
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
I wanted to do is connect some files in different folder inside elogFiles folder. My problem is i dont know how to connect the files inside of another folder files.
here is the family tree of my files:
http://s38.photobucket.com/user/eloginko/media/folder_zpsa156e2a5.png.html
My problem the links is not correct.
Both code are not related. And the user.php is asking for connection from inside the dbc folder database.php and myScript.js wants to find user.php where is located inside the view folder.
myScript.js: " url: 'js/../view/user.php',"
user.php: "include_once('view/../dbc/database.php');"
can anyone help me correct the correct directory links.
user.php
<?php
include_once('../dbc/database.php');
$db = new Connection();
$db = $db->dbConnect();
$email = $_POST['email'];
$pass = $_POST['password'];
if(!empty($email) && !empty($pass)){
$st = $db->prepare("SELECT * from user WHERE email=? AND password=?");
$st->bindParam(1, $email);
$st->bindParam(2, $pass);
$st->execute();
if($st->rowCount() == 1){
echo "1";
exit;
} else {
echo "Incorrect Email or Password";
}
}else{
echo "Please enter Email and Password";
}
?>
myScript.js
$(document).ready(function() {
$('div#show:empty').hide();
$('#login').click(function(){
var email = $('#lemail').val();
var password = $('#lpassword').val();
$.ajax({
data: {
email : email, password : password
},
type: "POST",
url: 'js/../view/user.php',
success: function(data)
{
if (Number(data) == 1)
{
$(".show-page[data-page=progBar]").trigger("click");
$('#myModal').modal('hide');
}
else
{
$('div#show:empty').show();
$('#show').html(data);
}
}
});
return false;
});
});
As your hierarchy is presently, provided, if you are on your http://localhost/elogFiles/view/user.php, you just need to go level one up ../
user.php
<?php
include_once('../dbc/database.php');
$db = new Connection();
$db = $db->dbConnect();
$email = $_POST['email'];
$pass = $_POST['password'];
$response['status'] = '';
$response['message'] = '';
if(!empty($email) && !empty($pass)){
$st = $db->prepare("SELECT * from user WHERE email=? AND password=?");
$st->bindParam(1, $email);
$st->bindParam(2, $pass);
$st->execute();
if($st->rowCount() == 1){
$response['status'] = 'OK';
} else {
$response['status'] = 'ERROR';
$response['message'] = 'Username/Password not found';
}
}else {
$response['status'] = 'ERROR';
$response['message'] = 'Please input username/password';
}
echo json_encode($response);
exit;
?>
Since, user.php processes the AJAX request, point the AJAX url attribute to this file. Consider this example:
myScript.js
$.ajax({
data: {
email : email, password : password
},
type: "POST",
url: 'http://localhost/elogFiles/view/user.php',
dataType: 'JSON',
success: function(data) {
if (data.status == 'OK') {
$(".show-page[data-page=progBar]").trigger("click");
$('#myModal').modal('hide');
} else {
$('div#show:empty').show();
$('#show').html(data.message);
}
}
});