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
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!
I have the following line in my HTML file for my homepage. How come it won't print out the name of the current user when they log in? I have the line in the body section of the html file. I want to put it on all my pages too but it won't display. The user does exist as it logs in succesfully via my php echo mesage.
This line:
<div id="usernameDiv"><?php echo $_SESSION['username']; ?></div>
Here is the login page:
<?php
function SignIn() {
require_once("constants.php"); //Now constants will be accessible
session_start();
try {
$link = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$username = $_POST['username']; //no need to esaping as we will use prepared statements
$password = $_POST['password'];
if (!empty($username) && !empty($password)) {
//You need to define a new column named "id" which will be int auto_increment and it will be your primary key
$sql = "SELECT id, username, password FROM users where username = :username AND password = :password";
//Prepare your query
$stmt = $link->prepare($sql);
//Execute your query binding variables values
$stmt->execute(array(':username'=>$username, ':password'=>$password));
//Fetch the row that match the criteria
$row = $stmt->fetch();
if (!empty($row['username']) && !empty($row['password'])) {
$_SESSION['is_logged'] = true; //Now user is considered logged in
$_SESSION['username'] = $row['username'];
$_SESSION['id'] = $row['id'];
//Never store passwords in $_SESSION
echo "Welcome to your User Account for CSIT Conference. Click to go home: ";
echo ' Home Page . ';
echo "Or here to go to your assigned papers: ";
echo ' Assigned Papers . ';
} else {
echo "SORRY... YOU ENTERED WRONG ID AND PASSWORD... PLEASE RETRY...";
}
$link = null;
} else {
echo 'Please enter username and password.';
}
} catch(PDOException $e) {
echo $e->getMessage();
}
}
if (isset($_POST['submit'])) {
SignIn();
}
?>
Here is the home page. Eventually I want it on all the pages.
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="import" href="navigation.html">
</head>
<body>
<center> <b>World Congress CS-IT Conferences 2016</center>
<div id="horizontalmenu">
<ul>
<li>Home<br/></li>
<ul> <li>General Information <ul>
<li>About</li>
<li> Conference Fee</li>
<li>Hotel</li> </ul>
<li>Keynote Speakers<br/></li>
<li>Call for Papers<br/></li>
<li>Important Dates<br/></li>
<li>Major Areas<br/></li>
<li>Paper Submission<br/></li>
<li>Login<br/></li>
<li>Registration<br/></li>
<li>Conference Program<br/></li>
<li>Guidelines<br/></li>
<li>Comments<br/></li>
</ul>
</nav></b>
<div id="usernameDiv"><?php echo $_SESSION['username']; ?></div>
<br><br>
<div class="zoom pic">
<center> <img src="images/technology.png" alt="portrait"> <center>
</div>
</body>
</html>
You are starting the session inside of your SignIn() function. Remove session_start(), and instead put the following at the top of your file to start your session:
if (!session_id()) #session_start();
You must also include the above line anywhere that you want to use the session data (for example, it should be the first line in your index file.)
* All of this assumes that you either have PHP setup to execute in a .html file, or your file is actually index.php instead of index.html
I have an backend website setup that displays all the users on my site in an organised table, I should be able to edit and delete the users from the php page. However I cannot get the delete function to work, here is the code.
Data_Display.php
<?php
include('session.php');
?>
<?php include ("db.php"); ?>
<?php
$sql = "SELECT * FROM username ORDER BY UserNameID DESC";
$query = mysql_query($sql) or die(mysql_error());
if (isset($_GET['UserNameID'])) {
$id = mysql_real_escape_string($_GET['UserNameID']);
$sql_delete = "DELETE FROM users WHERE id = '{$UserNameID}'";
mysql_query($sql_delete) or die(mysql_error());
header("location: data_display.php");
exit();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="icon" type="image/ico" href="favicon.ico">
<title>Network TV - All Records</title>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body >
<div class="container">
<div class="content">
<h1>Network TV Users and User control panel</h1>
<br>
<div class="toolbar">
Add New Person
Home
</div>
<br>
</div>
</div>
<div class="container">
<div class="content">
<?php if (mysql_num_rows($query)) { ?>
<?php while ($rows = mysql_fetch_assoc($query)) { ?>
<div class="separator"></div>
<h2><b>User reference:</b> <?php echo $rows['UserNameID']; ?></h2>
<h2><b>Name:</b><?php echo $rows['name']; ?></h2>
<h2><b>Email address:</b> <?php echo $rows['email']; ?></h2>
<h2><b>Gender:</b> <?php echo $rows['sex']; ?></h2>
<h2><b>Profile Picture:</b> <?php echo $rows['imagelink']; ?></h2>
<div class="toolbar">
Edit
Delete
</div>
<?php } /* End Loop */ ?>
<div class="separator"></div>
<?php } else { ?>
<div class="separator"></div>
<h2>There are no records to display</h2>
<div class="separator"></div>
<?php } /* End Rows Checking */?>
</div>
</div>
<div class="container">
<br>
<br>
<br>
<br>
<br>
</div>
<script>
function confirmDelete ( message, url )
{
var confirmation = confirm ( message );
if ( confirmation == true ) {
window.location = url;
} else {
return false;
}
}
</script>
</body>
</html>
Session.php
<?php
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("localhost", "root", "Oliver");
// Selecting Database
$db = mysql_select_db("users", $connection);
if(!isset($_SESSION)){session_start();}
// Storing Session
$user_check=$_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql=mysql_query("select username from username where username='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['username'];
if(!isset($login_session)){
mysql_close($connection); // Closing Connection
header('Location: home.php'); // Redirecting To Home Page
}
?>
db.php
<?php
$connection = mysql_connect('localhost', 'root', 'Oliver');
mysql_select_db('users', $connection) or die(mysql_error());
?>
Information
When I click the delete button in data_display.php, I do receive the javascript alert to confirm that I do want to delete the user from the database, but nothing actually happens.
if (isset($_GET['recordId'])) {
$id = mysql_real_escape_string($_GET['recordId']);
$sql_delete = "DELETE FROM users WHERE id = '{$id}'";
mysql_query($sql_delete) or die(mysql_error());
header("location: data_display.php");
exit();
}
You are sending recordId as parameter.
I've got a login script that does not close the session when the user goes to another site or returns to the login page. My question is, how do I destroy the session when they navigate away from the site or outside of the directory? Would I need to add a timeout argument when the user starts the session? Would I need to use cookies instead of session?
login.php
require("../includes/header.php");
if($_SERVER["REQUEST_METHOD"] == "POST"){
$p_num = $_POST["username"];
$pwd = $_POST["password"];
$query = "SELECT * FROM $user_table";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($result)){
$user_id = "{$row['user_id']}";
$user_name = "{$row['user_name']}";
$password = "{$row['password']}";
$image = "{$row['image']}";
$email = "{$row['email']}";
$program = "{$row['program']}";
$role = "{$row['role']}";
if(($user_id == $p_num) && ($pwd == $password)){
$_SESSION["id"] = $user_id;
$_SESSION["user"] = $user_name;
$_SESSION["program"] = $program;
$_SESSION["pass"] = $password;
$_SESSION["image"] = $image;
$_SESSION["email"] = $email;
$_SESSION["role"] = $role;
header("Location: ../pages/instructor.php");
}
else{
header("Refresh: 1; URL=../index.php");
}
}
}
instructor.php
<?php require("../includes/header.php"); ?>
<title></title>
<link href="../css/style.css" rel="stylesheet/less" type="text/css">
<script src="../js/jquery.2.0.3.js"></script>
<script src="../js/script.js"></script>
<script src="../js/less-1.7.4.min.js"></script>
</head>
<body>
<div id="page">
<header>
<div id="logo" class="logo_bg"></div>
<div id="fsi_logo" class="logo_bg"></div>
</header>
<div id="main">
<div id="instructor">
<?php
echo "<img id=instructor_image src=" .$_SESSION["image"] .">";
echo "<h1>" .$_SESSION["user"] ."</h1>";
echo "<span><p>" .$_SESSION["program"] ."</p> - <h2>" .$_SESSION["role"] ."</h2></span>";
echo "" .$_SESSION["email"] ."";
?>
</div>
<div id="bleg">
<h1>BUILD SCENARIO</h1>
<h1>SEARCH SCENARIOS</h1>
<h1>VIEW SCENARIOS</h1>
</div>
<?php require("../includes/footer.html"); ?>
logout.php
session_start();
session_unset();
session_destroy();
script.js
$(window).on('beforeunload', function(e){
e.preventDefault();
ajax = new XMLHttpRequest();
ajax.open("../php/logout.php", "POST", true);
ajax.send();
})
Do it with javascript
window.onbeforeunload = function (e) {
e.preventDefault(); //Not even sure what the default action does, but oh well
ajax = new XMLHttpRequest();
ajax.open("killsession.php","POST",true);
ajax.send();
}
killsession.php will of course be where the session is killed
Write a jquery/JS event handler for unload doc and send a request to ExpireSession.php expiring the session
As said "It depends on what constitutes "leaving""
$count = $_SESSION['count'];
if($count === 1) {
unset ($_SESSION['count']);
}
else (empty($_SESSION['count'])) {
$_SESSION['count'] = 1;
}
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