PHP Session lost after window.location.href - javascript

Certain visitors are losing sessions when getting redirect to pages.
pages have session_start(); on them, I am using window.location.href to
redirect users after success from ajax response. while this is not
happening to me using Chrome or Android. but its happening to other devices
which I cant replicate but received complaints. is there a remedy for this? we are on HTTPS. we remove the .php using nginx.
JS Code:
$(function (){
$(".my_button").click(function(e){
$.post("/post", {id: 1,blah:1},
function(data){
if(data.success){
window.location.href = data.next_page;
//Example
//window.location.href = "thankyou";
}
}, "json");
return false;
});
});
Next Pages:
<?php
session_start();
$echo = "test";
?>
/post
<?php
session_start();
$blah = $_POST['blah'];
if($blah == 1){
$next_page = "thankyou";
}else if($blah == 2){
$next_page = "back";
}
$response = array('success' => true,'next_page' => $next_page);
print json_encode($response);die();
?>
checker.php
<?php
session_start();
if(!isset($_SESSION['my_id'])){
header("Location: index.php");
exit;
}
?>

Related

[Ajax][PHP] - login form, response is always empty

I have a problem with my login form. Every time when i write (correct or incorrect) login and password in my login form, my JS script return error and when i try to print "response" it is empty.
Can anyone help?
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
var name = $("#name").val().trim();
var paw = $("#paw").val().trim();
$.ajax({
url: 'check.php',
type: 'POST',
data: {name:name, paw:paw},
success: function(response){
if(response == 1){
window.location= "home.php";
}
else{
alert("error");
}
}
});
});
});
<?php
session_start();
require_once 'dbconfig.php';
error_reporting(E_ALL ^ E_NOTICE);
if(isset($_POST['submit']))
{
$name = trim($_POST['name']);
$paw1 = trim($_POST['paw']);
$paw = md5($paw1);
try {
$stmt = $pdo->prepare("SELECT * FROM user WHERE login=:nazwa and haslo=:has");
$stmt->execute(array(':nazwa'=>$name, ':has'=>$paw));
$count = $stmt->rowCount();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($row['haslo']==$paw){
echo 1;
$_SESSION['user_session'] = $row['login'];
}
else {
echo 0;
}
} catch (\Exception $e) {
echo $e->getMessage();
}
}
?>
Remove the if(isset($_POST['submit'])) line. The reason is that the button key value is not sent via the AJAX call. To verify, do a print_r($_POST);
instead verify that name and password variables are not empty()
if (!empty($_POST['name']) && !empty($_POST['paw'])) {
}
Also do not use md5() for your passwords. use php's password_hash() to hash and password_verify() to verify that the posted password via the form matches the hash stored in the database for that user.

Java Script for page redirecting over PHP SESSION status

I m trying to redirect pages according to PHP session status, so that, if session start () redirect to page1 else page 2
but seems like i kinda didn't done well with coding.
code goes as:
<script>
if (session_start();) {
window.location = 'page1.php';
}
else {
window.location = 'page2.php';
}
</script>
Any Help is Appreciated..
I think u want something like this:
<script>
<?php
session_start();
if($_SESSION['login'] == true) {
$_SESSION['login'] = false;
echo "window.location = 'page1.php';";
} else {
$_SESSION['login'] = true;
echo "window.location = 'page2.php';";
}
?>
</script>
First of all, session_start is a php-related function, and you are using it inside javascript.
You should prepend and append to every PHP code you want to use both these symbols:
<?php # Start
?> # End
Second Point: If you need to redirect someone to some page, use header("location") in PHP.
So your result code should be:
<?php
if(session_start()){
header("location: page1.php");
}
else{
header("location: page2.php");
}
?>
Btw.. I don't understand why you are using a "session_start" as a condition.
// create a php file first
index.php
// include js on all pages
// create a javascript file
func.js
<script type="text/javascript">
// lets create a function
function newtab(page)
{
if(page != "")
{
window.open(page,"_self","location=yes");
}
}
</script>
<?php
// no harm, we can still add javascript here
// we assume this is index.php
// start a session here
session_start();
// you need to create a switch
if(!isset($_SESSION['switch']))
{
echo '<script>newtab("page1.php")</script>';
}
else
{
echo '<script>newtab("page2.php")</script>';
}
// you can play with the switches
?>
hope this helps
Just do it with PHP:
if(session_start()){
header("Location:page1.php"); die();
} else {
header("Location:page1.php"); die();
}

PHP - How to return an error message to a register page

i'm having issues in returning an error message into a register form: I have 2 files (register.php and process_register.php),
Pratically into register.php ther's the form from which i pass the request thought POST, while in process_login is executed a function (register($conn,$username,$password))
Here are the code of the files
process_register.php
<?php
if((include 'db_connect.php')==TRUE){echo"OKDB";}
if((include 'functions.php')==TRUE){echo"OKFUNCTIONS";}
sec_session_start();
if(login_check($conn) == true) //Already Logged In!
header('Location: ./index.php');
else{
if(isset($_POST['username'], $_POST['password'])) {
//Got username and pswd
$username=$_POST['username'];
$password = $_POST['password'];
$registerresult=register($conn,$username,$password);
if($registerresult==TRUE) //Registration success!
header('location: login.php');
else
header('location: register.php');
}else {
// Not here with a post request.
echo 'Invalid Request';
}
}
?>
register($conn,$username,$password)
function register($conn,$username,$password){
//ifusernamealreadyused
$alreadyregister="SELECT * FROM User WHERE username='$username';";
$query_alreadyregister=mysqli_query($conn,$alreadyregister);
$alreadyregister_rows=mysqli_num_rows($query_alreadyregister);
if($alreadyregister_rows!=0) //UsernameAlreadyUsed
return false;
else{ //UsernameNotAlreadyUsed
//RegistrationOK!
$registration="INSERT INTO User(username,password) VALUES('$username',sha2('$password',512));";
$query_registration=mysqli_query($conn,$registration);
return true;
}//UsernameNotAlreadyUsed
} //Register
My question is: How can i show a message into the form if the username is not 'correct?(returns false)
Cheers in advance!
This is quite simple just add these lines in your existing code
change this header('location: register.php'); to
header('location: register.php?message=username already exist');
and in your register.php check for this
<?php if(isset($_GET['message'])) {echo $_GET['message'];} ?>
In the page you wish to display the error message, add:
<?php if(isset($message)) {echo $message;} ?>
Modify your register function:
<?php
function register($conn,$username,$password){
//ifusernamealreadyused
$alreadyregister="SELECT * FROM User WHERE username='$username';";
$query_alreadyregister=mysqli_query($conn,$alreadyregister);
$alreadyregister_rows=mysqli_num_rows($query_alreadyregister);
if($alreadyregister_rows!=0) //UsernameAlreadyUsed
$message = 'Username already used!'; //set your error message here
return false;
else{ //UsernameNotAlreadyUsed
//RegistrationOK!
$registration="INSERT INTO User(username,password) VALUES('$username',sha2('$password',512));";
$query_registration=mysqli_query($conn,$registration);
return true;
}//UsernameNotAlreadyUsed
} //Register
?>

Redirect from Ajax's PHP script

I have a form like this:
<form action="process.php" method="post">
<input type="text" name="input" />
<button type="submit">Submit</button>
</form>
And I have an Ajax script like this:
$("button").click(function(event) {
var $ajaxData = {
"input-val" : $("input").val();
}
$.ajax({
type : "POST",
url : "process.php",
data : $ajaxData,
dataType : "json",
encode : true
});
.done(function($data) {
alert($data["stat"]);
});
event.preventDefault();
$("form").unbind();
});
Also a PHP script (process.php) where the form data is send:
<?php
if(isset($_POST['input-val'])) {
$data['stat'] = 'success';
echo json_encode($data);
}
?>
All is correct and set, but, if I want to stop the users of seeing or going (manually) to the "process.php" page I add a redirect function:
<?php
if(isset($_POST['input-val'])) {
$data['stat'] = 'success';
echo json_encode($data);
}
header('Location: index.php');
?>
That makes Ajax's request fail automatically. How can I stop users of going or seeing the PHP script?
As I said, the "event.preventDefault();" is stopping Ajax of sending the users to the PHP script, but users can go there by themselves.
The problem is, the script is expecting a JSON, while your "redirect" code sends a HTTP 301 to a HTML file. Ultimately, the AJAX XHR is not seeing your JSON, but gets the HTML output.
Revert back your code to how it was before:
<?php
if(isset($_POST['input-val'])) {
$data['stat'] = 'success';
echo json_encode($data);
}
Instead, do it in the AJAX handler:
.done(function($data) {
alert($data["stat"]);
if ($data["stat"] == "success")
location.href = 'index.php';
}) // And you are also missing a ) here.
According to comments:
If you are redirecting if the $_POST is not set, please use the else:
if (isset($_POST['input-val'])) {
$data['stat'] = 'success';
echo json_encode($data);
} else {
header('Location: index.php');
}

from PHP to Javascript to enter PHP again and set Sessions

Im trying to fix this issue im having. The problem is that I use this code when someone want to sign in to the admin panel:
<script>
function myFunction() {
//alert('you can type now, end with enter');
$("#test").focus();
}
$(document).ready(function() {
$("form").submit(function(e) {
e.preventDefault();
// alert($("#test").val());
var email = $("#test").val();
if(email==''){
// alert("Error.");
sweetAlert("Oops...", "Error!", "error");
} else {
$.post("sess.php",{ code1: code},
function(data) {
// alert(data);
// swal(data);
if((data)=="1") {
swal("Welcome!", "Please wait!", "success")
} else {
sweetAlert("Oops...", "Something went wrong.", "error");
}
$('#form')[0].reset(); //To reset form fields
});
}
});
});
</script>
Sess.php looks like this:
<?php
include("conn.php");
?>
<?php
include("ipcheck.php");
$code2=htmlEntities($_POST['code1'], ENT_QUOTES);
$info = explode("-", $code2);
$username = $info[0];
$password = $info[1];
$_POST = db_escape($_POST);
$sql = "SELECT id FROM adminusers
WHERE user='{$username}'
AND pass='$password'";
$result = mysql_query($sql);
if (mysql_num_rows($result) == 0){
echo "2";
exit;
}
// Session for user
$_SESSION['sess_id'] = mysql_result($result, 0, 'id');
$_SESSION['sess_user'] = $username;
// DAtabse going on here.
echo "1";
exit;
?>
So if the username and password is correct the login is successful and those session is set in sess.php:
$_SESSION['sess_id'] = mysql_result($result, 0, 'id');
$_SESSION['sess_user'] = $username;
My problem is, how do I get the sessions that is set for the user thru sess.php back to index.php using javascript so I can set the sessions in index.php not in sess.php?
why to you care to pass the session to javascript ? I mean if you set the session server side on sess.php you have already setted it even in index.php (session exists during the entire ... session :-) ) so when sess.php return that the authentication is correct, your javascript should just move the page to index.php like:
window.location.href = 'index.php';
in index.php, if you print the session print_r($_SESSION) you should see the values that you have previously set in sess.php
If your $_SESSION is empty in index.php probably you have to start the session before reading $_SESSION using session_start();

Categories