Session Variable showing undefined - javascript

I have made the login page using ionic and it seems to work well. The $_SESSION variable also gets displayed after successfull login. Then in another php file, when I try to print the same session variable, it shows undefined or not set. Also, the session expires after refresh and it shows an alert to login again
Here is my login php code
<?php
ob_start();
session_start();
$errmsg_arr = array();
$errflag = false;
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers:{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
$errors = array();
$data = array();
// Getting posted data and decodeing json
$_POST = json_decode(file_get_contents('php://input'), true);
require_once 'db_functions.php';
$db = new db_functions();
if(empty($_POST['doc_key']))
{
$data['errors'] = 'Please enter all the credentials';
echo json_encode($data);
}
else if(empty($_POST['password']))
{
$data['errors'] = 'Please enter all the credentials';
echo json_encode($data);
}
else
{
$doc_key = $_POST['doc_key'];
$password = $_POST['password'];
$user = $db->getDoctorByEmailAndPassword($doc_key, $password);
if( $user == true)
{
//session_regenerate_id();
$_SESSION['name'] = $user["name"];
$_SESSION['contact'] = $user["contact"];
$_SESSION['email'] = $user["email"];
$_SESSION['license_no'] = $user["license_no"];
$_SESSION['type'] = $user["type"];
$_SESSION['gender'] = $user["gender"];
$_SESSION['location'] = $user["location"];
$_SESSION['fees'] = $user["fees"];
$_SESSION['experience'] = $user["experience"];
$_SESSION['doc_key'] = $user["doc_key"];
//session_write_close();
$data['message'] = $_SESSION['name'];// "User logged in successfully";
echo json_encode($data);
}
else
{
$data['errors'] = 'Login Credentials are invalid';
echo json_encode($data);
}
}
?>
This is the code of other page where I want to display the session variable
<?php
ob_start();
session_start();
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers:{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
$data = array();
$type_user = "";
if(isset($_SESSION['user_name']) || isset($_SESSION['license_no']))
{
if($type_user == "doctor")
{
$data["name"] = $_SESSION["name"];
$data["email"] = $_SESSION["email"];
$data["contact"] = $_SESSION["contact"];
$data["license_no"] = $_SESSION["license_no"];
$data["doc_key"] = $_SESSION["doc_key"];
$data["gender"] = $_SESSION["gender"];
$data["type"] = $_SESSION["type"];
$data["location"] = $_SESSION["location"];
$data["fees"] = $_SESSION["fees"];
$data["experience"] = $_SESSION["experience"];
echo json_encode($data);
}
else
{
$data["name"] = $_SESSION["name"];
$data["email"] = $_SESSION["email"];
$data["contact"] = $_SESSION["contact"];
$data["gender"] = $_SESSION["gender"];
$data["user_name"] = $_SESSION["user_name"];
echo json_encode($data);
}
}
else
{
$data["errors"] = "Please login first to see this";
echo json_encode($data);
}
?>
This page does not return the session data to controller. It shows blank
Here are the codes of controllers and ionic code
Controller for login page
.controller('doctorloginCtrl', function($scope,$http,$window) {
$scope.doctor = {};
$scope.loginDoc = function(){
$http({
method: 'POST',
url: 'http://localhost/drmedic/login_doctor.php',
data: $scope.doctor,
headers: {'ContentType': 'application/x-www-form-urlencoded'}
})
.success(function(data){
if(data.errors)
{
alert(JSON.stringify(data.errors));
}
else
{
alert(JSON.stringify(data.message));
$window.location.href = "#/home";
}
});
}
})
Controller for the other page where I want to show the details
.controller('profileCtrl', function($scope,$http,$ionicSideMenuDelegate,$window) {
$ionicSideMenuDelegate.toggleLeft();
$http({method: 'GET', url: 'http://localhost/drmedic/retrieve_login_details.php'}).success(function(data) {
if(data.errors)
{
alert(data.errors);
$window.location.href = "#/select-role";
}
else
{
$scope.contents = data;
console.log($scope.contents);
}
});
})
After login, when I go to the profile page by typing localhost:8100/#profile, it shows blank.. It does not display the {{contents.name}} field
IONIC CODE for Profile page
<ion-view title="Profile">
<ion-content overflow-scroll="true" padding="true" scroll="false" class="has-header">
Hi {{contents.name}}
</ion-content>
</ion-view>
The sessions used to work properly for my other project. Can't figure it out why it isn't working for this one. Is it because of the Authentication-Allow-Cross headers??
Please help.

Use Javascript localStorage Property. It will store data in your device until you remove it. So this is very easy to keep some data in the device. You can acccess it from anywhere in your code if it is exists.
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("lastname");
for more information visit https://www.w3schools.com/jsref/prop_win_localstorage.asp

Related

File upload request canceled on Angular 13

I'm making a script for a photographer website. We need to send pictures to the server via a PHP file. For info the host doesn't allow to modify php.ini.
So, the thing is: If I send files from my connection (fiber) everything works weel. But my friend doesn't have fiber. So I limited my bandwidth to 10MB/S. And there it's not working: the file is sent (around 17 sec execution) then I got a canceled request return.
Here is my angular code:
public sendFile(file: File): Observable<any> {
const formData = new FormData();
formData.append('thumbnail', file);
formData.append('action', 'uploadImage');
formData.append('pass', this.savedPass);
formData.append('format', file.type.replace('image/', ''));
return this.http.post<any>(environment.upload_address, formData, {
reportProgress: true,
observe: 'events',
headers: new HttpHeaders({ timeout: `20000` }),
});
}
And here is my PHP code (working weel with my fiber, so it must be something around max execution time):
<?php
ini_set('max_execution_time', '300');
set_time_limit ( 300 );
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
function checkAdmin($pass) {
include $_SERVER['DOCUMENT_ROOT']."/creds.php";
if(isset($pass) && !empty($pass) && $pass === $admin_pwd){
return true;
}
return false;
}
function generateKey($length){
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
$toReturn = '';
for($i = 0; $i < $length; $i++){
$newChar = $chars[random_int(0, strlen($chars))];
$toReturn .= $newChar;
}
return $toReturn;
}
function execQuery($query) {
include $_SERVER['DOCUMENT_ROOT']."/creds.php";
$mysqli = new mysqli($db_host.":".$db_port, $db_user, $db_pass, $db_name);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
exit();
}
$result = $mysqli->query($query);
if(is_bool($result)){
return [];
}
// Fetch all
$toReturn = [];
while($row = $result->fetch_assoc()){
array_push($toReturn, $row);
}
$mysqli->close();
return $toReturn;
}
header('Access-Control-Allow-Origin: http://localhost:4200');
header('Access-Control-Allow-Methods: POST');
header("Access-Control-Allow-Headers: *");
$allowed_types = [
'image/jpg',
'image/jpeg',
'image/png'
];
$isAdmin = false;
if(isset($_POST['pass']) && !empty($_POST['pass'])){
$isAdmin = checkAdmin($_POST['pass']);
}
if($isAdmin && isset($_FILES) && !empty($_FILES) && isset($_FILES['thumbnail']) && !empty($_FILES['thumbnail']) && in_array($_FILES['thumbnail']['type'], $allowed_types)){
$newKey = generateKey(10);
while(file_exists($_SERVER['DOCUMENT_ROOT'].'/'.'photos/'.$newKey.'.'.$_POST['format'])){
$newKey = generateKey(10);
}
move_uploaded_file($_FILES['thumbnail']['tmp_name'], $_SERVER['DOCUMENT_ROOT'].'/'.'photos/'.$newKey.'.'.$_POST['format']);
execQuery('INSERT INTO pictures (code, title, active) VALUES ("'.$newKey.'.'.$_POST['format'].'", "", 0)');
}
Does someone have asolution?

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

Ionic Angular pass data to PHPfile and insert into MySQL database

Something strange happen, I pass insert data from angular controller to php file. Next, php file is inserting data into MySQL database. All the data is successfully inserted. However once I click on button two record is inserted into MySQL database. One will the empty data is inserted and second is the data I entered from UI. The following is my code:
Javascript controller Code:
.controller('registerController',['$scope', '$stateParams', '$state', '$http', function($scope, $stateParams, $state, $http){
var userInformation = [];
$scope.registration = {};
console.log($stateParams.all);
$scope.doRegister = function () {
if( $scope.registration.pasword !== $scope.registration.confirmpassword){
alert("Password not match");
}
$http({
url: "http://localhost/php/chat.php",
method: "POST",
data: {
'username': $scope.registration.username,
'email': $scope.registration.emailaddress,
'password': $scope.registration.pasword
}
}).success(function(response) {
console.log(response);
}).error(function(response) {
console.log(response);
});
$state.go('login', {userInformation : userInformation});
};
$scope.goBack = function() {
$state.go('login');
}
}])
PHP Code
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$user = $request->username;
$email = $request->email;
$pass = $request->password;
$servername = "localhost";
$username = "jack";
$password = "1234";
$dbname = "chat";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO use_directory VALUES ('', '$user', '$email', '$pass');" ;
$retval = $conn->multi_query($sql);
if( $retval === TRUE) {
echo "Add successfully\n";
}else {
die('Could not edit data');
}
?>
Here is my database outcome
$sql = "INSERT INTO use_directory (user,email,pass) VALUES ( '$user','$email', '$pass')" ;
if(mysqli_query($conn, $sql)){
echo "Add successfully\n";
}else{
die('Could not edit data');
}
Have you tried like this? Hope it helps :)

call and execute a javascript file from a remote php file

I have an angularjs service that sends a rest api link to a php file, the problem is that , this php file is calling another php file which contains a javascript code. When I execute the code in the service, it executes the php file , but the javascript code is just printed out without being executed. It's been a whole day of research but without any solution. Please can you tell me where the problem is? I have used require 'secondFile.php'; and include 'secondFile.php'; , I have also tried to bring the whole javascript code from the second file to the first file, so that I call the javascript locally, but it always prints the code without executing it.
Here is my code:
The angularjs service function:
var link = 'http://path/to/first.php';
$http.post(link, {idf : newDoc.idf})
.success(function (res){
console.log(res);
}).error(function (err) {
console.log(err);
});
the first php file, which is a remote file
<?php
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400');
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
$method = $_SERVER['REQUEST_METHOD'];
//$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'),true);
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
var_dump($request);
$idf= $request->idf;
$val= $request->val;
switch ($method) {
case 'POST':
insertit($idf, $val);
break;
case 'PUT':
updateit();
break;
case 'REMOVE':
removeit();
break;
}
}
catch(PDOExecption $pe) {
echo "okay";
print "ERROR!".$pe->getMessage();
die();
}
function insertit($idf, $val) {
include 'connect.php';
$dataBilan = array($val);
$stmt = $DB->prepare("INSERT INTO `Test` (val) VALUES (?)");
$stmt->execute($dataBilan);
$last = $DB->lastInsertId();
$idf= $last;
$info_bilan= array(
'val' =>$val
);
$data = array(
'idf'=>$last,
'action'=>'update',
'table'=>'activite',
'data' =>$info_bilan
);
require 'second.php';
echo "okay done inserting";
}
and second.php:
<script src="pouchdb-5.3.1.min.js"></script><script type="text/javascript" language="javascript">
var dbRemote = new PouchDB('http://localhost:5984/Mydatabase');
var myDocs;
var value = <?php echo json_encode($data); ?>;
console.log(JSON.stringify(value));
if((value.idf != null) && (value.idf != 0))
{
console.log("-------here we go----");
dbRemote.allDocs({include_docs: true}).then(function (res) {
myDocs = res.rows.map(function (row) {
return row.doc; });
onUpdate(value);
});
}
}
function binarySearch(arr, docId) {
var low = 0, high = arr.length, mid;
while (low < high) {
mid = (low + high) >>> 1; // faster version of Math.floor((low + high) / 2)
arr[mid].id < docId ? low = mid + 1 : high = mid
}
return low;
}
function onUpdate(value)
{
console.log("couchdb's "+ myDocs.length);
if(myDocs.length !=0)
{
console.log("haha");
var index = binarySearch(myDocs, value.idf);
var doc = myDocs[index];
if(action== "update")
{
dbRemote.put(doc).then (function () {
console.log("Updated! ");
}).catch(function (err) {
console.log(err);
});
}
}
}
</script>
The content of second.php file is just printed out but it's not executed. When I execute first.php everything goes right , but when I execute the service I just see the printed file. Please any ideas?
Example:
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$stream = ssh2_exec($connection, '/usr/local/bin/php -i');

EOF / Failed to load error when calling PHP file with AJAX

Apparently my POST requests are being cancelled?
http://puu.sh/d73LC/c6062c8c07.png
and also, mysqli_result object has all null values when i query the database with a select query:
object(mysqli_result)[2]
public 'current_field' => null
public 'field_count' => null
public 'lengths' => null
public 'num_rows' => null
public 'type' => null
here is my php file:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "uoitlol";
$name = "test1"; //this should be $_POST['name']; test1 is just to test if it works.
$err = false;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_errno > 0) {
echo 'connerr';
die();
}
$sql = "INSERT INTO summoners (name) VALUES (?)";
$getname = "SELECT name FROM summoners";
$result = $conn->query($getname);
while ($row = $result->fetch_assoc()) {
echo 'name : ' . $row['name'];
if ($row['name'] === $name) {
echo 'error, name exists';
$err = true;
}
}
$stmt = $conn->prepare($sql);
$stmt->bind_param('s', $name);
if ($err === false) {
if (!$stmt->execute()) {
echo 'sqlerr';
} else {
echo 'success';
}
}
$stmt->close();
mysqli_close($conn);
here is my javascript file, which calls the php file with ajax whenever i click submit on my form (in a different html file)
$(document).ready(function () {
$("#modalClose").click(function () {
document.getElementById("signupInfo").className = "";
document.getElementById("signupInfo").innerHTML = "";
});
$("#formSubmit").click(function () {
var name = $("#name").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = {'name' :name};
if (name === '')
{
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>Please enter a summoner name!</b>";
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "submitName.php",
data: dataString,
cache: false,
success: function (msg) {
if (msg === 'error'){
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>That summoner name is already in the database!</b>";
} else if (msg === 'sqlerror'){
document.getElementById("signupInfo").className = "alert alert-danger";
document.getElementById("signupInfo").innerHTML = "<b>SQL error, contact the administrator.</b>";
} else if (msg === 'success'){
document.getElementById("signupInfo").className = "alert alert-success";
document.getElementById("signupInfo").innerHTML = "<b>Summoner successfully added!</b>";
}
}
});
}
return false;
});
});
I'm getting these errors everytime I click my button that submits my form:
Failed to load resource: Unexpected end of file from server (19:41:35:538 | error, network)
at public_html/submitName.php
Failed to load resource: Unexpected end of file from server (19:41:35:723 | error, network)
at public_html/submitName.php
Failed to load resource: Unexpected end of file from server (19:41:36:062 | error, network)
at public_html/submitName.php
I'm using Netbeans IDE, if that matters.
puu.sh/d6YXP/05b5f3dc06.png - screenshot of the IDE, with the output log errors.
Remove this from your submitName.php, unless there really is HTML in it.
<!DOCTYPE html>
If there is HTML in it, do this instead.
<?php
//your PHP code//
?>
<!DOCTYPE html>
//your HTML here//
</html>
Also, if submitName.php contains no HTML, make sure there is no blank line after ?> at the bottom.
EDIT: In regards to your query failing, try this code.
if (!empty($name) { //verify the form value was received before running query//
$getname = "SELECT name FROM summoners WHERE name = $name";
$result = $conn->query($getname);
$count = $getname->num_rows; //verify a record was selected//
if ($count != 0) {
while ($row = $result->fetch_assoc()) {
echo 'name : ' . $row['name'];
if ($row['name'] === $name) {
echo 'error, name exists';
$err = true;
}
}
} else {
echo "no record found for name";
exit;
}
}
Drop the ?> at the end of the php file and instead of using var dataString = 'name=' + name; use this instead:
var data = { "name" : name};
jQuery will automagically do the dirty stuff for you so that you don't have to special text-escape it and stuff.
That's as far as I can help without any log files and just a quick skim of your code.

Categories