from PHP to Javascript to enter PHP again and set Sessions - javascript

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

Related

PHP Session lost after window.location.href

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

Data Not inserting to DB - PHP MYSQL

Trying to get together the sign up validation with PHP and Ajax. Not sure what is wrong but the submission does not happen. If I don't add the validation part everything looks fine and i am able to insert the data to mysql.
<script type="application/javascript">
$("#submit").submit(function (event) {
event.preventDefault();
var datatopost = $(this).serializeArray();
console.log(datatopost);
$.ajax({
url: "signupregister.php",
type: "POST",
data: datatopost,
success: function (data) {
if (data) {
$("#signupmessage".html(data));
}
},
error: function () {
$("#signupmessage").html("<div class = 'alert alert-danger'></div>")
}
});
});
</script>
_
<?php
session_start();
include('mysqlconnection.php');
include('index.php');
function customError($errors, $errorslevel)
{
}
set_error_handler("customError", E_ALL);
if (isset($_POST['submit'])) {
if ($_POST($first_name) == "") {
$errors .= $first_nameError;
} else {
$first_name =
filter_var($_POST["first_name"], FILTER_SANITIZE_STRING);
}
}
if ($errors) {
$resultMessage = '<div class="alert alert-danger">' .
$errors . '</div>';
echo $resultMessage;
exit;
}
$first_nameError = '<p>first name required</p>';
First up, in your validation PHP script, you won't need to include 'index.php'
Try redirecting the form to an empty page where you only include your validation data, while setting a session variable for the first error encountered.
At the end of your validation, if your error variable contains an error, you can redirect to the form and display your said error at a convenient location. Keep in mind you will have to save form data in session variables if you want to preserve all user input (thus removing the hassle of refilling the form over and over again).
If it doesn't, you can proceed to insert the data in your db then redirect to your desired landing page.
Here's a sample code based on your input:
<?php
session_start();
if(isset($_POST['submit'])){
$_SESSION['fname'] = $_POST['fname'];
//so on for your other variables
if($_SESSION['fname'] == ""){
$_SESSION['err'] = "First Name Required";
}
if(//insert your format validation for first name){
$_SESSION['err'] = "First Name Invalid";}
}
//end of validation
if isset($_SESSION['err']){
header('Location: myform.php');
}
else{
//save all your variables into normal ones, i.e $fname-$_POST['fname'];
//insert into database;
//check correct insertion;
//redirect to landing page;
}
}
?>

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

how to pass variables between 2 php files

I have two php files to make authentication to active directory users, i want to get the attribute url from it and pass this variable $data from authenticate.php to login.php if the function returned true to be in the location of header("Location: *URL*");,how can this be done?
authenticate.php:
<?php
// Initialize session
session_start();
function authenticate($user, $password) {
if(empty($user) || empty($password)) return false;
// Active Directory server
$ldap_host = "CRAMSDCR01V.cloud4rain.local";
// connect to active directory
$ldap = ldap_connect($ldap_host);
$ldap_dn="OU=by-style,DC=cloud4rain,DC=local";
// verify user and password
if($bind = #ldap_bind($ldap, $user, $password))
{
$result = ldap_search($ldap,$ldap_dn, "(cn=*)") or die ("Error in search query: ".ldap_error($ldap));
$data = ldap_get_entries($ldap, $result);
echo $data["url"];
return true;
}
else
{
// invalid name or password
return false;
}
}
?>
login.php:
<?php
include("authenticate.php");
// check to see if user is logging out
if(isset($_GET['out'])) {
// destroy session
session_unset();
$_SESSION = array();
unset($_SESSION['user'],$_SESSION['access']);
session_destroy();
}
// check to see if login form has been submitted
if(isset($_POST['btn-login'])){
// run information through authenticator
if(authenticate($_POST['userLogin'],$_POST['userPassword']))
{
// authentication passed
header("Location: authenticate.php?$data");
die();
} else {
// authentication failed
$error = "Login failed: Incorrect user name, password, or rights<br /-->";
}
}
// output logout success
if(isset($_GET['out'])) echo "Logout successful";
?>
login.php
<?php
include("authenticate.php");
That essentially acts like pasting the contents of authenticate.php inside login.php so although it's technically 2 files, it acts as if it's just the one - however $data is defined within the authenticate() function and so is only scoped within that function.
In authenticate.php - return the data from the function
// verify user and password
if($bind = #ldap_bind($ldap, $user, $password))
{
$result = ldap_search($ldap,$ldap_dn, "(cn=*)") or die ("Error in search query: ".ldap_error($ldap));
$data = ldap_get_entries($ldap, $result);
// echo $data["url"]; // I assume this is just for debugging...
// return $data from the function which should be "truthy"
return $data;
}
else
{
// invalid name or password
return false;
}
In login.php - evaluate the return from the authenticate() function - since PHP is loosely typed any (non-empty) string returned by the function can be evaluated as being "truthy" - the only other returns you have from the function are false so...
// run information through authenticator
if($authData = authenticate($_POST['userLogin'],$_POST['userPassword']))
{
// authentication passed
// renamed the variable $authData just for clarity
header("Location: authenticate.php?$authData");
die();
}
else {
// authentication failed
$error = "Login failed: Incorrect user name, password, or rights<br />";
}
Not sure why you have $_SESSION = array(); in login.php but if you want to pass $data from one php to another then just set it in session as
$_SESSION['data'] = $data;
ang to get it in the other file use
$data = $_SESSION['data'];

Using Javascript to run a php script to check username

I've been trying to build a registeration form for a website I am building. I can do the basics but I want it to check the username availability without reloading the page.
JAVASCRIPT
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script>
$(document).ready(function()
{
$("#Username").focusout(function()
{
//Check if usernane if available
var username = $("#Username").val();
$.post("scripts/check_username.php", {username: username}, function(data)
{
if(data == 'false')
{
alert('Username not available');
$("#Username").setCustomValidity("This username is already taken!");
}
else
{
alert('Username available');
}
});
return false;
});
});
</script>
HTML
<form id="registerForm">
<table>
<tr><td>Username</td><td><input id="Username" class='textInput' type='text' name='username' required></td></tr>
PHP SCRIPT
<?php
include 'open_connection.php';
$result = 'true';
$username = mysql_real_escape_string($_POST['username']);
$result = mysql_query("SELECT * FROM tblMembers WHERE Username='$username'");
while($row = mysql_fetch_array($result))
{
$result = 'false';
}
echo $result;
?>
When I leave the textbox it says username available no matter what. I placed a username "test" in the database... no luck
Please help
PHP:
$output = 'true';
$username = mysql_real_escape_string($_POST['username']);
$result = mysql_query("SELECT * FROM tblMembers WHERE Username='$username'");
while($row = mysql_fetch_array($result))
{
$output = 'false';
}
echo $output;
Ans Script:
<script>
$(document).ready(function()
{
$("#Username").focusout(function()
{
//Check if usernane if available
$.post("scripts/check_username.php", {username: $("#Username").val()}, function(data)
{
if(data =='false')
{
$("#Username").setCustomValidity("This username is already taken!");
}
else
{
alert('Username available');
}
});
return false;
});
});
</script>
By the way, don't use mysql_* function, they're deprecated. use Mysqli or PDO. Next thing is you forgot to put semi-colon that the end of your statements !
You specify $("#Username").value do you mean to use $("#Username").val()?
$('#Username').value is probably returning you rubbish which will not exist in your DB.
Do you use Developer Tools or Firebug?
It would be easy to see where the issue lies if you examined the $.post to check_username.php:
(1) is the correct post request being sent? I think your data object should be {"username":username}
(2) is your script responding true? or something else? You only know it's not returning false by the way your if statement is structured.

Categories