How do I access $_SESSION in an included file? - php

Here is my code:
My root directory is: root
An index.php file located at the root/index.php
<?php
require_once('root/includes/initialize.php');
<?php template('header.php', 'TITLE');?>;
?>
<div id="main">
//SOME CONTENT
</div>
My initialize.php file gets all my core include files and puts them into one "require_once". Located in root/includes/initialize.php
<?php
//Define Path
defined('LIB_PATH') ? null : define('LIB_PATH', 'root/includes/');
//Core Functions
require_once(LIB_PATH.'functions.php');
//Core Objects
require_once(LIB_PATH.'_database.php');
require_once(LIB_PATH.'_session.php');
//Classes
require_once(LIB_PATH.'_user.php');
?>
updated**
My functions.php file includes a simple templating function that grabs a template file such as my header.php. It is located in root/includes/functions.php
<?php
//Templating
function template($path="", $pageTitle=NULL) {
if ($pageTitle != NULL) {
$_POST['page_title'] = $pageTitle;
}
include(root/public/templates/'.$path);
}
?>
My _session.php file takes care of my session control. Located in root/includes/_session.php
<?php
/**
* Class for Sessions
*/
class Session
{
public $logged_in = FALSE;
public $uid;
function __construct() {
session_start();
$this->check_login();
}
public function check_login() {
if (isset($_SESSION['uid'])) {
$this->uid = $_SESSION['uid'];
$this->logged_in = TRUE;
} else {
unset($this->uid);
$this->logged_in = FALSE;
}
}
public function logged_in() {
return $this->logged_in;
}
public function login($user) {
if ($user) {
$this->uid = $_SESSION['uid'] = $user;
$this->logged_in = TRUE;
}
}
public function logout() {
unset($_SESSION['uid']);
session_unset();
session_destroy();
redirect(WEB_ROOT);
}
}
$session = new Session();
?>
updated**
My header.php holds the top of all the pages in my site. Located in root/public/templates/header.php. This is the file I'm having trouble with, I cant figure out why I am unable to echo out the $session->uid or the $_SESSION['uid'] in this file.
<html>
<head>
<!--CSS-->
<link rel="stylesheet" type="text/css" href="root/public/css/style.css">
<title>MY SITE</title>
</head>
<body>
<div id="header">
<div id="logo">
<?php echo $_POST['page_title'];?>
</div>
<?php echo $session->uid;?> //DOESN'T WORK
</div>
I am able to echo out everything just fine in my index.php file and the other files on my site, but not in the included header.php. Any one know why? Thanks.

session_start() must be called at the start of EVERY php file that is going to either set or get a session variable. The only place I see you calling session_start() is in the one file.
http://www.php.net/manual/en/session.examples.basic.php
<?php
session_start();
if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0;
} else {
$_SESSION['count']++;
}
?>
Also on a side note. I'm looking at your class Session and I'm not seeing any $mySession = new Session(); anywhere to also start a session.
UPDATE:
I recreated your basic file structure and code in my IDE and got it work by adding this line in the class.
public function check_login() {
if (isset($_SESSION['uid'])) {
$this->uid = $_SESSION['uid'];
$this->logged_in = TRUE;
}
else {
unset($this->uid);
$this->logged_in = FALSE;
$_SESSION['uid'] = session_id();
/*Add this next line */
$this->uid = $_SESSION['uid'];
}
}
The first time I ran index.php just the <?php echo $_SESSION['uid']; ?> part of header worked. Refreshed and <?php echo $session->uid; ?> also worked so it echoed twice. This tells me your class isn't assigning the ID to a class variable, hopefully this is the desired out come as it worked on my end, or you can tweek it as needed.
UPDATE 2:
Function File (edit to match your paths but you need to return a string)
<?php
//Templating
function template($path = "", $pageTitle = NULL) {
if ($pageTitle != NULL) {
$_POST['page_title'] = $pageTitle;
}
return "$path";
}
?>
Then in the Index.php file add this way instead:
<?php
require_once('initialize.php');
include(template('header.php', 'TITLE'));
//include('header.php');
?>
<div id="main">
//SOME CONTENT
</div>
</body>
</html>
_session.php file:
<?php
/**
* Class for Sessions
*/
class Session
{
public $logged_in = FALSE;
public $uid;
function __construct() {
session_start();
$this->check_login();
}
public function check_login() {
if (isset($_SESSION['uid'])) {
$this->uid = $_SESSION['uid'];
$this->logged_in = TRUE;
}
else {
unset($this->uid);
$this->logged_in = FALSE;
$_SESSION['uid'] = session_id();
$this->uid = $_SESSION['uid'];
}
}
public function logged_in() {
return $this->logged_in;
}
public function login($user) {
if ($user) {
$this->uid = $_SESSION['uid'] = $user;
$this->logged_in = TRUE;
}
}
public function logout() {
unset($_SESSION['uid']);
session_unset();
session_destroy();
redirect(WEB_ROOT);
}
}
$session = new Session();
?>
And header.php
<html>
<head>
<!--CSS-->
<link rel="stylesheet" type="text/css" href="style.css">
<title>MY SITE</title>
</head>
<body>
<div id="header">
<div id="logo">
<?php echo $_POST['page_title'];?>
</div>
<?php echo $session->uid; ?> //WORKS NOW
<?php echo $_SESSION['uid']; ?> //WORKS NOW
</div>

The question is pretty vague. My guess would be, that since your index.php file in located in root/index.php, then your include paths:
require_once('root/includes/initialize.php');
include('root/public/templates/header.php');
are incorrect. You don't start with a /, so paths are relative, and considering the location of your index.php, you are including root/root/includes/initialize.php. If that's the case, you should easily spot that by the lack of <title>MY SITE</title> and TITLE on your page. Haven't you?
If that's the problem, I suggest you define some kind of HOME constant, for example
define ('HOME', dirname(__FILE__));
// or define ('HOME', __DIR__); depending on your PHP version
so that you can then include everything relative to that constant
require_once(HOME . '/includes/initialize.php');
Other than that I don't see any errors in your code.

Related

View class maintain variables from controller request

I'm loading the main view within the controller home as following:
class Home
{
public static function login()
{
Views::load('frontend/index', ['view' => 'account/login', 'name' => 'Stackoverflow']);
}
}
Now as you can see the view being loaded is frontend/index but I also say what is the view that must be loaded afterwards account/login.
So in the frontend/index.php file I have the following:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php Views::load($view); ?>
<?php echo $name; // prints 'stackoverflow' ?>
</body>
</html>
What happens is that I'm able to access the variable $name in the frontend/index file but not in the account/login file.
The account/login.php file contains:
<h2>Hello: <?php echo $name; // shows error saying 'Undefined variable: name' ?></h2>
The error just tells me that the variable is not being cached/stored.
Finally my view class has the following structure:
<?php
class Views
{
public static function load($file, $data = null)
{
if(file_exists(VIEWS_PATH . $file . '.php') == FALSE)
throw new Exception('View not found');
if($data != null)
extract($data, EXTR_SKIP);
ob_start();
require_once(VIEWS_PATH . $file . '.php');
$content = ob_get_contents();
ob_end_clean();
// prints the view
echo $content;
}
}
What can I do in order to allow the variables sent by controller to be cached/stored and called in multiple views?

what could make session that was set in login page but lost when redirect?

I have a problem with my script. I have been using this same script for months. Lat week I got a message from my client that cannot access their
dashboard anymore. I check it was showing too much redirect problem. I
quickly made attempt to solve this programming but all availed. I found out
that the session actually set on the Login page because I echo it out
without redirecting, but whenever I redirect to member dashboard the session
variable will be undefined. I have gone through other people similar problem
on this forum but none were able to proffer solution to my problem. Because
this same script has been working for months. Please take a look at the code
and help me out.
This is Login page. Login.php The session actually set because when display LoginId when I echo echo it out. but lost when redirecting to another page. though It was working for more four months before this unexpected problem
<?php
require("includes/config.php");
require_once(ROOT_PATH . "main/class.member.php");
$auth_member = new MEMBER();
if($auth_member->is_loggedin() != ""){
$auth_member->redirect(BASE_URL.'member');
}
if(isset($_POST['loginMemBtn'])){
$userLoginID = strip_tags($_POST['userID']);
$password = strip_tags($_POST['password']);
if($auth_member->memberLogin($userLoginID, $password)){
$auth_member->redirect(BASE_URL.'member');
}
else{
$error[] = "Inccorrect Login Details!";
}
}
?>
class.member.php
This is the class that holds all the member details and where the session
was set. It contain MemberLogin Function
<?php
session_start();
error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once(ROOT_PATH.'includes/dbconnect.php');
// Class
class MEMBER{
private $connect;
public function __construct(){
$database = new Database();
$db = $database->dbConnection();
$this->connect = $db;
}
public function lastInsertId(){
return $this->connect->lastInsertId();
}
public function runQuery($sql){
$stmt = $this->connect->prepare($sql);
return $stmt;
}
public function memberLogin($userLoginID, $password){
try {
$stmt = $this->connect->prepare("SELECT * FROM members
WHERE status='Active'
AND (email=:email OR phone=:phone OR username=:email)
");
$stmt->execute(array(':email'=>$userLoginID, ':phone'=>$userLoginID));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0) {
if(password_verify($password, $userRow['password'])) {
$_SESSION['member_session'] = $userRow['login_id'];
return true;
}else{
return false;
}
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
public function is_allowuser(){
if(isset($_SESSION['member_session'])) {
return true;
}
}
public function redirect($url){
header("Location: $url");
}
public function doMememberLogout(){
session_destroy();
unset($_SESSION['member_session']);
return true;
}
}
?>
session.php this file that check whether session is set or not and it
include i to all other script
<?php
$session = new MEMBER();
if(!$session->is_allowuser()){
$session->redirect(BASE_URL.'login');
exit();
}else{
$auth_member = new MEMBER();
$loginID = $_SESSION['member_session'];
$stmt = $auth_member->runQuery("SELECT * FROM members WHERE
login_id=:loginID");
$stmt->execute(array(":loginID"=>$loginID));
$userInfo = $stmt->fetch(PDO::FETCH_ASSOC);
if($userInfo['status'] != 'Active'){
unset($_SESSION['member_session']);
}
}
?>
This is dashboard.php this is the page that member redirect to from Login
Page
<?php
require("../includes/config.php");
require_once(ROOT_PATH . "main/class.member.php");
require_once(ROOT_PATH . "main/session.php");
//echo $_SESSION['member_session'];
?>
public function redirect($url){
header("Location: $url");
exit;
}
Use exit after header call in redirect method of class.member.php file

In my ecommerce website purchase confimation page show a warning message [duplicate]

This question already has answers here:
PHP sessions that have already been started [duplicate]
(11 answers)
Closed 5 years ago.
I am trying to developing a ecommerce website. But My problem is in product purchase confirmation page.It show this type of message: (Notice: A session had already been started - ignoring session_start() in C:\xampp\htdocs\online shop\dataAccessLayer\dalSession.php on line 6) I need to some suggestion how can I solve this issue.
Here is my code.
This is my dalSession.php page:
<?php
class Session
{
public static function Start(){
session_start(); //line 6
}
public static function Set($key , $value){
$_SESSION[$key] = $value;
}
public static function Get($key){
if (isset($_SESSION[$key])) {
return $_SESSION[$key];
}
else{
return false;
}
}
public static function Stop(){
session_destroy();
header("Location:user/login.php");
}
public static function StopA(){
session_destroy();
header("Location:../user/login.php");
}
public static function StopB(){
session_destroy();
header("Location:login.php");
}
public static function Check()
{
self::Start();
//echo $this->user_id;;
if (self::Get("Mlogin")==false)
{
self::Stop();
header("Location:login.php");
}
}
public static function CheckA(){
self::Start();
if (self::Get("Alogin")==false) {
self::StopA();
header("Location:../user/login.php");
}
}
public static function CheckAll()
{
if (self::Get("Mlogin")==false && self::Get("Alogin")==false)
{
return false;
}
else
{
return true;
}
}
public static function CheckUserLogin()
{self::Start();
if (self::Get("Mlogin")==false)
{
return false;
}
else
{
return true;
}
}
public static function Auto(){
self::Start();
if(self::Get("Mlogin")==false){
echo "<a style=\"color:white;\" href='user/login.php'>Login</a>";
} else {
echo "<a style=\"color:red;\" href='?action=logout'>Logout</a>";
if(isset($_GET['action']) && ($_GET['action']== "logout")){
self::Stop();
}
}
}
public static function AutoA(){
self::Start();
if(self::Get("Mlogin")==false){
echo "<a style=\"color:white;\" href='login.php'>Login</a>";
} else {
echo "<a style=\"color:red;\" href='?action=logout'>Logout</a>";
if(isset($_GET['action']) && ($_GET['action']== "logout")){
self::StopB();
}
}
}
}
?>
This is My confirm.php code:
<?php
require_once("/../dataAccessLayer/dalSession.php");
require_once("/../dataAccessLayer/dalLogin.php");
session::check();
?>
<?php
if(isset($_GET['action']) && ($_GET['action']== "logout")){
Session::Stop();
}
?>
<!doctype html>
<html lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Success Notification Boxes</title>
<link rel="stylesheet" type="text/css" media="all" href="style.css">
<script type="text/javascript" src="https://ajax.googleapis.com /ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div id="w">
<div id="content">
<!-- Icons source http://dribbble.com/shots/913555-Flat-Web-Elements -->
<div class="notify successbox">
<h1>Success!</h1>
<span class="alerticon"><img src="" alt="checkmark" /></span>
<p>Thanks For Your Purchase.</p>
<p>Your Purchase Will Deliver Within 72 Hours.</p>
<p>Any Question? Please Call: <b>+8801721557233</b></p>
<p></p>
</div>
<h1><a class="navbar-brand" href="../index.php">Home</a></h1>
</div><!-- #end #content -->
</div><!-- #end #w -->
</body>
</html>
You can modify your function Start. Replace:
public static function Start(){
session_start();
}
By:
public static function Start(){
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
}
It will fix your problem (the notice will not be displayed anymore). The idea is: if your session is already started, don't start it again.
Then if it does not work, remove ALL the space in your confirm.php file before the first <?php (it seems you have two spaces before the first <?php but I'm not sure it's because you copy/pasted it).
Remove spaces before
That characters are starting a session. and may be its better to use some template engine to generate html? Smarty, twig or simple php templates.

How to redirect a file using function

I'm trying to access my file where it contains a home page using a function from another file (redirect.php). MyWebsite/main/main.html this is the location of my file that I want to access. I stuck in here redirect::toMain('main.html'); don't have a idea how to link the full path so I will be directing to the home page. I tried to pass ('main.html') value to the function toMain() but it didn't work. Location of folder below.
So MyWebsite is the main folder and it contains sub-folder listed below.
function (folder) contains a redirect function
main (folder) contains a html. main.html where it set as my home page. This is where the user will redirect.
Class: redirect.php Location: MyWebsite/function/redirect.php
<?php
class redirect
{
public static function toMain($location = null)
{
if($location)
{
header('Location: ' . $location);
exit();
}
}
}
$a = new redirect();
?>
loginProcess.php
<?php
session_start();
require_once('../connection/connection.php');
require_once('../connection/loginCRUD.php');
require_once('../function/redirect.php');
if(isset($_POST['submit']))
{
$dbusername = $_POST['loginUsername']; //Store value of textfield in array
$dbpassword = $_POST['loginPassword'];
if(!empty($dbusername) && !empty($dbpassword))
{
if((new loginCRUD)->readLogin($dbusername,$dbpassword)) //If true
{
// echo "You are logged in!";
$_SESSION['loginUsername'] = $dbusername;//Session are stored in array.
// redirect the user to the home page
redirect::toMain('main.html');
}
else
{
echo "Incorrect username and/or password";
}
}
}//end of isset
?>
Here is one way that I would do this:
class redirect
{
private static $baseUrl = 'http://localhost/MyWebsite/main/';
public static function toMain($location = null)
{
if($location)
{
header('Location: ' . self::$baseUrl . $location);
exit();
}
}
}
The $baseUrl can also be this:
private static $baseUrl = '/MyWebsite/main/';
Make sure that MyWebsite starts with http:// or it will redirect to a relative URL. You don't need $a = new redirect(); since you are accessing the methods statically.
Now you can do this:
redirect::toMain('main.html');

Load html/php template function

I just go to the point.
Nvm need to add more text to much code..
Trying to load a Template with php inside it but php prints in html instead.
Init.php
class Init {
public static $ROOT = '';
public static $TEMPLATE = '';
public static $SERVICE = '';
public static function start() {
// Init Paths
Init::$ROOT = str_replace("\\", "/", __DIR__);
Init::$TEMPLATE = Init::$ROOT . "/Template/";
Init::$SERVICE = Init::$ROOT . "/Service/";
// Init Template.php class
require_once(Init::$SERVICE . "Template.php");
// Load template Top.php
$top = new Template(Init::$TEMPLATE . "Layout/Top.php");
echo $top->load(); // Show Top.php
}
}
Top.php
<!DOCTYPE html>
<html>
<?
// Load template Head.php
$head = new Template(Init::$TEMPLATE . "Layout/Head.php");
$head->set("TITLE", "Dashboard"); //Set [#TITLE] to Dashboard
$head->load(); // Show Head.php
?>
</html>
Head.php
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>[#TITLE] | cwEye</title> <!-- [#TITLE] will be Dashboard-->
<?
echo "Hello"; // ERROR -> This will print <? echo"Hello"; ?> in my page
?>
</head>
Template.php
<?
class Template {
protected $file;
protected $values = array();
private static $templateFile = null;
public function __construct($file) {
$this->file = $file;
}
public function set($key, $value) {
$this->values[$key] = $value;
}
// This code works but it will not load php inside
public function load() {
if (!file_exists($this->file)) return "Error loading template file ($this->file).";
ob_start();
include_once($this->file);
$data = ob_get_clean();
foreach ($this->values as $key => $value) {
echo str_replace("[#$key]", $value, $data);
}
if(count($this->values) == 0) echo $data;
}
}
?>
Ive played with allot of functions to make it but it does not work...
It just prints the php in html.
Tried with
ob_start();
include_once(FILE);
$data = ob_get_clean();
Don't use short tags like <? or <?=, use <?php instead. You probably have your short_open_tag set to false in php.ini. If you are using PHP 7 then you should know short tags were removed completely and wont work anymore.
In head.php use the full tag. Change
to
<?php echo "hello"; ?>

Categories