how to pass variables between 2 php files - javascript

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

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.

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

after insert no return anything but data have been save

<?php
$host="localhost";
$user="root";
$password="";
$con=mysqli_connect("localhost","root","","recipe");
if ($_GET['type'] == "upload")
{
$title=$_GET['title'];
$creator=$_GET['creator'];
$ingredient=$_GET['ingredient'];
$serving=$_GET['serving'];
$note=$_GET['note'];
$prepare=$_GET['prepare'];
$insertsql = "INSERT INTO upload (title,creator,ingredient,serving,note,prepare)
VALUE ('$title','$creator','$ingredient','$serving','$note','$prepare')";
if(mysql_query($insertsql,$db))
{echo 1; }
else
{echo 0; }
}
?>
<script>
$.ajax({
type : "get",
url : "dataconn.php",
data : "type=upload&title="+title+"&prepare="+prepare+"&creator="+creator+"&ingredient="+ingredien t+"&serving="+serving+"&note="+note,
success : function(data){
alert(data);
}
});
</script>
</head>
</html>
When I pass variable in to PHP from JavaScript it able to save in database but I need some value like the data have been successful save and will come out a alert 1 or 0.
But once I connect to database it cant alert any more. Like some error blocking in database but still can save just does not come out any alert. If I remove it then it running all
It does not sure alert as well.
Change this line:
if(mysql_query($insertsql,$db))
To this line; using mysqli_* extensions and correctly using $con for the query instead of $db which is a connection variable you don’t have set anywhere:
if(mysqli_query($con,$insertsql))
Also, you should set your MySQL calls to return errors like this:
$con=mysqli_connect("localhost","root","","recipe") or die(mysqli_connect_errno());
And change this as well:
$result = mysqli_query($con,$insertsql) or die(mysqli_connect_errno());
if ($result) {
echo 1;
}
else {
echo 0;
}
Also you are using VALUE in the query when it should be VALUES:
$insertsql = "INSERT INTO upload (title,creator,ingredient,serving,note,prepare)
VALUES ('$title','$creator','$ingredient','$serving','$note','$prepare')";
Not to mention in your JavaScript AJAX code you have +ingredien t+ when it should be +ingredien t+:
data : "type=upload&title="+title+"&prepare="+prepare+"&creator="+creator+"&ingredient="+ingredient+"&serving="+serving+"&note="+note,
At the top why are you setting variables for the MySQL connection but then putting values inline?
$host="localhost";
$user="root";
$password="";
$con=mysqli_connect("localhost","root","","recipe");
And finally, I did a cleanup of your main MySQL logic code. I have included mysqli_stmt_bind_param, mysqli_free_result & mysqli_close and set a foreach loop for $_GET values. This simply should work:
// Credentials.
$host="localhost";
$user="root";
$password="";
// Connecting, selecting database
$con = mysqli_connect($host, $user, $password, 'recipe') or die(mysqli_connect_errno());
if (isset($_GET['type']) && !empty($_GET['type']) && $_GET['type'] == "upload") {
// Set a '$_GET' array and roll through each value.
$get_array = array('title', 'creator', 'ingredient', 'serving', 'note', 'prepare');
foreach ($get_array as $get_key => $get_value) {
$$get_value = isset($_GET[$get_value]) && !empty($_GET[$get_value]) ? $_GET[$get_value] : null;
}
// Set the query.
$insertsql = "INSERT INTO `upload` (`title`, `creator`, `ingredient`, `serving`, `note`, `prepare`)"
. " VALUES (?, ?, ?, ?, ?, ?)"
;
// Bind the params.
mysqli_stmt_bind_param($insertsql, 'ssssss', $title, $creator, $ingredient, $serving, $note, $prepare);
// Run the query.
$result = mysqli_query($con, $insertsql) or die(mysqli_connect_errno());
if ($result) {
echo 1;
}
else {
echo 0;
}
// Free the result set.
mysqli_free_result($result);
// Close the connection.
mysqli_close($con);
}

Ajax setting cookies

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

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