Ajax setting cookies - javascript

I have a login form with ajax and I am trying to set cookies if a "remember me" checkbox is checked. I already have code that runs when the user has the "remember me" box checked but the cookies aren't being set. Executing var_dump($_COOKIE) outputs array(1) { ["PHPSESSID"]=> string(26) "xxxxxxxxxxxxxxxxxxxxxxxxxx" } and it outputs the same thing even after executing secookie().
Login.php
<?php
require_once (dirname(__FILE__) . '/../../inc/inc.all.php');
$username;
$password;
$remember;
$token;
if (!isset($_POST['username'])) {
echo "Username field must be set!";
die();
}
$username = $_POST['username'];
if (!isset($_POST['password'])) {
echo "Password field must be set";
die();
}
$password = md5($_POST['password']);
$remember = $_POST['remember'];
if (!isset($_POST['token'])) {
echo "There was a problem logging you in securly, Prehaps you are trying to log in from a different window?";
die();
} else {
$token = $_POST['token'];
}
// Validate token
if (!isset($token) || $token != $_SESSION['token']) {
echo "Invalid token: There was a problem logging you in securley, Prehaps you are trying to log in from a different window?";
die();
}
// Log the user in
$sql = "SELECT ID FROM cs_users WHERE username = '{$username}' AND password = '{$password}'";
$query = $db -> query($sql);
if ($query -> num_rows) {
list($id) = #array_values($query -> fetch_assoc());
if ($remember) {
$expire = time() + 60 * 60 * 24 * 180;
echo $id.'<br>'.$username.'<br>'.$password.'<br>';
setcookie("id", $id, $expire);
setcookie("username", $username, $expire);
setcookie("password", $password, $expire);
// header("LOCATION:{$_SERVER['PHP_SELF']}");
} else {
$_SESSION['id'] = $id;
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
}
echo true;
} else {
echo "Invalid username/password";
die();
}
?>

You need to start the session by calling session_start();

*Executing var_dump($_COOKIE) outputs array(1) { ["PHPSESSID"]=> string(26)
"xxxxxxxxxxxxxxxxxxxxxxxxxx" } and it outputs the same thing even after executing secookie().*
The questions here, can you set another cookies from another scripts? If no means server config issues, else, need to debug current script.
From what I understand from your question, you cannot check test
$_COOKIE from within the same script that set it. In other words,
you cannot test var_dump($_COOKIE) directly after executing
secookie(). You can't read the value of a $_COOKIE until a new page request is made. This is because the value of cookie data is sent from the browser with each request.
I think setting cookies might take a moment to be settled. The best way to test if you the cookie has been created is to check your browser cookies and see if the cookies are there.
When you run the command setCookie(); it will only take effect when
the script finishes and pass the output to the browser. Then the
browser will create the cookie.
Check what the return value of setcookie function is maybe it
returns FALSE if output has been already sent before the function
call.
Check PHP configuration and .htaccess to see if setting cookies is enabled (try to set cookie regardless if the login process, just set a testing cookie and see if it works).
Try adding domain path, setcookie('name','14', time()+3600, '/', 'yourSite.com')
Disabling cookies for IP addresses and localhost was a design decision, do you have a domain name?
Hope that helps.

I fixed it myself. It Was setting the cookies. For the domain /internal/cloudshop/login. Changing the setCookie to setCookie("username", $username, "/") fixed the problem

Related

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

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

Lag issues cause of AJAX/PHP

So i am trying to make an asynchronous call of a PHP script but for some reason there is an error: Maximum call stack size exceeded that is making my site lagging a LOT. There must be a loop somewhere in my code but i can't really find it. I am looking for the past 3 days and still nothing. If someone could spot anything i would be really greatfull. Thanks in advance!
PHP code:
<?php
require_once 'li.php'; //File with the constants
$Username = $_POST['Username'];
$query = "SELECT Username
FROM user_info
WHERE Username = ?
LIMIT 1";
if($stmt = $conn->prepare($query)){ //Prepares the statement!
$stmt->bind_param('s', $Username);
$stmt->execute(); //Executes it!
if($stmt->fetch()){ //Checks if the query returns anything!
$stmt->close(); //If yes then closes the prepared statement!
$error = "Username taken";
echo $error;
}
}
?>
AJAX/JS code:
$(document).ready(function(){
$('#Username').on("keyup", function(){
$.ajax({
type: 'POST',
url: 'NameValidation.php', //Your required php page
data: { Username: Username }, //pass your required data here
async: true,
}).done(function(response){
if(response != ""){
$('#UsernameLabel').html("Username Taken!");
}
});
});
});
In case you didn't understand what i want to do with this code let me explain some more. I want every time the Username input changes to search if the username already exists in the database and alert the user by changing the Label text.
PS: Dont worry about SQL injection security i'll add that later when i fix this problem! ^-^
you are not closing connection if query returns nothing, try changing the code to :
if($stmt->fetch()){ //Checks if the query returns anything!
$error = "Username taken";
echo $error;
}
$stmt->close(); //close connection in any case

PHP login script redirection not working after login

I found and fixed a little bit I am not so good with PHP but any improvements are welcome.
The problem is that sometimes in Chrome and Opera but only sometimes after login sucess the script redirect to a welcome page with javascript redirection after 5 secs. But sometimes it just get stuck and does not redirect but just show a white page without error and other times it redirect and worls fine. What can it be?
Here is the code
<?php session_start();?>
<?php
include 'inc/connection.php';
$db=mysqli_connect($dbserver, $dbuser, $dbpass, $dbname)or die("DB connection error...");
$username_to_sanitize = $_POST['username'];
$password_to_sanitize = $_POST['password'];
$sanitized_username = mysqli_real_escape_string($db, $username_to_sanitize);
$sanitized_password = mysqli_real_escape_string($db, $password_to_sanitize);
$query = "SELECT password, salt, privilege, username FROM members WHERE username = '$sanitize_username'";
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result) == 0) // User not found. Redirected to login page.
{header('Location:login.php?message=Username not found, please try again');}
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $sanitized_password) );
if($hash != $userData['password']) // Incorrect passw. Redirected to login page.
{header('Location:error.php?message=Wrong password, please try again');}
else if($userData['privilege']=="ADMIN"){session_start();
$_SESSION['username']=$userData['username'];
header('Location:redirection.php?URL=admins/index.php');}
else if($userData['privilege']=="MODERATOR"){session_start();
$_SESSION['username']=$userData['username'];
header('Location:redirection.php?URL=moderators/index.php');}
else if($userData['privilege']=="MEMBER"){session_start();
$_SESSION['username']=$userData['username'];
header('Location:redirection.php?URL=members/index.php');}
else if($userData['privilegio']=="BANNED"){session_start();
$_SESSION['username']=$userData['username'];
header('Location:redirection.php?URL=banned/index.php');}
else{
header('Location:error.php?message=su need privileges to acces this site');
exit();
}
?>
After reading and testing new scripts found on internet I still cannot fix this problem after 2 months. Any idea?
You have a lot of duplication in your code, which is bad because each place that you duplicate means that you need to change it when you update the code, which means that there are more places for bugs to pop up later.
To help, I placed in only one session_start(), and I converted the if/elseif/elseif/elseif... to a switch statement.
Instead of dealing with the location headers themselves, I've replaced those with the http_redirect function, which basically does it for you. To boot, it encodes the URLs for you so you don't have to worry about that.
If you keep seeing a blank page, then you should check the webserver's logs (apache or nginx or php-fpm, or whatever) to see if the errors are there. Otherwise, turn on better error reporting; quite often blank pages are just errors that haven't been reported.
<?php
session_start();
include 'inc/connection.php';
$db = mysqli_connect($dbserver, $dbuser, $dbpass, $dbname) or die('DB connection error...');
$sanitized_username = mysqli_real_escape_string($db, $_POST['username']);
$sanitized_password = mysqli_real_escape_string($db, $_POST['password']);
$query = "SELECT password, salt, privilege, username FROM members WHERE username = '$sanitized_username'";
$result = mysqli_query($db, $query);
if (mysqli_num_rows($result) == 0) {
// User not found. Redirected to login page.
http_redirect('login.php', array('message' => 'Username not found, please try again'), true);
}
$userData = mysqli_fetch_array($result, MYSQL_ASSOC);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $sanitized_password) );
if($hash != $userData['password']) {
// Incorrect passw. Redirected to login page.
http_redirect('error.php', array('message' => 'Wrong password, please try again'), true);
}
// Just set the username once
$_SESSION['username'] = $userData['username'];
switch ( $userData['privilege'] ) :
case 'ADMIN':
http_redirect('redirection.php', array('URL' => 'admins/index.php'), true);
break;
case 'MODERATOR' :
http_redirect('redirection.php', array('URL' => 'moderators/index.php'), true);
break;
case 'MEMBER' :
http_redirect('redirection.php', array('URL' => 'members/index.php'), true);
break;
case 'BANNED' :
http_redirect('redirection.php', array('URL' => 'banned/index.php'), true);
break;
default:
// The message is weird. Should it be:
// 'You need privileges to access this site' or something like that?
http_redirect('error.php', array('message' => 'su need privileges to acces this site'), true);
break;
endswitch;
http_redirect('error.php', array('message' => 'su need privileges to acces this site'), true);
?>

PHP mysql previous declared function issue

I'll make this as short and sweet as possible.
I have this script called usernameget.php which echos the currently logged in username:
<?php
include 'functions.php';
include 'db_connect.php';
sec_session_start();
$userId = $_SESSION['user_id'];
if(login_check($mysqli) == true) {
$con=mysqli_connect("localhost","myusername","mypass","mysqldb");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT members.username FROM members WHERE id= $userId");
while ($row = mysqli_fetch_assoc($result))
{
echo $row['username'];
}
/* free result set */
mysqli_free_result($result);
mysqli_close($con);
} else {
echo 'Null User <br/>';
}
?>
This script uses functions.php (part of a secure login script located here: http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL#Create_PHP_Functions ) in order to function. sec_session_start(); is just a custom session_start, but functions.php also makes it possible to get the username via $user_id.
The problem is, when I include usernameget.php in the main page (which also uses functions.php to secure,) it throws errors because it's trying to redeclare sec_session_start();
I can strip usernameget.php of this security but obviously since it banks on functions.php / sec_session_start(); it doesn't work afterwards. I've tried to write a specific USERNAMEGETfunctions.php without the session stuff for usernameget.php to use but I'm not adept enough to get it working, and it feels like an inelegant solution.
So as I understand it: functions.php and sec_session_start(); are used to secure the main page so the includes on the main page can't use functions.php or it will conflict. Would anyone be able to show me how to get this script going without redeclaring/conflicting?
Included below is the entire functions.php
<?php
function sec_session_start() {
$session_name = 'sec_session_id'; // Set a custom session name
$secure = false; // Set to true if using https.
$httponly = true; // This stops javascript being able to access the session id.
ini_set('session.use_only_cookies', 1); // Forces sessions to only use cookies.
$cookieParams = session_get_cookie_params(); // Gets current cookies params.
session_set_cookie_params($cookieParams["lifetime"], $cookieParams["path"], $cookieParams["domain"], $secure, $httponly);
session_name($session_name); // Sets the session name to the one set above.
session_start(); // Start the php session
session_regenerate_id(); // regenerated the session, delete the old one.
}
function login($email, $password, $mysqli) {
// Using prepared Statements means that SQL injection is not possible.
if ($stmt = $mysqli->prepare("SELECT id, username, password, salt FROM members WHERE email = ? LIMIT 1")) {
$stmt->bind_param('s', $email); // Bind "$email" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
$stmt->bind_result($user_id, $username, $db_password, $salt); // get variables from result.
$stmt->fetch();
$password = hash('sha512', $password.$salt); // hash the password with the unique salt.
if($stmt->num_rows == 1) { // If the user exists
// We check if the account is locked from too many login attempts
if(checkbrute($user_id, $mysqli) == true) {
// Account is locked
// Send an email to user saying their account is locked
return false;
} else {
if($db_password == $password) { // Check if the password in the database matches the password the user submitted.
// Password is correct!
$user_browser = $_SERVER['HTTP_USER_AGENT']; // Get the user-agent string of the user.
$user_id = preg_replace("/[^0-9]+/", "", $user_id); // XSS protection as we might print this value
$_SESSION['user_id'] = $user_id;
$username = preg_replace("/[^a-zA-Z0-9_\-]+/", "", $username); // XSS protection as we might print this value
$_SESSION['username'] = $username;
$_SESSION['login_string'] = hash('sha512', $password.$user_browser);
// Login successful.
return true;
} else {
// Password is not correct
// We record this attempt in the database
$now = time();
$mysqli->query("INSERT INTO login_attempts (user_id, time) VALUES ('$user_id', '$now')");
return false;
}
}
} else {
// No user exists.
return false;
}
}
}
function checkbrute($user_id, $mysqli) {
// Get timestamp of current time
$now = time();
// All login attempts are counted from the past 2 hours.
$valid_attempts = $now - (2 * 60 * 60);
if ($stmt = $mysqli->prepare("SELECT time FROM login_attempts WHERE user_id = ? AND time > '$valid_attempts'")) {
$stmt->bind_param('i', $user_id);
// Execute the prepared query.
$stmt->execute();
$stmt->store_result();
// If there has been more than 5 failed logins
if($stmt->num_rows > 5) {
return true;
} else {
return false;
}
}
}
function login_check($mysqli) {
// Check if all session variables are set
if(isset($_SESSION['user_id'], $_SESSION['username'], $_SESSION['login_string'])) {
$user_id = $_SESSION['user_id'];
$login_string = $_SESSION['login_string'];
$username = $_SESSION['username'];
$user_browser = $_SERVER['HTTP_USER_AGENT']; // Get the user-agent string of the user.
if ($stmt = $mysqli->prepare("SELECT password FROM members WHERE id = ? LIMIT 1")) {
$stmt->bind_param('i', $user_id); // Bind "$user_id" to parameter.
$stmt->execute(); // Execute the prepared query.
$stmt->store_result();
if($stmt->num_rows == 1) { // If the user exists
$stmt->bind_result($password); // get variables from result.
$stmt->fetch();
$login_check = hash('sha512', $password.$user_browser);
if($login_check == $login_string) {
// Logged In!!!!
return true;
} else {
// Not logged in
return false;
}
} else {
// Not logged in
return false;
}
} else {
// Not logged in
return false;
}
} else {
// Not logged in
return false;
}
}
?>
Don't use plain include for core function libraries, the kind which tend to get included in ALL your scripts. Use include_once instead, so that PHP will only ever include the file once, and then ignore any further include attempts. This will prevent your function redeclaration errors.
You must use require_once instead include_once because your program not will run without that files...
include_once produce warning when try to include the file and it fails.
require_once produce fatal error when try to include the and it fails.
For core libs, you should use require_once. (http://www.php.net/manual/pt_BR/function.require.php)
require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.

Categories