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.
Related
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!
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
I'm trying to show the detail of my product from a database, but i only want to show the product I clicked using the button "afficher le detail" right now it shows all app at once.
Any tips would be appreciated because I'm really lost on this one.
i don't know if i need to modify the index, class.app or product page.
this is what i got on my index.php
<?php
session_start();
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Applications</title>
</head>
<body>
<?php
include ("class.app.php");
$obj_app = new app();
include("class.client.php");
$obj_client = new client();
$btnajouterpanier=false;
if(isset($_SESSION['utilisateur'])){
if($obj_client->validate_login($_SESSION['utilisateur'],$_SESSION['motdepasse'])){
echo $obj_client->get_welcome_message($_SESSION['utilisateur']);
$btnajouterpanier=true;
}
}
if($_SERVER['REQUEST_METHOD'] === 'POST' && $_SERVER["CONTENT_TYPE"] === 'application/json'){
$data = json_decode(file_get_contents('php://input'),true);
$resultat = array('ajout' => FALSE);
$_SESSION['panier'][$_POST($data['id'])]+= 1;
$resultat['ajout'] = TRUE;
}
echo '<form name="frm_cat" action="index.php" method="POST">';
echo '<select name="lst_cat">';
$obj_app->get_cat_options();
echo '</select>';
echo '<input type="submit" name="btn_cat" value="Filtrer" />';
echo '</form>';
if(isset($_POST['lst_cat'])){
$obj_app->get_app_list($_POST['lst_cat'],$btnajouterpanier);
}else{
$obj_app->get_app_list('',$btnajouterpanier);
}
?>
<script src="jquery-3.2.1.min.js"></script>
<script src="panier.js"></script>
</body>
</html>
this is my class.app.php
<?php
class app{
private $dbh;
public function __construct(){
$this->dbh = new PDO('mysql:host=localhost;dbname=appstore','root','',array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ));
}
public function get_cat_options(){
$req = $this->dbh->prepare('SELECT * FROM cat ORDER BY titre');
$req->execute();
while($cat = $req->fetch()){
echo '<option value="'.$cat->id.'">'.$cat->titre.'</option>';
}
}
public function get_app_list($idcat="",$btnajouterpanier=false){
if ($idcat!=""){
$reqapp = $this->dbh->prepare("SELECT app.* FROM app JOIN appcat ON app.id=appcat.idapp WHERE appcat.idcat='".$idcat."'");
}else{
$reqapp = $this->dbh->prepare("SELECT app.* FROM app");
}
$reqapp->execute();
while($app = $reqapp->fetch()){
echo '<h3>'.$app->nom.'</h3><br/>';
echo '<img src="image/'.$app->image.'" /><br/>';
echo '<p>'.$app->description.'</p><br/>';
echo $app->prix.' $<br/>';
echo "<form name='btn_det' method='POST' action='produit.php'><input type='hidden' name='app_detail' value='".$app->id."' /><input type='submit' name='iddetail' value='Afficher le detail' data-id='".$app->id."'/></form>";
if($btnajouterpanier){
echo '<button type="button" class="btnajouterpanier" data-id="$app->id">Ajouter au panier</button>';
}
echo '<hr/>';
}
}
public function detail($iddetail){
$reqdet = $this->dbh->prepare('SELECT * FROM app where id = ?');
$reqdet->execute(array($iddetail));
while($app = $reqdet->fetch()){
echo '<h3>'.$app->nom.'</h3><br/>';
echo '<img src="image/'.$app->image.'" /><br/>';
echo '<p>'.$app->description.'</p><br/>';
echo $app->prix.' $<br/>';
}
}
}
?>
<script src="jquery-3.2.1.min.js"></script>
<script src="panier.js"></script>
and this is my produit.php page
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Document sans nom</title>
</head>
<body>
<?php
include ("class.app.php");
$obj_app = new app();
$obj_app->detail($_POST['iddetail'])
?>
</body>
</html>
When I use session_start() in my code i have the session setup properly and when I run the code and log in it keeps me logged in and everything works properly, but when I add HTML underneath the PHP code located at the top of the page and refresh it (while logged in) it logged me out?
My Code Without HTML
Core file
ob_start();
session_start();
function loggedin() {
if(isset($_SESSION['user_id'])&&!empty($_SESSION['user_id'])) {
return true;
} else {
return false;
}
}
require 'connect.inc.php';
require 'core.php';
include 'main_login.inc.php';
if (loggedin()) {
$dir = $user_name;
if($handle = #opendir($dir)) {
if($handle2 = #opendir($dir.'/docs')){
//If Logged In And Users File Exists: Load Page
}
} else {
// If Users File Does Not Exist: Create User File
#mkdir($user_name, 0755, true);
// Create Docs
#mkdir($user_name.'/docs', 0755, true);
}
} else {
// If User Is Not Logged: Redirect To Jamie Co Home
#header('Location: http://www.jamieco.ca');
}
?>
My code with HTML (Non-working code)
<?php
require_once 'connect.inc.php';
require_once 'core.php';
include 'main_login.inc.php';
if (loggedin()) {
$dir = $user_name;
if($handle = #opendir($dir)) {
if($handle2 = #opendir($dir.'/docs')){
//If Logged In And Users File Exists: Load Page
}
} else {
// If Users File Does Not Exist: Create User File
#mkdir($user_name, 0755, true);
// Create Docs
#mkdir($user_name.'/docs', 0755, true);
}
} else {
// If User Is Not Logged: Redirect To Jamie Co Home
#header('Location: #');
}
?>
<!DOCTYPE html>
<html>
<body>
<header>
<nav>
<ul>
<li>Home</li>
<li>Clients</li>
<li>Sign In</li>
<li>Contact</li>
</ul>
</nav>
</header>
<div id = "clear" />
<div id = "big_wrapper">
<div id = "wrapper">
<br><br>
<!-- Logged In Stuff Goes Here -->
<div id = "user_options">
<ul>
<li><?php echo 'Welcome, '.$first_name.' '.$last_name.'<br><br>'; ?></li>
<li>Logout</li>
</ul>
</div>
<?php echo 'Welcome Back '.$first_name; ?>
<br><br>
<table border = "1" cellspacing = "5" id = "files">
<tr><td colspan = "7">File Handling</td></tr>
<tr>
<td>File Name:</td>
<td>File Size:</td>
<td>File Type:</td>
<td>Security Level:</td>
<td colspan = "3">Actions:</td>
</tr>
<?php
$dir = $user_name.'/docs/';
if($handle = #opendir($dir)) {
while($file = #readdir($handle)) {
if($file!='.'&&$file!='..') {
echo '<tr><td>'.$file.'</td>';
$name = $dir.$file;
$size = filesize($dir.$file);
$type = substr($name, strrpos($name, '.')+1);
echo '<td>'.$size.' Bytes'.'</td>';
echo '<td>'.$type.'</td>';
echo '<td>'.$file_grade.'</td>';
echo '<td>'.'Download'.'</td>';
echo '<td>'.'Rename'.'</td>';
echo '<td>'.'Delete'.'</td>';
}
}
}
?>
</tr>
</table>
<br><br>
<!-- Stuff Here -->
<br><br>
</div>
</div>
</body>
</html>
Problem Solved. I changed the session to a token, not sure why this works but it does!
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