PHP not accessing Javascript cookie - javascript

I am creating a small CRUD web app where I need the user to enter their password when they wish to delete an item from the database, I have an onClick() on the delete button on the HTML table which passes the ID of the product to be deleted to the js function.
When the function runs I wish to confirm that they really want to delete the product and then ask for their password and store it in a cookie. BUT IT DOES NOT SEEM TO WORK :(
I am setting a cookie using javascript like
document.cookie = 'password=${userPassword},expires=${now.toGMTString()},path=/../includes/delete-product.inc.php;
With this line of code, when I console.log(document.cookie), it shows me the cookie in the console like
password=admin,expires=Sat, 12 Dec 2020 08:40:38 GMT,path=/../includes/delete-product.inc.php; PHPSESSID=3n1l3q6ksqitdpc76hjrero9ja
when I redirect to another PHP page using window.open() I can not access this cookie.
print_r($_COOKIE); <- only shows me the PHPSESSID only.
When I explicitly try to access the cookie using the following line
$userPassword = $_COOKIE[password]; it gives me undefined index 'password'
This is my code.
myproject/admin/view-products.php (This is the page where I try to set the cookie using javascript)
function deletePrompt(id) {
const now = new Date();
const time = now.getTime();
const expiresIn = time + (50 * 1000);
now.setTime(expiresIn);
const path = `../includes/delete-product.inc.php`;
const intent = confirm("Are you sure you want to delete this products");
if (intent === true) {
const userPassword = prompt("Enter password");
document.cookie = `password=${userPassword},expires=${now.toGMTString()},path=/../includes/delete-product.inc.php`;
console.log(document.cookie);
return;
window.open(`../includes/delete-product.inc.php?id=${id}`, "_self");
}
}
myproject/includes/delete-product.inc.php (This is the PHP page where I need to access the cookie)
<?php
require_once "./database-connection.inc.php";
require_once "./functions.inc.php";
if (isset($_SESSION["adminId"])) {
$productId = $_GET["id"];
$userPassword = $_COOKIE["password"]; //<- This throws undefined index error
if (deleteProduct($connection, $productId, $userPassword)) {
header("location: ../admin/view-products.php?msg=deleted");
exit();
}
else {
header("location: ../admin/view-products.php?msg=incorrectPass");
exit();
}
}
else {
header("location: ../admin/login.php");
exit();
}

To anyone else facing this the problem, the solution is that cookies don't get sent across directories, so you need to have the recipient file in the same domain if you wish to transfer cookies across them otherwise it won't work.
eg.
Following pattern will work
youProject/someDirectory/file1
youProject/someDirectory/file2
Following will NOT WORK
youProject/someDirectory/file1
youProject/someOtherDirectory/file2

Related

Check if the value of the local storage is equal or not to that of a Php variable

hello I have this php file with the name ** request.php ** that has this Code:
<?php
$Password_user = 'AIzaSyA';
?>
and I have a Index.html file, and I also have a Local Storage with that name user_pass so I created a variable with the name get_spass that looks like this:
var get_spass= localStorage.getItem('user_pass');
so how can i create a request in Ajax that is able to check if the value of the Storage location is equal or not gives it Variable ** Password_user of request.php?
You have to change your php file to:
<?php
$Password_user = 'AIzaSyA';
echo $Password_user;
?>
In your html file you can fetch the file and check the password value with this code:
var get_spass= localStorage.getItem('user_pass');
var passIsCorrect = checkPassword(get_spass);
if (passIsCorrect) {
//do stuff...
}
async function checkPassword(get_spass) {
const passwordPhp = await fetch("request.php");
if (get_spass === passwordPhp) {
return true;
}
return false;
}
Note that everyone can get the request.php content. If the password need to be secret you have to implement some sort of authentication to assure the request.php file can be read only by authorized users or person.

Ajax dependent text field and dropdown menu (Php and Javascript)

I'm a student and still new with Javascript and php, i need to make a login page for my website that can check user input in the database using ajax.
Example: When the user enter their username and password into the field given,the system will automatically check in database either the user exist or not and return the data needed such as user responsibilty from the response table to the dropdown menu below, then they can login into the system.
Below is my basic coding:
Config.php:
e$host = "localhost";
$User = "root"
$Pass = "passw";
$db = "skm_spm";
Login.php:
<?
require ("config.php");
$conn=mysqli_connect($host,$user,$pass,$db);
$duser="select * from tab_user where user_name = '".$_POST["Lname"]."'";
$uresult=myqli_query($conn,$duser);
if(!$uresult)
die("Invalid query: ".mysqli_error());
else
if(mysqli_num_rows($uresult)== 0){
echo "User does not exist";
}
else
{
$row=mysqli_fetch_array($result,MYSQL_BOTH);
if($row["User_Password"] == $_POST["Lpass"])
{
$dresp="select resp_id,resp_name from tab_resp";
$result2 = mysqli_query($conn,$dresp);
}
else
{
}
}
?>
<html>
<b>Login</b><br>
Name : <input type = "text" name="Lname" id="Lname" placeholder="Username"/><br>
Password: <input type = "password" name="Lpass" id="Lpass" placeholder="password"/><br><br>
<div class = "optresp">
<select name="sresp" id="sresp">
<option>--Responsibility--</option>
<?
while (mysqli_fetch_array($result2)){
echo "<option value='$row[1]'>$row[1]</option>";
?>
</select>
</div>
</html>
I have learn on internet and try to code with my understanding,but still failed. I need a php ajax coding that can work with code above.
Thank you.
I will provide you with some code from my recent project and hopefully you will be able to understand it and adapt it to your needs.
Firstly, you should have the login form in a separate file to the PHP login code. Then have button on the page or an enter events that run a Javascript function, in my case Login(). In this Javascript function the text within the input fields are saved to two variables and some basic checks are done on them to ensure that they have been filled in. Next, the PHP login function file (it has no visible content in just processes some data in PHP) using the $.post line. This also passed the two input variables (under the same name) to the PHP file. You can also see that depending on what is returned/echoed from the PHP file as "data" several possible outcomes may occur (Login Success, Account Banned or Invalid Login). I personally call these outcomes error messages or success messages, for example error message 6 for incorrect password/username.
//FUNCTIONS
function Login(){
var StrUsername = $("#txtUsername" ).val();
var StrPassword = $("#txtPassword").val();
if (StrUsername == "" && StrPassword == ""){
$('#pError').text('Enter your Username and Password!');
}
else if(StrUsername == ""){
$('#pError').text('Enter your Username!');
}
else if(StrPassword == ""){
$('#pError').text('Enter your Password!');
}
else{
$.post('https://thomas-smyth.co.uk/functions/php/fnclogin.php', {StrUsername: StrUsername, StrPassword: StrPassword}, function(data) {
if (data == 0){
window.location.href = "https://thomas-smyth.co.uk/home";
}
else if (data == 1){
window.location.href = "https://thomas-smyth.co.uk/banned";
}
else if (data == 6){
$('#pError').text('Username & Password combination does not exist!');
}
});
}
}
Next the PHP function file. Firstly, the variables passed by the Javascript are collected using $_POST. My SQL class is then pulled into the file, this does all my SQL DB connections. I then have my SQL statement that will search to see if the account exists. Notice the ? in it. This prevents SQL injections as the variables is bound into the statement through the SQL server meaning it won't allow people to put SQL code within my input fields to break my database. I then check whether the account exists, if it doesn't I save data to 6, which will cause the error message 6 in the Javascript to run when data is returned. I have a field in my database that contains a rank. If the login is correct then I create a SESSION variable to store their username and rank in. This is later used on pages to check whether they are logged in before displaying a page (this speeds up navigation as it means that the DB doesn't need to be searched everytime the user switches page, however does bring some issues like if you ban a user while they are logged in they will stay logged in until their session dies). You could use this on your dropdown menu to ensure the user is logged in and/or get their username. Finally, I return 0 or 1, so that the Javascript then re-directs them to the correct page.
<?php
//Retrieves variables from Javascript.
$StrUsername = $_POST["StrUsername"];
$StrPassword = $_POST["StrPassword"];
require "sqlclass.php";
$TF = new TF_Core ();
$StrQuery = "
SELECT Username, Rank FROM tblUsers
WHERE Username = ? AND Password = ?";
if ($statement = TF_Core::$MySQLi->DB->prepare($StrQuery)) {
$statement->bind_param('ss',$StrUsername,$StrPassword);
$statement->execute ();
$results = $statement->get_result ();
if($results->num_rows == 0){
$data = 6;
}
else {
while ($row = $results->fetch_assoc()) {
//Other groups
if ($row["Rank"] == "Developer" || $row["Rank"] == "Staff" || $row["Rank"] == "Cadet"){
session_start();
$_SESSION["LoginDetails"] = array($StrUsername, $row["Rank"]);
$data = 0;
}
//Banned
else if ($row["Rank"] == "Banned"){
session_start();
$_SESSION["LoginDetails"] = array($StrUsername, "Banned");
$data = 1;
}
}
}
}
echo $data;
?>
Hopefully this helps you. Please say if you need more help!
You need to make ajax call on blur of username to check if user exists in database and on success of that you can make one more ajax to check for password match of that particular user. This will give you both cases whether a user exixts or not if exixts then does the password match or not only after that user will be logged in and then you can show the responsibilities of that particular user.
For username:
$('#Lname').blur(function(){
$.ajax({
url:'url where query for matching username from database',
data:'username collected from input on blur',
type:'POST',
success:function(data){
//Code to execute do on successful of ajax
}
})
})
For Password:
The ajax call remains the same only url, data and response changes

How to create a remember me function in login without using form in javascript or jquery

I'm almost done with my project, but the specifications for my login is not yet 100% done. Remember me function is not yet working.
HTML
<input type="text" id="signinId" class="email-input" placeholder="Email">
<input type="password" id="signinPwd" class="password-input" placeholder="Password">
<input id="rememberChkBox" type="checkbox">
<button id="Sign" class="button">Login</button>
Jquery Script
$(document).ready(function(){
$("#Sign").click(function(){
//Script for login is here...
});
});
I am not using form in this login page.
The specs is that when the checkbox is checked upon login, the user must be remebered. Once he logout, the textbox should be empty and when clicked on the #signinId input his username must be displayed.
It should look like this, if it is possible:
Sceenshot 1:
When email input is clicked
Screenshot 2: Autofill
Any help is very much appreciated.
Thank you in advance.
Auto Login system.
'Remember me' is not actually used to display user name and password on the login form because this feature is already provided by any browser. But it is intended for automatic login when users revisit the web.
To make auto login system without storing login credential on cookie is by adding database table that store userid and login_string.
Insert/Update the login_string every user login.
And when user login using remember me (press the radio button), then store the login_string on the cookie.
-------------------------------------------------------------------
id (ai) | userid | login_string (128 chars)
--------------------------------------------------------------------
1 | 1 | 86faabe4142269e2274df911a....
--------------------------------------------------------------------
2 | 2 | 013835e194d75c183dc914c9e....
Login_string must be a unique string and can be created by this way :
$login_string = hash('sha512', $userid . $_SERVER['HTTP_USER_AGENT'] . time());
The result is a unique 128 string length.
To store login_string on the cookie :
if(isset(post('remember_me')) {
$cookie_name = 'user_str_session';
$cookie_value = $login_string;
setcookie($cookie_name, $cookie_value, time() + (86400 * 1), "/"); // one day example
}
Next time the user close the browser and revisit the web ( where normally login session has expired ), then at the first page load, system will find the login_string and return the userid. By using this userid, system will create login session for automatic login.
Example script :
if(!isset($_SESSION['id'])) {
if(isset($_COOKIE['user_str_session'])) {
$user_string = $_COOKIE['user_str_session'] ;
$sql = "SELECT `userid` FROM `users_log` WHERE `string` =? ";
$query = $this->db->query($sql, $user_string);
$userid = $query->row()->userid;
if($userid) {
$_SESSION['id'] = $userid;
}
}
}
To prevent the login_string on a public computer, apply user logout by deleting the login_string on cookie.
function logout()
{
// remove cookie
setcookie("user_str_session", "", time() - 3600, "/");
session_destroy();
redirect('/');
}
This is only a brief description to create an automatic login system. Practically you can play with your own style and needs.
Its working perfectly for me..
You need Jquery.cookie.min.js..
$(function () {
if (localStorage.chkbox && localStorage.chkbox != '') {
$('#rememberChkBox').attr('checked', 'checked');
$('#signinId').val(localStorage.username);
$('#signinPwd').val(localStorage.pass);
} else {
$('#rememberChkBox').removeAttr('checked');
$('#signinId').val('');
$('#signinPwd').val('');
}
$('#rememberChkBox').click(function () {
if ($('#rememberChkBox').is(':checked')) {
// save username and password
localStorage.username = $('#signinId').val();
localStorage.pass = $('#signinPwd').val();
localStorage.chkbox = $('#rememberChkBox').val();
} else {
localStorage.username = '';
localStorage.pass = '';
localStorage.chkbox = '';
}
});
});
When login form has been sumbitted check the checkbox, if it has been checked, store the login form data including username and password in a related cookie. the next time a user comes to the page you can read the cookie, if it is set fill the form with the stored data.
this fiddle can help you:
https://jsfiddle.net/wrvnsst2/
you can use the below link to learn how to work with cookies in jquery:
http://www.sitepoint.com/eat-those-cookies-with-jquery/
some codes to explain more:
$(document).on(ready,function(){
fillByMemory()
$('button#sign').on('click',function(){
if($('#rememberChkBox').val()){
rememberMe();
}
doLogin();
});
});
function rememberMe(){
$.cookie('id',$('#signinId').val());
$.cookie('pass',$('#signinPwd').val());
}
function fillByMemory(){
if(!!$.cookie('id'))
$('#signinId').val($.cookie('id'));
if(!!$.cookie('pass'))
$('#signinPwd').val($.cookie('pass'));
}

Not allowing a user to move forward to logging in until given access [duplicate]

This question already exists:
Blocking a user from logging in with a certain permission level and then an alert displaying to let them know why
Closed 7 years ago.
I am trying to figure out how to deny a user access from signing in to my site unless they have been approved. I am making my site private to only those I allow to join. Anyone can register, but once they do they are given a permission/group level of 1 or 'bench'. Once I accept the user and change the permission level, then they are able to login.
As of now, I am stopping the level/group 1 users with a redirect back to the index page(where they sign in at). However, I want to not allow them to move forward to the next page at all. The reason being is I want to display some sort of pop up alert displaying a message that I created.
I'm not sure if I can do this with validation or the way I am trying to do it. I added on to my login code and am attempting to put my permission code I had on the signed in page to try to stop it from the start. Basically, in an attempt that if the user tries to log in, the script dies once it sees that the permission level is at the group 'bench'. Then a pop alert displays saying why.
I'm not having much success with it. My group/permission levels have a name and ID. I have tried putting both in this single quotatiob's like 'bench' and '1', but I get the same error with both.
Fatal error: Call to a member function hasPermission() on a non-object in /home4/pfarley1/public_html/example.com/index.php on line 12
I'm trying to log them in like this...
<?php
if(Input::exists()) {
if(Token::check(Input::get('token'))) {
$validate = new Validate();
$validation = $validate->check($_POST, array(
'username' => array('required' => true),
'password' => array('required' => true)
));
// added this line in
if($user->hasPermission('1')) {
die($permissionError);}
if($validation->passed()) {
$user = new User();
$remember = (Input::get('remember') === 'on') ? true : false;
$login = $user->login(Input::get('username'), Input::get('password'), $remember);
if($login) {
Redirect::to('userIndex.php');
} else {
$tryagain = '<span class="signinpanel">' . "The information you entered did not match our records." . '</span>';
}
} else {
foreach($validation->errors() as $error) {
echo $error, '<br>';
}
}
}
}
?>
My permission code for users..
public function hasPermission($key) {
$group = $this->_db->get('groups', array('id', '=', $this->data()->group));
if($group->count()) {
$permissions = json_decode($group->first()->permissions, true);
if($permissions[$key] == true) {
return true;
}
}
return false;
}
What am I doing wrong this this or is there a better way to do this?
Edit:
The last question wasn't specific enough, so I added info and there has been modification to the code in how I was trying to do this.
What is $user on line 12?
if($user->hasPermission('1')) {
Error message is pretty explicit.

PHP variable transfer from one page to another

I am building a game on html5(phaser js) for which i need to build a leaderboard. the code snippet is this:
restart_game: function() {
// Start the 'main' state, which restarts the game
//this.game.time.events.remove(this.timer);
//this.game.time.events.remove(this.timer2);
//this.game.state.start('main');
var string="score.php?score="+this.score;
window.open(string);
},
in the window.open function i wish to pass the value of score to another page where i will ask for the player's name and then insert both the score and the name to the database. But i am having trouble passing the score value across three pages.
How can i do this? Do I need AJAX or just PHP and Javascript is sufficient?
Can you use browser cookie? you can save score value in cookie and access it whenever you need? Read this on how to use cookies link https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
To save to cookie like this:
document.cookie="score=54; expires=Thu, 18 Dec 2013 12:00:00 GMT";
In PHP you can read cookie
if(isset(($_COOKIE['score'])) {
$score = $_COOKIE['score'];
}
To Read cookie in JS:
var score = document.cookie;
You may use the session variable for keeping the variable in the memory and it will be accessible untill your session is alive.
<?php
error_reporting(E_ALL);
session_start();
if (isset($_POST['session'])) {
$session = eval("return {$_POST['session']};");
if (is_array($session)) {
$_SESSION = $session;
header("Location: {$_SERVER['PHP_SELF']}?saved");
}
else {
header("Location: {$_SERVER['PHP_SELF']}?error");
}
}
$session = htmlentities(var_export($_SESSION, true));
?>
For more information look here Here
Find jQuery
restart_game: function() {
var score = this.score;
$.ajax({
url: 'save_score.php',
data: {score: score},
method: 'POST'
}).done(function() {
window.location = "other_page.php";
});
},
save_score.php
session_start();
if(isset($_POST['score']) && strlen($_POST['score']) > 0) {
$score = intval($_POST['score']);
$_SESSION['score'] = $score;
}
other_page.php
session_start();
var_dump($_SESSION);
You can use the $_SESSION variable in php to keep track of user related data in a session. It requires cookies.

Categories

Resources