Value of sessions lost while routing URL's - php

I have index.php file where all stylesheets,js,etc files are included and i only change file in the content area of index.php using require once.Problem is that when user ask for some other page sessions are lost....and session variable is undefined...this is my index.php...while i access main.php , I am getting session variable undefined error...
----index.php file-----
<?php session_start();?>
<?php require_once("cc_includes/sessions.php"); ?>
<?php require_once('cc_includes/functions.php'); ?>
<?php require_once("cc_includes/sanitize.php"); ?>
<?php require_once('cc_includes/route.php'); ?>
<?php require_once("cc_includes/mydb.php"); ?>
<?php
if($request_uri_header!='')
{
require_once($request_uri_header);
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<?php require_once("cc_includes/default_files.php");?>
</head>
<title><?php echo $the_title;?></title>
<body id="page1">
<!-- header -->
<div class="bg">
<section>
<?php require_once("cc_includes/message.php"); ?>
<div class="main">
<header>
<?php require_once("cc_includes/logo.php"); ?>
<?php require_once("cc_includes/navigation.php");?>
<?php require_once("cc_includes/slider.php"); ?>
</header>
<section id="content">
<div class="padding">
<?php require_once("cc_includes/boxes.php"); ?>
<div class="wrapper">
<div class="col-3">
<div class="indent">
<?php
if($request_uri!='')
{
require_once($request_uri);
}
?>
</div>
</div>
</div>
</div>
</section>
<?php require_once("cc_includes/footer.php");
require_once("cc_includes/end_scripts.php");
?>
</div>
</section>
</div>
</body>
</html>
-----sessions.php file------
$session_user=false;
$session_message=false;
if(!isset($_SESSION) || !isset($_SESSION['user']))
{
$session_user=array(
's_name'=>'',
's_gender'=>'',
'college_id'=>'',
's_joining'=>'Dynamic',
's_department'=>'Dynamic',
's_location'=>'',
's_dob'=>'',
's_approved'=>0
);
$_SESSION['user']=serialize($session_user);
}
else
{
//print_r(unserialize($_SESSION['user']));
//exit;
$session_user=unserialize($_SESSION['user']);
}
-----route.php file--------
if(isset($_GET['url']))
{
$total_request=explode('/',$_GET['url']);
if(count($total_request)>1)
{
$_GET['url']=$total_request[0];
array_shift($total_request);
$_GET['action']=$total_request[0];
array_shift($total_request);
foreach($total_request as $key=>$value)
{
$_GET['param'.$key]=$value;
}
unset($total_request);
}
if($session_user['s_approved']!=0)
{
if($_GET['url']=='' || $_GET['url']=='index.php')
{
header("location: main.php");
}
if(!is_file($_GET['url']))
{
set_error_message("No Such Location Exits!");
header("location: main.php");
}
$request_uri=$_GET['url'];
$request_uri_header="headers/".str_replace('.php','.h',$request_uri);
}
else
{
$request_uri="users/login.php";
$request_uri_header=str_replace('.php','.h',$request_uri);
if($_GET['url']!='' && $_GET['url']!='index.php')
{
if($_GET['url']=='services.php' || $_GET['url']=='register.php')
{
$request_uri=$_GET['url'];
$request_uri_header="headers/".str_replace('.php','.h',$request_uri);
}
else
{
if(is_file($_GET['url']))
{
set_error_message("You need to Login Before Accessing Other Site Area!");
}
else
{
set_error_message("No Such Location Exits!");
}
header("location: index.php");
}
}
}
if(!is_file($request_uri_header))
{
$request_uri_header='';
}
}
else
{
$request_uri="users/login.php";
$request_uri_header=str_replace('.php','.h',$request_uri);
}
----main.h file-----
if(!registered_user() && !admin_user())
{
set_error_message("Please Login To View The Page!",2);
header("Location: index.php");
}
set_title("College Connections | Home");
view_boxes(false);
view_slider(FALSE);
-----main.php file-----
<?php
// if(!isset($session_user))
//{
//echo $session_user['s_name'];
//exit;
//}
//print_r($session_user);
//exit;
echo"<h1 class=\"profile\">".$session_user['s_name']."</h1><h1 class=\"blue_profile\">'s Profile</h1><a href=\"dashboard.php\" style='float:right;margin-right:30px;margin-top:20px;'>College Dashboard</a><br /></br /><br />";
echo"<hr>";
echo"<div class=\"prof_image\">";
$c_id=$session_user['college_id'];
$image=mysql_query("select path from img_upload where username=\"$c_id\" limit 1",$connection);
if(!$image)
{
die("database query failed".mysql_error());
}
echo mysql_error($connection);
?>

You haven't called session_start() in any file other than index.php so when the other pages are loaded the sessions are being lost

Related

Global $_SESSION variables [duplicate]

This question already has answers here:
PHP Session variable not getting set
(9 answers)
Closed 1 year ago.
I've been following Dani Krossings Login System It's a great tutorial and is just what I am looking for, there is just one thing I'm struggling with.
After logging in, the header doesn't refresh. Following login, the header should change to ...Profile Page, Logout. The code I have stays as Sign Up, Login. It is as is the $_SESSION variable has not come through to the header. However, if after login, I select the Sign up or login link, the header changes to what it should be.
Function code
function uidExists($conn, $username) {
$sql = "SELECT * FROM users WHERE usersUid = ? OR usersEmail = ?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("location: ../signup.php?error=stmtfailed");
exit();
}
mysqli_stmt_bind_param($stmt, "ss", $username, $username);
mysqli_stmt_execute($stmt);
// "Get result" returns the results from a prepared statement
$resultData = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($resultData)) {
return $row;
}
else {
$result = false;
return $result;
}
mysqli_stmt_close($stmt);
}
function loginUser($conn, $username, $pwd) {
$uidExists = uidExists($conn, $username);
if ($uidExists === false) {
header("location: ../login.php?error=wronglogin");
exit();
}
$pwdHashed = $uidExists["usersPwd"];
$checkPwd = password_verify($pwd, $pwdHashed);
if ($checkPwd === false) {
header("location: ../login.php?error=wronglogin");
exit();
}
elseif ($checkPwd === true) {
session_start();
$_SESSION["userid"] = $uidExists["usersId"];
$_SESSION["useruid"] = $uidExists["usersUid"];
header("location: ../index.php?error=none");
exit();
}
}
header.php
<?php
session_start();
include_once 'includes/functions.inc.php';
?>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>PHP Project 01</title>
<!--I won't do more than barebone HTML, since this isn't an HTML tutorial.-->
<link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght#0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet">
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/style.css">
</head>
<body>
<!--A quick navigation-->
<nav>
<div class="wrapper">
<img src="img/logo-white.png" alt="Blogs logo">
<ul>
<li>Home</li>
<li>About Us</li>
<li>Find Blogs</li>
<?php
if (isset($_SESSION["useruid"])) {
echo "<li><a href='profile.php'>Profile Page</a></li>";
echo "<li><a href='logout.php'>Logout</a></li>";
}
else {
echo "<li><a href='signup.php'>Sign up</a></li>";
echo "<li><a href='login.php'>Log in</a></li>";
}
?>
</ul>
</div>
</nav>
<!--A quick wrapper to align the content (ends in footer.php)-->
<div class="wrapper">
Login.php
<?php
include_once 'header.php';
?>
<section class="signup-form">
<h2>Log In</h2>
<div class="signup-form-form">
<form action="includes/login.inc.php" method="post">
<input type="text" name="uid" placeholder="Username/Email...">
<input type="password" name="pwd" placeholder="Password...">
<button type="submit" name="submit">Sign up</button>
</form>
</div>
<?php
// Error messages
if (isset($_GET["error"])) {
if ($_GET["error"] == "emptyinput") {
echo "<p>Fill in all fields!</p>";
}
else if ($_GET["error"] == "wronglogin") {
echo "<p>Wrong login!</p>";
}
}
?>
</section>
<?php
include_once 'footer.php';
?>
login.inc.php
<?php
if (isset($_POST["submit"])) {
// First we get the form data from the URL
$username = $_POST["uid"];
$pwd = $_POST["pwd"];
// Then we run a bunch of error handlers to catch any user mistakes we can (you can add more than I did)
// These functions can be found in functions.inc.php
require_once 'dbh.inc.php';
require_once 'functions.inc.php';
// Left inputs empty
if (emptyInputLogin($username, $pwd) === true) {
header("location: ../login.php?error=emptyinput");
exit();
}
// If we get to here, it means there are no user errors
// Now we insert the user into the database
loginUser($conn, $username, $pwd);
} else {
header("location: ../login.php");
exit();
}
Anyone have any thoughts on how I can get the header to refresh on submission of a successful login form?
Since Sometimes Some Content Is Left On The Page After Reloading The Header, We Need To Use die() after Changing Location From Header.
TBH, Redirecting Using PHP Is Not Recommended, I Suggest You To Redirect The User Using An Inbuilt JavaScript Function, window.location.replace(path)
You Can Call It Inside A PHP Script Using
?>
<script>
window.location.replace(path)
</script>
<?php
Or Simply Just Create Your Own Function:
function redirect($path) {
?>
<script>
window.location.replace('<?php echo $path ?>')
</script>
<?php
}
And Use It: redirect("profile.php")
Always put a session_start() into every page I want to use $_SESSION variables.
Fixed.
Thanks for all your help!

the html not showing value of php(UPDATED)

UPDATED: I have a variable in PHP mailuid that I want to show in my HTML. It displays the error the value of mailuid is undefined on the webpage. How can I show the value of height to html page?
index.php
<?php
require "header.php";
?>
<main>
<link rel="stylesheet" type="text/css" href="styl.css">
<div class="wrapper-main">
<section class="section-default">
<h2><?php echo "$mailuid" ?></h2>
<?php
?>
</section>
</div>
</main>
<?php
require "footer.php";
?>
loginbackend.php
<?php
if(isset($_POST['login-submit'])) {
require 'db.php';
$mailuid = $_POST['mailuid'];
$password = $_POST['pwd'];
if (empty($mailuid) || empty($password)) {
header("Location: ./index.php?error=emptyfields");
exit();
} else {
$sql = "SELECT * FROM users WHERE uidUsers=? OR emailUsers=?;";
$stmt = mysqli_stmt_init($conn);
if (!mysqli_stmt_prepare($stmt, $sql)) {
header("Location: ./index.php?error=sqlerror");
exit();
} else {
mysqli_stmt_bind_param($stmt, "ss", $mailuid, $mailuid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if ($row = mysqli_fetch_assoc($result)) {
$pwdCheck = password_verify($password, $row['pwdUsers']);
if($pwdCheck == false) {
header("Location: ./index.php?error=wrongpwd");
exit();
} else if ($pwdCheck == true) {
session_start();
$_SESSION['userId'] = $row['idUsers'];
$_SESSION['userUid'] = $row['uidUsers'];
$username = substr($mailuid, 0, strpos($mailuid, "#"));
header("Location: ./index.php?login=success".$username);
exit();
} else {
header("Location: ./index.php?error=wrongpwd");
exit();
}
} else {
header("Location: ./index.php?error=nouser");
exit();
}
}
}
} else {
header("Location: ./signup.php");
exit();
}
As per your latest comment:
To get the mailuid from the URL (GET parameters) add the following code to your index.php
<?PHP
require "header.php";
$mailuid = !empty($_GET['mailuid']) ? $_GET['mailuid'] : null;
// You can also specify the default value to be used instead of `null` if the `mailuid` is not specified in the URL.
?>
<main>
<link rel="stylesheet" type="text/css" href="styl.css">
<div class="wrapper-main">
<section class="section-default">
<h2><?php echo "$mailuid"?></h2>
</section>
</div>
</main>
<?php
require "footer.php";
?>
From PHP7 you can use
$mailuid = $_GET['mailuid'] ?? null;
instead of
$mailuid = !empty($_GET['mailuid']) ? $_GET['mailuid'] : null;
The mistake you've made:
I think you're confusing forms and file including with how post works.
Let me explain:
A form sends data to the server, which is then pushed into the $_POST global variable. You can read this data and use this data easily by echoing or dumping it.
This is what you should do:
In this case, your data value will be empty as you're not passing anything to it.
You can solve this by creating a form and passing it to your PHP file.
You can also just require your php script.
Normally you would put data.php in your action, but since you wish to use the variable before you entered the form, you have to include it first.
index.html
<?php require 'data.php'; ?>
<form method="POST" action="">
<h1>Height: <?=$height?></h1>
<input type="text" placeholder="Enter the height..." name="height">
<input type="submit" name="submit" value="Submit">
</form>
data.php
<?php
if (!empty($_POST)) {
$height = $_POST['height'];
} else {
$height = 0; //Default height
}
My apologies if i didn't get your question properly.
===========================================
Option B, if this is what you mean, is just doing this:
index.html
<body>
<div class="container">
<?php
require 'data.php'; //Get the data.php file so we can use the contents
?>
<h1><?php echo $height; ?></h1>
</div>
</body>
data.php
<?php
$height = 100; //Height variable

when I uploaded my php application using Filezilla images are missing

I uploaded my php application using Filezilla and when I checked it online, all of the images are missing and total site get break. I don't understand this because everything works fine offline but when I check through after publishing it online, all the images disapear. I also checked all my links and they're fine.
Here is my code
<html>
<head>
<title> Vatsal Technosoft Messanger </title>
<script type="text/javascript" src="../JavaScript/frmvalidation.js"></script>
<link href="../Stylesheet/style.css" media="all" type="text/css" rel="stylesheet" />
</head>
<body>
<?php include 'connect.php' ?>
<?php include 'functions.php' ?>
<?php include 'header.php' ?>
<div id="outer" style="margin-top:0px;">
<div class="container" style="color:#00C; z-index:1;">
<div class="subcontainer" >
<?php
if(loggedin())
{
?>
<a href='' onclick='addcontact();' id='noti' style='text- decoration:none;margin-bottom:0px;'>
<?php
$my_id = $_SESSION['user_id'];
$notifrnd = mysql_query("SELECT * FROM `frnd_req` WHERE `to` = '$my_id' ");
if(mysql_num_rows($notifrnd))
{
while($arr = mysql_fetch_array($notifrnd))
{
$fid = $arr[1];
$firstname = getfirstname($fid , 'firstname');
$lastname = getlastname($fid , 'lastname');
}
echo "<font style='color:#FFFF00; font-size:11px; margin-left:15px; margin-top:3px; margin-bottom:5px; float:left; font-weight:bold;'>You have Friend request</font>";
}
}
?>
</a>
<?php
?>
<iframe name ='uses' src='../indexus.php' width='185' height='140' style='max-width:185px; background-color:#ccc;'>
</iframe>
<?php
if(adminlogedin())
{
$admin_id = $_SESSION['admin_id'];
eader('location:admindex.php');
}
?>
</div>
</div>
<div class="footer">
<div class="online">
<?php
if(loggedin())
{
echo "<img src='../Images/ym1.png'>";
}
else
{
echo "<img src='../Images/ym2.png'>";
}
?>
</div>
<div class="footertext">
<?php
if(loggedin())
{
$my_id = $_SESSION['user_id'];
$firstname = getfirstname($my_id , 'firstname');
$lastname = getlastname($my_id , 'lastname');
echo " $firstname $lastname ";
}
else
{
}
?>
</div>
</div>
</div>
</body>
</html>

Syntax error: end of file [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
It's saying,
Parse error: syntax error, unexpected end of file in
/mnt/sdcard/www/parts/background/editProfilePic_Process.php on line 96
Can't find the error.
Here is the code:
<?php
session_start();
$site="http://".$_SERVER["HTTP_HOST"]."/";
$root=$_SERVER["DOCUMENT_ROOT"];
if(substr($root,-1)!="/")
{
$root=$root."/";
}
if(!isset($_SESSION["u"]))
{
header("location:".$site."user");
exit;
}
else{
$u=$_SESSION["u"];
}
if(!isset($_POST["access"]))
{
echo "You cannot access this page";
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<?php
include($root."parts/resources.php");
?>
</head>
<body>
<?php
// header also contents the <noscript> alert
include($root."parts/header.php");
?>
<div class="wholepage">
<div class="page scatterList">
<?php
if(isset($_FILES["profilePic"]))
{
$name=$_FILES["profilePic"]["name"];
if($_FILES["profilePic"]["error"] !== UPLOAD_ERR_OK) {
die("Upload failed with error code ".$_FILES["profilePic"]["error"]);
}
if(!getimagesize($_FILES["profilePic"]["tmp_name"]))
{
exit;
}
$path=$site."img/1/".$u.".jpg";
move_uploaded_file($path, $_FILES["profilePic"]["tmp_name"]);
}
?>
</div> <!-- end of .page -->
</div> <!-- wholepage -->
<!-- FOOTER -->
<?php
include($root."parts/footer.php");
?>
</body>
</html>
What should I do to get rid of it?
You forgot to close a brace on your isset if loop. Try this code.
<?php
session_start();
$site="http://".$_SERVER["HTTP_HOST"]."/";
$root=$_SERVER["DOCUMENT_ROOT"];
if(substr($root,-1)!="/")
{
$root=$root."/";
}
if(!isset($_SESSION["u"]))
{
header("location:".$site."user");
exit;
}
else{
$u=$_SESSION["u"];
}
if(!isset($_POST["access"]))
{
echo "You cannot access this page";
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<?php
include($root."parts/resources.php");
?>
</head>
<body>
<?php
// header also contents the <noscript> alert
include($root."parts/header.php");
?>
<div class="wholepage">
<div class="page scatterList">
<?php
if(isset($_FILES["profilePic"]))
{
$name=$_FILES["profilePic"]["name"];
if($_FILES["profilePic"]["error"] !== UPLOAD_ERR_OK) {
die("Upload failed with error code ".$_FILES["profilePic"]["error"]);
}
if(!getimagesize($_FILES["profilePic"]["tmp_name"]))
{
exit;
}
$path=$site."img/1/".$u.".jpg";
move_uploaded_file($path, $_FILES["profilePic"]["tmp_name"]);
}
?>
</div> <!-- end of .page -->
</div> <!-- wholepage -->
<!-- FOOTER -->
<?php
include($root."parts/footer.php");
?>
</body>
</html>
Line 48: begin if
if (isset ($_FILES["profilePic"])) {
} End tag not exist.
Put } tag after move_uploaded_file line 57 or where you want.
Like this:
if (isset ($_FILES["profilePic"])) {
$name = $_FILES["profilePic"]["name"];
if ($_FILES["profilePic"]["error"] !== UPLOAD_ERR_OK) {
die("Upload failed with error code " . $_FILES["profilePic"]["error"]);
}
if (!getimagesize($_FILES["profilePic"]["tmp_name"])) { exit;}
$path = $site . "img/1/" . $u . ".jpg";
move_uploaded_file($path, $_FILES["profilePic"]["tmp_name"]);
}
you haven't close this block
if(isset($_FILES["profilePic"]))
{
You didn't finish one of you if statements.
Change:
if(isset($_FILES["profilePic"]))
{
$name=$_FILES["profilePic"]["name"];
to:
if(isset($_FILES["profilePic"]))
{
$name=$_FILES["profilePic"]["name"];
}
<?php
if(isset($_FILES["profilePic"]))
{
$name=$_FILES["profilePic"]["name"];
if($_FILES["profilePic"]["error"] !== UPLOAD_ERR_OK) {
die("Upload failed with error code ".$_FILES["profilePic"]["error"]);
}
if(!getimagesize($_FILES["profilePic"]["tmp_name"]))
{
exit;
}
$path=$site."img/1/".$u.".jpg";
move_uploaded_file($path, $_FILES["profilePic"]["tmp_name"]);
}// this one
?>
You never closed the first if statment..

Weird behaviour when trying to replace two php function results in html

The template file is .php and has those placeholders:
<ul>
<li><a href='a.php'>{{placeholder1}}</a></li>
{{placeholder2}}
</ul>
And this is the code which replaces them:
$file = file_get_contents($template);
$file = str_ireplace('{{placeholder1}}', count_messages(), $file);
$file = str_ireplace('{{placeholder2}}', show_link(), $file);
print $file;
Functions are nothing special ('functions.php'):
function count_messages()
{
ob_start();
if (preg_match('/^[A-Za-z0-9_]{3,40}$/', $_SESSION['username']))
{
$table = $_SESSION['username'];
}
else
{
header('Location: login.php');
exit();
}
try
{
$db = new PDO('sqlite:site.db');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$result = $db->prepare("SELECT Count(*) FROM `$table` WHERE `isRead` = '0'");
$result->execute();
$count = $result->fetchColumn();
if ($count > 0)
{
print "<b style='color: #00ff00; text-decoration: blink;'>$count</b> <b style='font-size: 6pt; text-decoration: blink; text-transform: uppercase;'>unread</b> ";
}
unset($db);
}
catch(PDOException $e)
{
echo $e->getMessage();
}
ob_end_flush();
}
function show_link()
{
ob_start();
if ($_SESSION['username'] == "admin")
{
print "<li><a href='admin_panel.php' target='main_iframe'><b style='color: #ffff00;'>Admin Panel</b></a></li>;
}
ob_end_flush();
}
First counts the messages and outputs number with some styling, the second adds to the menu 'Admin Panel' link if the username is 'admin.
The problems are (no errors in php log):
count_messages() works but outputs 'n unread' above all elements on the page.
show_link() doesn't output the link.
The file $template is readable and named template.php:
<?php
session_start();
if(!$_SESSION['islogged'])
{
header('Location: login.php');
exit();
}
require_once('functions.php');
?>
<!DOCTYPE HTML>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="UTF-8" />
<meta name="description" content="Documents" />
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Documents</title>
</head>
<body>
<div id="main">
<iframe src="documents.php" name="main_iframe" id="main_iframe">
</iframe>
</div>
<div id="main_menu">
<ul id="menu_list">
<li>{{placeholder1}}Messages</li>
{{placeholder2}}
<li>Log out</li>
</ul>
</div>
</body>
</html>
The index.php:
<?php
session_start();
require_once('functions.php');
$template = 'template.php';
if (file_exists($template))
{
if (is_readable($template))
{
if(!$_SESSION['islogged'])
{
session_destroy();
header('Location: login.php');
exit();
}
}
else
{
print "Template file cannot be opened";
}
}
else
{
print "Template file doesn't exist";
}
$file = file_get_contents($template);
$file = str_ireplace('{{placeholder1}}', count_messages(), $file);
$file = str_ireplace('{{placeholder2}}', show_link(), $file);
print $file;
?>
I hope someone here knows what causes this behaviour ...
You are using the functions’ result values in the str_ireplace function call but the functions don’t return anything, they are missing a return statement.
You probably meant to use return ob_get_clean(); instead of ob_end_flush(); in your code.

Categories