I dont get session object in php - php

i starting with php and i want get session object in login form, then, i want show values the object session in a php web page but session object not read their values object.
my php file:
try {
$userLogin = new userDto();
$userLogin->setUsername($_POST["txtUsername"]);
$userLogin->setPassword($_POST["txtPassword"]);
if (UserDao::validateLogin($userLogin)) {
//if true, the method validateLogin load other values object in data access layer
//i tried with print_r($userLogin) and show all values (name,age,ocupation, profile etc....).. works
session_start();
if ($userLogin->getIdProfile() == 1) {
$_SESSION["userClient"] = $userLogin;
include_once '../Pages/MenuClient.php';
} else {
$_SESSION['adminUser'] = $userLogin;
include_once '../Paginas/MenuAdmin.php';
}
} else {
echo 'No exist';
}
} catch (Exception $ex) {
echo $ex->getMessage();
}
php web page:
<?php
include_once '../../Dto/UserDto.php';
$dto = new UserDto();
if(isset($_SESSION["userClient"])) {
$dto = $_SESSION["userClient"];
echo 'Exist user'; --> works!!
echo '<script type="text/javascript">alert("'+$dto->getName()+'");</script>'; --> not work
else {
echo '<script type="text/javascript">alert("no found");</script>';
}
?>
<label><?php echo $dto->getName()?></label> --> not work
<label value="<?php echo $dto->getName()?>"></label> --> not work

Related

PHP session variable cannot be read in other page

I am building a login page using php.
I don't know why the session variable does not work.
Here is my login.php
<?php
function loginFail()
{
echo "<script> alert(\"Invalid user name or password\");";
echo "location.href=\"index.php\";";
echo "</script>";
}
if (empty($_POST["loginName"])|| empty($_POST["adminPwd"])) {
loginFail();
} else {
$userName=$_POST["loginName"];
$password=$_POST["adminPwd"];
if (($userName=="user") && ($password=="password")) {
session_start();
$_SESSION["isLogined"]="Ok";
header("location:admin.php");
} else {
loginFail();
}
}
?>
Here is admin.php
<?php
include 'checkSession.php';
?>
This is checkSession.php source code
<?php
function loginFail()
{
echo "<script> alert(\"Session Expired, please login again\");";
echo "location.href=\"index.php\";";
echo "</script>";
}
echo $_SESSION["isLogined"];
?>
The output of checkSession.php is :
Undefined variable: _SESSION
I have tried replace
header("location:admin.php");
with
echo "<script>";
echo "location.href=\"admin.php\";";
echo "</script>";
However, it still does not work.
Furthermore, I have tried replace :
header("location:admin.php");
With
echo $_SESSION["isLogined"];
It can display the word "Ok".
Would you tell me how to fix the problem?

How can I show items based on Session Variable php

Trying to display this data in the diary post page solely based on the Session variable.
The Session variable is already declared in the php/ functions file.
The data foreign key is already linked between the User ID in the accounts table and the diary post table in PHP my admin
I just need an Inner join query of some description to only show the data based on Session.
Functions declared at the top of diary page
<?php
include("php/functions.php");
$userID = $_SESSION["userID"];
?>
The functions file
<?php
if(session_id() == '') {
session_start();
}
if(!isset($_SESSION['myEmail'])){ //if login in session is not set
header("Location: login.php");
}
if (!isset($_SESSION['myEmail'])) {
echo" <a href='login.php'";
}
else {
$myFName = $_SESSION['userFirstName'];
}
Where I need to display the posts based on Session variable
<?php
// index.php
include 'mysql.php';
echo '<h1>My Positive Experience Diary</h1>';
echo "<em>Post 10 Positive Recent Experiences</em><hr/>";
$result = mysql_safe_query('SELECT * FROM posts ORDER BY date DESC');
if(!mysql_num_rows($result)) {
echo 'No posts yet.';
} else {
while($row = mysql_fetch_assoc($result)) {
echo '<h2>'.$row['title'].'</h2>';
$body = substr($row['body'], 0, 300);
echo nl2br($body).'...<br/>';
echo 'Read More | ';
echo '<hr/>';
}
}
echo <<<HTML
+ New Post
HTML;
?>
The mysql.php where the diarypost page is getting its data.
<?php
// mysql.php
function mysql_safe_string($value) {
$value = trim($value);
if(empty($value)) return 'NULL';
elseif(is_numeric($value)) return $value;
else return "'".mysql_real_escape_string($value)."'";
}
function mysql_safe_query($query) {
$args = array_slice(func_get_args(),1);
$args = array_map('mysql_safe_string',$args);
return mysql_query(vsprintf($query,$args));
}
function redirect($uri)
{
if (!headers_sent())
{
header('Location: '.$uri);
exit;
}
else
{
echo '<script type="text/javascript">';
echo 'window.location.href="'.$uri.'";';
echo '</script>';
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0;url='.$uri.'" />';
echo '</noscript>'; exit;
}
}
#mysql_connect('localhost','########','########');
#mysql_select_db('########');
What it looks like posting all the data from the database not based on User ID
enter image description here

Add/attach a UserID based on Session PHP

Looking to add a UserID based on session variable to this post method.
I can display the diary posts based on the Session ID but want to actually add the User's ID into the corresponding table everytime an entry is posted.
I've included pictures of the database below and the Insert Query that already adds posts.
The diary and tblUseraccount are already linked using foreign keys
PHP functions
<?php
if(session_id() == '') {
session_start();
}
if(!isset($_SESSION['myEmail'])){ //if login in session is not set
header("Location: login.php");
}
if (!isset($_SESSION['myEmail'])) {
echo" <a href='login.php'";
}
else {
$myFName = $_SESSION['userFirstName'];
}
The code I want to insert the UserID too
<?php
// post_add.php
if(!empty($_POST)) {
include 'mysql.php';
if(mysql_safe_query('INSERT INTO posts (title,body,date,) VALUES (%s,%s,%s)', $_POST['title'], $_POST['body'], time()))
echo 'Entry posted. View';
else
echo mysql_error();
}
?>
The mysql.php portion
<?php
// mysql.php
function mysql_safe_string($value) {
$value = trim($value);
if(empty($value)) return 'NULL';
elseif(is_numeric($value)) return $value;
else return "'".mysql_real_escape_string($value)."'";
}
function mysql_safe_query($query) {
$args = array_slice(func_get_args(),1);
$args = array_map('mysql_safe_string',$args);
return mysql_query(vsprintf($query,$args));
}
function redirect($uri)
{
if (!headers_sent())
{
header('Location: '.$uri);
exit;
}
else
{
echo '<script type="text/javascript">';
echo 'window.location.href="'.$uri.'";';
echo '</script>';
echo '<noscript>';
echo '<meta http-equiv="refresh" content="0;url='.$uri.'" />';
echo '</noscript>'; exit;
}
}
#mysql_connect('localhost','######','#######');
#mysql_select_db('######');
enter image description here
enter image description here
Firstly you need to set UserId in session
when you make the user login you can add the user id in session like you have added userFirstName
After that you can just start sessions in your file and then get the userId from session when you want to insert a post
session_start();
if(!empty($_POST)) {
include 'mysql.php';
$userId = $_SESSION['UserID']; //or whatever is your key in session where you store the user id
if(mysql_safe_query('INSERT INTO posts (title,body,date,UserID) VALUES (%s, %s, %s, %s)', $_POST['title'], $_POST['body'], time(), $userId)){
echo 'Entry posted. View';
}else{
echo mysql_error();
}
}
Also I noticed that your are using mysql_query to run your queries. You should use mysqli_query or PDO because mysql_query is deprecated in PHP 5.5 and it is removed in PHP 7.
You can read more in php page here

Session Doctrine in REST API

I need to control a session in a REST API. My REST API is implemented with slim and doctrine and within the routes.php file I have defined the POST request of the login:
session_start();
$app->post('/login', function ($request, $response) {
$em = getEntityManager();
$args = $request->getParsedBody() ?? json_decode($request->getBody(), true);
$user = $em->getRepository(Usuario::class)->findOneByUsername($args['username']);
if (null == $user) {
echo "<script language='javascript'>alert('User not found'); window.location='App.php'</script>" ;
} else {
if ($user->getPassword() == $args['password']){
$_SESSION['id'] = $user->getId();
$_SESSION['username'] = $user->getUsername();
if($user->getAdmin() && $user->getEnabled()){
echo "<script language='javascript'>window.location='Admin.php'</script>" ;
} else if($user->getEnabled()){
echo "<script language='javascript'>window.location='Comparator.php'</script>" ;
} else {
echo "<script language='javascript'>alert('Account
inabilited'); window.location='App.php'</script>" ;
}
} else {
echo "<script language='javascript'>alert('Incorrect Password'); window.location='App.php'</script>" ;
}
}
});
I have 3 page .php. In page App.php I have an access form. I want to do is that when any user wants to enter the Admin or Comparator page, he can not enter without logging in previously.
For this I have added the following code to the pages previously named:
<?php if (session_status() != "PHP_SESSION_ACTIVE" && session_status() != 2) { ?>
<script>window.location='App.php'</script>
<?php }?>
But when entering a valid username and password I get the following error:
It's very weird because the field username in the class Usuario exists.
Any solutions?

Strange Password_Hash Issue

So im using the exact same script as I used to a while back and for some reason when I move to my new domain and hosting it is having really weird issues, I created a user and got hm to try login, It wasnt working for him I got a new hash from a random test.php file with this php:
<?php
/**
* In this case, we want to increase the default cost for BCRYPT to 12.
* Note that we also switched to BCRYPT, which will always be 60 characters.
*/
$options = [
'cost' => 9,
];
echo password_hash("His Pass", PASSWORD_BCRYPT, $options)."\n";
?>
It then worked, He logged in fine and I then tried to login to my main admin account and for some reason its now not working even when I try remaking the hash 2 times now.
I have no idea whats going on can someone please enlighten me.
Heres the login code:
//If User Submits Form continue;
if(isset($_POST['username'])) {
//If the captcha wasn't submitted;
if(empty($_POST['g-recaptcha-response'])) {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "nocaptcha");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "nocaptcha");</script> <?php
}
//If the captcha was submitted;
} else {
//Set captcha variable to the Submitted Captcha Response;
$captcha=$_POST['g-recaptcha-response'];
//Captcha Verification Url;
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=t&response=';
//JSON Encode the Captcha's response and Site IP;
$response = json_decode(file_get_contents($url.urlencode($captcha).'&remoteip='.$_SERVER['REMOTE_ADDR']), true);
//If the captcha wasn't verified;
if($response['success'] == false) {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "captchafailed");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "captchafailed");</script> <?php
}
//Otherwise if it was verified;
} else {
//Try log in with the given details;
user_login($_POST['username'],$_POST['password']);
//If logged in redirect and give a notification;
if(loggedin()) { ?>
<script type="text/javascript">localStorage.setItem("notification", "loggedin");</script>
<meta http-equiv="refresh" content="0;URL='https://gameshare.io'" /> <?php
} else {
//And theres already a try with there IP;
if($trycount != '0') {
//Increment there try count and give a notification;
updateTries(); ?>
<script type="text/javascript">localStorage.setItem("notification", "loginfailed");</script> <?php
//If there isn't a try on there IP yet;
} else {
//Add one try and give a notification;
addTry(); ?>
<script type="text/javascript">localStorage.setItem("notification", "loginfailed");</script> <?php
}
}
}
}
}
User_login function:
//Create a new function named user_login;
function user_login($username = false, $password = false) {
//Fetch for the username and password applied;
$st = fetch("SELECT username,password,email,image FROM users WHERE username = :username",array(":username"=>$username));
//If a row was found continue
if($st != 0) {
$storedhash = $st[0]['password'];
if (password_verify($password, $storedhash)) {
//Set a new username session and set it the username;
$_SESSION['username'] = $username;
$_SESSION['email'] = $st[0]['email'];
$_SESSION['image'] = $st[0]['image'];
if($username == 'admin') {
$_SESSION['role'] = 'admin';
} else {
$_SESSION['role'] = 'user';
}
}
}
//If no errors happened Make the $valid true;
return true;
$dontaddtry = true;
}
Fetch function:
//Create a new function named fetch;
function fetch($sql = false,$bind = false,$obj = false) {
//Prepare The SQL Query;
$query = Connect()->prepare($sql);
//Execute Binded Query;
$query->execute($bind);
//While Fetching Results;
while($result = $query->fetch(PDO::FETCH_ASSOC)) {
//Add a row to the results respectiveley;
$row[] = $result;
}
//If there are no rows;
if(!empty($row)) {
//Make it an object;
$row = ($obj)? (object) $row : $row;
} else {
//Else row is false;
$row = false;
}
//If no errors happened Make $row true;
return $row;
}
Connect Function:
//Create a new function named LoggedIn, And apply database info;
function Connect($host = 'localhost',$username = 'x',$password = 'x',$dbname = 'x') {
//Try execute the PHP with no errors;
try {
//Create a PDO Session;
$con = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
//Session Attributes;
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
//Catch all PDOException errors;
catch (PDOException $e) {
//If any errors print result;
echo "<code><pre>".print_r($e)."</pre></code>";
//Make the PDO session false;
$con = false;
}
//If no errors happened Make the PDO session true;
return $con;
}
P.S If you wish to get an account to try on my site let me know and ill make a temporary account.
Make sure your the php version of your new hosting. password_hash needs at-least PHP 5.5.0.
You can check your current PHP version via following code.
<?php
echo 'Current PHP version: ' . phpversion();
?>

Categories