I want to display 'Welcome "username"' when a user logs in but it doesn't work. I might be doing something wrong with sessions.
It gives an error message of:
Notice: Array to string conversion
My code:
<?php
require("config.php");
if(empty($_SESSION['user']))
{
header("Location: index.php");
die("Redirecting to index.php");
}
$user = $_SESSION['user'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>uvoluntary</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<link href="font/stylesheet.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="navbar navbar-fixed-top navbar-inverse">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand">Logged In</a>
<div class="nav-collapse">
<ul class="nav pull-right">
<li>Create Event</li>
<li>My Events</li>
<li class="divider-vertical"></li>
<li>Log Out</li>
</ul>
</div>
</div>
</div>
</div>
<!-- MAIN CONTENT -->
<div class="container content container-fluid" id="home">
<h1 style="text-align: center;">Admin Control Panel</h1>
<!-- HOME -->
<h2>Welcome <?php echo $user; ?> </h2>
</div>
</body>
</html>
Config.php
<?php
// These variables define the connection information for your MySQL database
$username = "root";
$password = "";
$host = "localhost";
$dbname = "uvoluntarytest";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try { $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); }
catch(PDOException $ex){ die("Failed to connect to the database: " . $ex->getMessage());}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
header('Content-Type: text/html; charset=utf-8');
session_start();
?>
Index.php
<?php
require("config.php");
$submitted_username = '';
if(!empty($_POST)){
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex){ die("Failed to run query: " . $ex->getMessage()); }
$login_ok = false;
$row = $stmt->fetch();
if($row){
$check_password = hash('sha256', $_POST['password'] . $row['salt']);
for($round = 0; $round < 65536; $round++){
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password']){
$login_ok = true;
}
}
if($login_ok){
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
header("Location: secret.php");
die("Redirecting to: secret.php");
}
else{
echo '<h4 style="color:red;font-weight:bold; margin-top:40px; margin-left:850px;">Username And/or Password Incorrect. Please try again.</h4>';
}
}
?>
You're either missing session_start() or do not have it placed at the top of your files.
first file: missing it completely
Config.php: Needs to go at the top of the file
Why don't you start a session_start() function in the page..It needs to be in every page while you are coding using sessions.
And I didn't find any reason for setting $_SESSION['user'] in the code...
Please correct those..
begin with
session_start() function in the page.
It need to be in every page while you are coding using sessions.
try it. I hope its enough
Let's see the code where you create $_SESSION['user'] - sounds like you are assigning an array to that perhaps? try doing print_r($user) to see if that is the array in question your error is coming from. Perhaps you need something such as echo $user['username']
Edit: you are indeed assigning an array to $_SESSION['user']. Do this:
echo $user['username'];
Or alternatively fix your database code by doing:
$_SESSION['user'] = $row['username'];
Additionally setting a session before a header call doesn't usually work unless you close the session.
Try adding this just before the header call:
session_write_close();
And move your session_start() to the very top for good measure.
Welcome, <?php echo htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8'); ?> !
this displays Welcome(and the username name or number) Just Try.
Related
I am a beginner in web programming and now I am stuck, so I would like to ask for your help.
As you can see, the menu is on the left and next to it the "content" section or something like that where i would like to see tables, etc. What are called by the menus when i click on it. How can I call another php code like u can see below? For example, if you click on the customers, it brings out the customers in a table in the "content" section next to the menu without leaving the page and everything is there just there is now the customers and not the settings or something like that.
My index page Code:
<?php
session_start();
// Include login-check file
require_once "login-check.php";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- The meta viewport will scale my content to any device width -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--Favicon-->
<link rel="icon" type="image/x-icon" href="icons/favicon.png">
<!--Title-->
<title>Learning</title>
<link rel="stylesheet" href="./css/index-sytle.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css">
</head>
<body>
<?php
include "sidebar.php";
?>
<div class="users-table">
</div>
</body>
</html>
My sidebar code:
<div class="wrapper d-flex">
<div class="sidebar">
<ul>
</ul>
<ul>
<li><i class="fas fa-home"></i>Föoldal</li>
</ul>
<small class="text-muted px-3">Ügyfélkezelés</small>
<ul>
<li><i class="fas fa-user"></i>Ügyfelek</li>
<li><i class="fas fa-file"></i>Ajánlatok</li>
<li><i class="fas fa-user"></i>Rendelések</li>
</ul>
<ul>
<li><i class="fas fa-sign-out-alt"></i>Kilépés</li>
</ul>
</div>
And my viewCustomer code which i want to see on the same page "index.php", but near the menus.
<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'test');
/* Attempt to connect to MySQL database */
$conn = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check connection
if($conn === false){
die("Nem sikerült csatlakozni..." . mysqli_connect_error());
}
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
if(!$result){
die("Rossz kérés: ") . $conn->error;
}
while($row = $result->fetch_assoc()){
echo $row["id"];
echo $row["username"];
}
?>
Thank You guys for your help!
A simple solution is doing it via the include() and function using data retrieved from the url.
if (isset($_GET["page"])) {
$q = $_GET["page"];
$qa = explode('/', $q);
$page = $qa[0] ?? "home";
//check if a file with the filename retrieved from the $_GET["page"] exists
if (file_exists($pathToFile . $page . '.php')) {
//if it does, include that file
include($pathToFile . $page . '.php');
} else {
//$_GET["page"] is not set, redirect to somewhere it is or.
}
Now you link to you index file only and setting the $_GET["page"] to whichever file you wish to retrieve.
Should look something like this:
index.php?page=filename
the $_GET["page"] here will contain the value "filename"
currently I have a website with a basic login, I was just wondering how I would display a the name,skill and description of the unique user who is logged in.This is what I have done so far.I can only find articles on how to display data into table.This is the updated code:
<?php
include('session.php');
require 'config.php';
$sql = "SELECT * FROM profile";
$result = $conn->query($sql);
//echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="profile.css">
</head>
<body>
<ul>
<li>Home</li>
<li>PostJob</li>
<li>Find Job</li>
<li>How It Works</li>
<li>Notifications</li>
<li>Message</li>
<li>profile</li>
</ul>
<h1>Welcome To Bid4MyJob</h1>
<li>edit profile</li>
<div id="ProfilePage">
<div id="LeftCol">
<div id="Photo"></div>
<div id="ProfileOptions">
a
</div>
</div>
<div id="Info">
<p>
<strong>Name:<?php echo $row["name"]?></strong>
<!--<span>James</span>-->
</p>
<p>
<strong>Skill:<?php echo $row["skill"]?><</strong>
<!--span>James</span>-->
</p>
<!-- <p>
<strong>review:<?php /*echo $row["review"]*/?><</strong>
<span>james</span>
</p> -->
<p>
<strong>Description:<?php echo $row["description"]?><</strong>
<span>James</span>
</p>
<!--<p>
<strong>Name:</strong>
<span>james</span>
</p>-->
</div>
<!-- Needed because other elements inside ProfilePage have floats
<div style="clear:both"></div>-->
</div>
</body>
</html>
when the user successfully loggedin create a cookie and store their username or email whatever you used in that cookie. You have to do this stuff in your login.php file where you checks for username and password.
if(login success)
{
setCookie("username",value of username that you got from
user,'time()+3600','/');
echo "login successful";
}
After that in Profile you have write code like this;
<?php
$name=$_COOKIE['username'];
$sql=$conn->prepare("SELECT * from profile where username=?");
$stmt->bind_param('s', $name); // 's' specifies the variable type =>'string'
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
// do something with $row
}
?>
After that you can display the inforamtion in your div like $row['username'] etc.
if $row[] come from a sql request, just add in your request something like :
$user = (...) your current user logged
(...)
select (...) where user = $user
You can use $_SESSION to identify people after login and store information about the person. A session variable saves data of a specific user across multiple pages.
A session id is stored in the user browser and that is used to identify the $_SESSION data of a person.
In your program you can easily do something like this:
<?php
session_start(); //before anything else
include('session.php');
require 'config.php';
$sql = "SELECT * FROM profile";
$result = $conn->query($sql);
//assuming $row contains the information from
$_SESSION["user"] = $row;
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="profile.css">
</head>
....
....
Now on another page, you could easily:
<?php
session_start();
if(isset($_SESSION["user"]) {
//logged in
$name = $_SESSION["user"]["name"];
} else {
//not logged in
}
?>
<html>
....
....
I searched the whole internet to find a solution, but couldn't find one.
This is my problem: I made a site to login a user, create a session and the possibility to log out (of course). However, when I log in a user, I create a session, but the session just keeps going on and doesn't stop when I try to destroy it.
index.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
</head>
<body>
<!-- menu bar -->
<?php if (session_status() == PHP_SESSION_ACTIVE) { ?>
<div class="navbar">
<ul>
<li>Home</li>
<li>Products</li>
<li>Contact</li>
<li style="cursor: pointer;" onclick="document.getElementById('logoutpop').style.display='block'"><a>My account</a></li>
<li style="cursor: pointer;">Log out</li>
<ul style="float: right;">
<li ><a href="winkelmandje.php" >Shopping Bag</a></li>
</ul>
</ul>
</div>
<?php } elseif (session_status() == PHP_SESSION_NONE){ ?>
<div class="navbar">
<ul >
<li>Home</li>
<li>Products</li>
<li>Contact</li>
<li style="cursor: pointer;" onclick="document.getElementById('loginpop').style.display='block'"><a>Log in</a></li>
<ul style="float: right;">
<li ><a href="winkelmandje.php" >Shopping bag</a></li>
</ul>
</ul>
</div>
<?php } else {}?>
// other irrelevant html code
</body>
</html
login_action.php
<?php
session_start();
// server gegevens
$servername = "localhost";
$username = "user";
$password = "password";
$dbname = "db";
// Connect with server
$conn = new mysqli($servername, $username, $password, $dbname);
$email = "";
$password = "";
// Give connection error
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else {
}
if(isset($_POST['submit'])) {
$email = $_POST['email'];
$password = $_POST['password'];
// check if filled in
if(!empty($_POST['email'])) {
// query in SQL
$query = ("SELECT * FROM WebsiteUsers WHERE email='$email' AND pass='$password' ");
// result
$result = $conn->query($query);
// check if result exists in database
if ($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
}
// session variables
$_SESSION['loggedin'] = $email;
$_SESSION['message']="You are now logged in";
header('Location: index.php');
exit;
}
else
{
// show some error
}
}
}
$conn->close();
?>
logout_action.php
<?php
session_start();
session_destroy();
header("Location: index.php");
exit;
?>
You're using session_status() to check if the user is logged in.
But according to the docs http://php.net/manual/en/function.session-status.php PHP_SESSION_ACTIVE is true when a session is started. You create a session at the beginning of the home page using session_start() even tho the user isn't logged in he's still starting a session. So you need to set a variable in the session itself stating if the user passed the login or not.
Also:
You're storing your passwords in plain text, don't do that use Bcrypt or a diferent algorithm
Your code is vulnerable to SQL injection, learn about prepared statements and use them http://php.net/manual/en/mysqli.prepare.php don't under any circumstances use your current code in a production environment
This question already has answers here:
How can I get an unknown username given an ID?
(2 answers)
Closed 1 year ago.
i am new to this field and this is the first time i am working with session, the question may seem very basic but would appreciate if someone could help me. Currently I have made a login and logout page using session and wish to display data of the particular user who has logged in. The user is redirected to retailer_login.php after they sign in, apart from login form there are 4 pages for the entire login and logout process.
retailer_login.php, retailer_session.php, retailer_profile.php, retailer_logout.php
Every page is working fine however i am able to display only single data column of the user from database but i wish to display the entire information that is stored about that specific user.
DATABASE
Id name email password country city state occupation
1 sam sam#gmail.com sam XYZ ZBC QWE student
retailer_login page
<?php
session_start(); // Starting Session
if (isset($_POST['submit'])) {
try {
if (empty($_POST['email']) || empty($_POST['password'])) {
throw new Exception("email or Password is invalid");
} else {
// Define $email and $password
$email = $_POST['email'];
$password = $_POST['password'];
// To protect MySQL injection for Security purpose
$email = stripslashes($email);
$password = stripslashes($password);
$mail = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password);
//Etablishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("abc.com", "abc", "abc");
// Selecting Database
$db= mysql_select_db("abc", $connection);
// SQL query to fetch information of registerd users and finds user match.
$query = mysql_query("select * from retailerregister where password='$password' AND email='$email'", $connection);
$rows = mysql_num_rows($query);
if ($rows != 1)
throw new Exception("email or Password is invalid");
$_SESSION['login_user'] = $email; // Initializing Session
header("location: retailer_profile.php"); // Redirecting To Other Page
mysql_close($connection); // Closing Connection
}
}
catch (Exception $e) {
$_SESSION['login_error'] = $e->getMessage();
header("Location: index.html");
}
}
?>
retailer_profile page
<?php
include('retailer_session.php');
?>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Welcome to your homepage</title>
<meta name="viewport" content="width=device-width", initial-scale=1.0">
<link href="css/bootstrap.min.css" rel="stylesheet" />
<link href="css/styles.css" rel="stylesheet" />
<link href="css/carousel.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<div id="profile">
<div class="navbar navbar-inverse navbar-static-top">
<div class="container">
<id="welcome">Welcome : <i><?php echo $login_session; ?></i>
<button class = "navbar-toggle" data-toggle = "collapse" data-target = ".navHeaderCollapse">
<span class = "icon-bar"> </span>
<span class = "icon-bar"> </span>
<span class = "icon-bar"> </span>
</button>
<div class="collapse navbar-collapse navHeaderCollapse">
<ul class = "nav navbar-nav navbar-right">
<li class ="active"> Home</li>
<li> Profile</li>
<li class="dropdown">
Property <b class ="caret"></b>
<ul class="dropdown-menu">
<li> Add property </li>
<li> View property </li>
</ul>
</li>
<li> <id="logout">Log Out</li>
</ul>
</div>
</div>
</div>
</div>
<div name="container">
</div>
<script src = "js/jquery-1.11.1.js"> </script>
<script src = "js/bootstrap.js"> </script>
</body>
</html>
retailer_logout page
<?php
session_start();
if(session_destroy()) // Destroying All Sessions
{
header("Location: index.html"); // Redirecting To Home Page
}
?>
retailer_session page
<?php
// Establishing Connection with Server by passing server_name, user_id and password as a parameter
$connection = mysql_connect("abc.com", "abc", "abc");
// Selecting Database
$db = mysql_select_db("abc", $connection);
session_start();// Starting Session
// Storing Session
$user_check=$_SESSION['login_user'];
// SQL Query To Fetch Complete Information Of User
$ses_sql=mysql_query("select * from retailerregister where email='$user_check'", $connection);
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['email'];
if(!isset($login_session)){
mysql_close($connection); // Closing Connection
header('Location: index.html'); // Redirecting To Home Page
}
?>
right now i am only able to use $login_session in order to display email on profile page. Can anyone please tell my how to display other data of the logged in user on the retailer_profile page through session
Just create another variables about current logged in user:
$row = mysql_fetch_assoc($ses_sql);
$login_session =$row['email'];
// another user data
$user_name = $row['name'];
$user_country = $row['country'];
$user_city = $row['city'];
$user_state = $row['state'];
$user_occupation = $row['occupation'];
Or you can just use one variable which shouldn't be overwritten:
$user_data = $row;
And then somewhere in script:
echo $user_data['city']; // etc...
I have a login page which records the username that the user enters and adds it to a variable of $uname. However when the page after the login page loads, I cannot echo the $uname. For example, when i type
Welcome <?php echo $uname; ?>
it does not insert the username.
below is a copy of my login-validation code. but I am not sure if the $_SESSION variable is working correctly, or how to reference it in my profile.php file.
<?php
session_start();
$_SESSION['uname'] = $uname;
// Grab User submitted information
$uname = $_POST["uname"];
$pass = $_POST["pass"];
// Connect to the database
$con = mysql_connect("mysql.*********.co.uk","******","************");
// Make sure we connected succesfully
if(! $con)
{
die('Connection Failed'.mysql_error());
}
// Select the database to use
mysql_select_db("onedirectionaffection_members",$con);
$result = mysql_query("SELECT uname, pass FROM users WHERE uname = $uname");
$row = mysql_fetch_array($result);
if($row["uname"]==$uname && $row["pass"]==$pass)
header("Location: ../../profile/profile.php");
else
echo"Sorry, your credentials are not valid, Please try again.";
?>
If anyone could help I would be hugely thankful. Also, I am an absolute beginner at all of this so if you need anymore details I'll try my best to answer.
profile.php
<?php
session_start();
echo $_SESSION['uname'];
?>
<html>
<head>
<title>1D Affection</title>
<link rel="stylesheet" Type="text/css" href="../css/stylesheet.css" />
<link rel="stylesheet" Type="text/css" href="../css/font.css" />
<link rel="stylesheet" Type="text/css" href="../css/profile.css" />
</head>
<body bgcolor="white">
<div id="wrapperhead">
<div id="headcont">
<div class="logo">
<img src="../images/1DA logo ripped.png" height="150px">
</div>
<div class="subheading">
<img src="../images/1d subheading.png" height="150px">
</div>
</div>
</div> <!--END OF HEADER-->
<div id="nav">
<div class="navigation">
<ul>
<li><a class="nav" href="../index.html">Home</a></li>
<li><a class="nav" href="#">News</a></li>
<li><a class="nav" href="#">Fan-fiction</a></li>
<li><a class="nav" href="#">Gallery</a></li>
<li><a class="nav" href="#">Testimonials</a></li>
<li><a class="nav" href="http://www.onedirectionstore.com/" target="_blank">Store</a></li>
</ul>
</div> <!-- END OF MENU-->
<!-- END OF NAVIGATION-->
</div>
<div id="wrappercontent">
<div class="content">
<div class="maincont">
<div class="profcust">
<div class="profpic">
</div>
<div class="profinfo">
</div>
</div>
<div class="username">
Welcome <?php session_start(); echo $uname; ?>
</div>
<div class="story">
</div>
</div>
<div class="sidenav">
Coming Soon
</div>
</div><!--end of content-->
</div>
</body>
</html>
Seems like you haven't added session_start(); on top of your profile.php page.
Try like this
//profile.php
<?php
session_start();
echo $_SESSION['uname'];
This is probably a good part of the issue.
$_SESSION['uname'] = $uname;
$uname = $_POST["uname"];
Your setting your session's uname to blank on every load of that page. Put $_SESSION['uname'] = $uname; at the end of the code when it's validated.
1) You need to add a value to $uname first, then assign its value to $_SESSION element, so it's better be like this:
$uname = $_POST['uname'];
$_SESSION['uname'] = $uname;
or even like this:
$_SESSION['uname'] = $_POST['uname'];
2) As already mentioned, At profile.php you should also have session_start();
3) Make a clean exit like this:
header("Location: ../../profile/profile.php");
exit();
My bet is that it should be working fine after.
Some how, this is now working. From what I can figure out, the solution was to call in the $_SESSION variable, and then wrap that inside another variable. so
<?php
session_start();
$uname = $_SESSION['uname'];
?>
Thanks for all the help :D
session_start(); needs to be inside all pages using sessions.
I tested the following:
<?php
session_start(); // page_2.php
echo "Welcome " . $_SESSION['uname'];
?>
In conjunction with my test page: page_a.php
<?php
session_start();
$uname = "FRED";
$_SESSION['uname'] = $uname;
?>
CLICK
Echo'ed Welcome FRED on page 2.
I also noticed you have another instance of session_start(); in your page profile.php, remove it because you will be starting a new session while overwriting your first.
<div class="username">
Welcome <?php session_start(); echo $uname; ?>
</div>
Therefore you should be using:
$uname = $_SESSION['uname'];
in conjunction with:
<div class="username">
<?php echo "Welcome " . $_SESSION['uname']; ?>
</div>
As berkes stated in this comment you have a security issue:
$uname = $_POST["uname"];
$pass = $_POST["pass"];
Change it to:
$uname = mysql_real_escape_string($_POST['uname']);
$pass = mysql_real_escape_string($_POST['pass']);
MySQL_ functions are deprecated, therefore using MySQLi_ with prepared statements is highly suggested or PDO.
Do read the following articles:
How can I prevent SQL injection in PHP?
On owasp.org