How to view other users profile if session is set in php - php

Well I am trying to create kind of a social network but there is a problem with my session. So I am not able to visit other users profile. This is my code for loginwebsite1.php
<?php
ob_start();
session_start();
$connection = mysqli_connect('localhost', 'root', '123456789', 'register');
if (isset($_POST['email1'])) {
$email = mysqli_real_escape_string($connection, htmlentities($_POST['email1']));
}
if (isset($_POST['password1'])) {
$password = mysqli_real_escape_string($connection, htmlentities($_POST['password1']));
}
if (!empty($email) && !empty($password)) {
$query = "select id from register where email='$email' and password='$password'";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
if ($row > 0) {
$_SESSION['id'] = $row;
$_GET['id'] = $row;
header('location: new.php');
} else {
echo "sorry but the email-id or password is wrong";
}
} else {
echo "please enter your email-id or password or there";
}
?>
My session code goes like this:
<?php
ob_start();
session_start();
if (isset($_SESSION['id']) && !empty($_SESSION['id'])) {
$id = $_SESSION['id'];
foreach ($id as $fn)
$connection = mysqli_connect('localhost', 'id', 'password', 'register');
$query = "select firstname,lastname from register where id='$fn'";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
$firstname = $row['firstname'];
$lastname = $row['lastname'];
} else {
header('location: loginwebsite1.php');
}
?>
But when I try to enter like profile.php?id=9 it still opens the profile of the user who is logged in.

$id=$_SESSION['id'];
This line is where you problem is I believe. Here you get the ID number for the profile page to load from the $_SESSION variable when you should be getting it from the $_GET variable.
It should read:
$id=$_GET['id'];

you should also check if the $_GET['id'] is also set like this
$connection=mysqli_connect('localhost','id','password','register');
if(isset($_SESSION['id']) && !empty($_SESSION['id']) || !empty($_GET['id']))
{
$id=!empty($_GET['id'])? $_GET['id']: $_SESSION['id'];
foreach($id as $fn){
$query="select firstname,lastname from register where id='$fn'";
$result=mysqli_query($connection,$query);
$row=mysqli_fetch_array($result);
$firstname=$row['firstname'];
$lastname=$row['lastname'];
}
}else{
header('location: loginwebsite1.php');
}
also set your $connection variable to connect only once to your database.

Related

Extend expiry on sessions token PHP

I am trying to store sessions in the local storage of the user when they log in, but the expiry of the session is short and it is deleted every time I route to another page, and I could not figure out what had gone wrong. Below is some snippet of my code.
connect.php
<?php
$host = "localhost";
$username = "root";
$password = "";
$database = "ezcar2";
$conn = mysqli_connect($host, $username, $password, $database);
?>
ct_home.php
<body>
<?php
include_once 'connect.php';
session_start();
if (!isset($_SESSION['username'])) {
header("Location: ct_login.php");
exit();
}
?>
</body>
Whenever I refresh the page, I would be redirected back to ct_login.php. I would like for the session to stay until the user logs out.
EDIT (ct_login.php && setting the sessions)
<?php
include_once 'connect.php';
session_start();
if(isset($_POST['btnlogin'])){
$c_username = trim($_POST['txtusername']);
$c_password = trim($_POST['txtpwd']);
$sql_query = "SELECT * FROM tblcustomer WHERE CT_USERNAME = '$c_username' AND CT_PASSWORD = '$c_password'";
$sql_role = "SELECT * FROM tblcustomer WHERE CT_USERNAME = '$c_username' AND CT_PASSWORD = '$c_password' AND CT_ROLE = 'CAR OWNER'";
$sql_status = "SELECT * FROM tblcustomer WHERE CT_USERNAME = '$c_username' AND CT_PASSWORD = '$c_password' AND CT_STATUS = 'APPROVED'";
if($result = mysqli_query($conn, $sql_query)){
$rows = mysqli_num_rows($result);
if($rows == 1) {
if ($status = mysqli_query($conn, $sql_status)) {
$row_ = mysqli_num_rows($status);
if($row_ == 1) {
if($role = mysqli_query($conn, $sql_role)){
$rows_ = mysqli_num_rows($role);
if($rows_ == 1) {
//store username & password in session variable
$rec = mysqli_fetch_row($role);
$_SESSION['username'] = $rec[7];
$_SESSION['role'] = $rec[9];
header("Location: ct_home.php");
// session_start();
} else {
$rec = mysqli_fetch_row($result);
$_SESSION['username'] = $rec[7];
$_SESSION['role'] = $rec[9];
header("Location: ct_home.php");
// session_start();
}
}
} else {
echo('<script>alert("Account request is still pending. Please wait for confirmation email.");</script>');
echo "<meta http-equiv='refresh' content='0'>";
exit();
}
}
} else {
echo('<script>alert("Invalid Credentials. Please try again!");</script>');
echo "<meta http-equiv='refresh' content='0'>";
exit();
}
}
}
?>
Edit (#1) : The database connection is used to validate user login
Please let me know what else I can provide to draw a clearer picture of the whole situation. Many thanks in advance.

PHP Log in page with hashed password issue

So I am trying to create a simple login structure, and im not sure why it does not work, I appreciate there are many examples on here, and please do not mark this for duplication, I just really need some help I have tried and tried but I can not see what I have done wrong.
<?php
session_start();
include 'databaseconnection.php';
$email = strip_tags($_POST['email']);
$pwd = strip_tags($_POST['pwd']);
$sql = "SELECT * FROM user WHERE email='$email'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$hash_pwd = $row['pwd'];
$hash = password_verify($pwd, $hash_pwd);
if ($hash == 0) {
header("Location: error.php")
exit();
} else {
$sql = "SELECT * FROM user WHERE email='$uid' AND pwd ='$hash_pwd'";
$result = mysqli_query($conn, $sql);
if (!row = mysqli_fetch_assoc($result)); {
echo "your email address or password is incorrect!";
} else {
$_SESSION['id'] = $row['id'];
}
header("Location: profile.php")
If someone could simply suggest what changes I should make, I would really appreciate it.
There you go simple code
<?php
session_start();
include 'databaseconnection.php';
$email = $_POST['email'];
$pwd = $_POST['pwd'];
$sql = "SELECT * FROM user WHERE email = '$email'";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$hash_pwd = $row['pwd']; // password from database
// if password is valid start session and redirect to profile.php
if (password_verify($pwd, $hash_pwd))
{
$_SESSION['id'] = $row['id'];
header('Location: profile.php');
}
else
{
header("Location: error.php")
exit();
}
?>
You have not closed the "} else {"... section.
First check request second filter input third use pdo
<?php
session_start();
include 'databaseconnection.php';
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
$email = filter_input(INPUT_POST, 'email',FILTER_VALIDATE_EMAILL); //filter input
$pwd = filter_input(INPUT_POST, 'pwd',FILTER_SANITIZE_STRING,FILTER_FLAG_STRIP_HIGH); //filter input
$hashed = sha1($pwd);
$sql= $conn->prepare( "SELECT * FROM user WHERE email ? AND password = ?"); //use pdo here
$sql->execute(array($email, $pwd));
$row = $sql->fetch();
if($row['email'] !== $email || $row['password'] !== $hashed){
header("Location: error.php");
exit();
} else {
$_SESSION['id'] = $row['id'];
header("Location: profile.php");
}
}else {
echo 'error';
}
?>

php header not working online but working on my localhost.....why?

This works perfectly well on my localhost but when i hosted online, it does not logon and it echo logged on successful and error free. Pls what can be the cause for this?
<?php
session_start();
$_SESSION['user_logged']=$user;
$_SESSION['user_password']=$password;
$user = $_POST["username"];
$password = $_POST["password"];
include("include/connect.php");
$msg = array();
if(isset($_POST['submit'])){
foreach($_REQUEST as $key=>$val){
$$key=$val;
}
if(count($msg)==0){
$sql="SELECT username, password FROM admin WHERE username='$username' && password='$password'";
$res=mysql_query($sql) OR die(mysql_error());
if(mysql_fetch_array($res)>0){
$_SESSION['user_logged']= $user;
$_SESSION['user_password']=$password;
header("location:dashboard.php");
echo "You looged in Successfully";
} else{
$msg[]='Incorrect username/password';
}
}
}
?>
Below is the dashboard.php which its suppose to redirect to.
<?php
include('include/connect.php');
include('include/function.php');
if(isset($_REQUEST['mode']) )
{
$mode=$_REQUEST['mode'];
if($mode == 1)
{
$id=$_REQUEST['id'];
$sql="DELETE FROM enquiry WHERE id='$id'";
$result=mysql_query($sql);
}
}
$msg=array();
if(isset($_POST['submit'])){
$title=$_POST['news'];
$news_item=$_POST['news'];
if(empty($news_item)){
$msg[]='You must enter news in the column!';
}
if(empty($title)){
$msg[]='News Title must not be empty!';
}
else {
$sql = "SELECT * FROM news_file WHERE title='$title' ";
$res = mysql_query($sql) or die(mysql_error());
$result = mysql_fetch_array($res);
if($result > 0){
$msg[] = 'News with the same title has been added already';
} else {
$sql = "INSERT INTO news_file (title,news,date) VALUES ('$title','$news_item',Now())";
$result = mysql_query($sql);
$msg[]='News was successfully added';
}
}
}
?>
Try this.
<?php
session_start();
/*
These should be the other way round, as you are setting
the session variables with variables which have not been
initialised yet
*/
$user = $_POST["username"];
$password = $_POST["password"];
$_SESSION['user_logged']=$user;
$_SESSION['user_password']=$password;
include("include/connect.php");
$msg = array();
if(isset($_POST['submit'])){
foreach($_REQUEST as $key=>$val){
$key=$val; // Removed Erroneous double $
}
if(count($msg)==0){
$sql="SELECT
username,
password
FROM
admin
WHERE
username='$username'
AND
password='$password'";
// MySql does not accept && as a comparison operator.
$res=mysql_query($sql);
if(!$res)
{
var_dump(mysql_error());
exit;
}
else
{
if(mysql_fetch_array($res)>0)
{
$_SESSION['post'] = $_POST;
while(mysql_fetch_array($res)>0)
{
$_SESSION['user_logged']= $user;
$_SESSION['user_password']=$password;
header("location:dashboard.php");
echo "You logged in Successfully";
}
}
else
{
msg[]='Incorrect username/password';
}
}
?>
Looking at the code you have provided for dashboard.php, you are expecting there to be $_POST data, for a page which you have redirected to. Where you have redirected to the page, there will be no $_POST data for you to retrieve from the server.
I have amended my script above, to store the $_POST data in the session, so using that, you should be able to call your news items by calling $_SESSION['post']['news'], or if this is too long winded, simply re-assign the POST data once inside your dashboard.php script like so.
$post = $_SESSION['post'];
Then you can call it by using $post['news'].

Can't fetch data from MySQL (php) (Re-edited)

I have realized why i can't actually access userdata (after i am logged) old way to find the username is $_SESSION['username']; (assuming there is a row as 'username' in MySQL database)
So as i have a test account as "good25" (reason to choose numbers was to see if Alphanumeric inputs works fine.. its just checkup by me.. nevermind)
Problem :
assuming, i have rows in a table as 'username' and all of his information.. such as 'password', 'email', 'joindate', 'type' ...
On net i found out how to snatch out username from Session
<?php session_start(); $_SESSION('username'); ?>
successful!!
i had an idea to check if session is actually registering or no??
after a log on start.php i used this code
if(isset($_SESSION['username'])) { print_r($_SESSION['username']); }
the result was "1" (while i logged in using this username "good25")
any suggestions?
index.php (lets say, index.php just holds registration + Login form + registration script.. in login form, action='condb.php')
<?php
require 'condb.php';
if (isset($_POST['btn-signup']))
{
//FetchInputs
$usern = mysqli_real_escape_string($connection,$_POST['username']);
$email = mysqli_real_escape_string($connection,$_POST['email']);
$password = mysqli_real_escape_string($connection,$_POST['password']);
$repassword = mysqli_real_escape_string($connection,$_POST['repassword']);
$usern = trim($usern);
$email = trim($email);
$password = trim($password);
$repassword = trim($repassword);
//SearchUser
$searchusr = "SELECT username FROM $user_table WHERE username='$usern'";
$usersearched = mysqli_query($connection, $searchusr);
$countuser = mysqli_num_rows($usersearched);
//SearchEmail
$searcheml = "SELECT email FROM $user_table WHERE email='$email'";
$emlsearched = mysqli_query($connection, $searcheml);
$counteml = mysqli_num_rows($emlsearched);
//RegisteringUser
if ($countuser == 0)
{
if ($counteml == 0)
{
$ctime = time();
$cday = date("Y-m-d",$ctime);
$aCode = uniqid();
$adduser = "INSERT INTO $user_table(username, email, password, realname, activationcode, verified, joindate, type, points) VALUES ('$usern','$email','$password','$name','$aCode','n','$cday','Free',$signPoints)";
if (mysqli_query($connection, $adduser))
{
?><script>alert('You have been registered');</script><?php
}
else {
?><script>alert('Couldnt Register, please contact Admin<br><?mysqli_error($connection);?>');</script><?php
}
} else {
?><script>alert('Email already exists!');</script><?php
}
} else {
?><script>alert('Username already exists!');</script><?php
}
}
?>
condb.php
$connection = mysqli_connect($db_server, $db_user, $db_pass);
mysqli_select_db($connection, $db_name);
if(!$connection) {
die ("Connection Failed: " . mysqli_connect_error);
}
if (isset($_POST['btn-login']))
{
$uname = mysqli_real_escape_string($connection,$_POST['uname']);
$upass = mysqli_real_escape_string($connection,$_POST['upass']);
//FindUser
$finduser = "SELECT * FROM $user_table WHERE username='$uname' AND password='$upass'";
$findinguser = mysqli_query($connection,$finduser);
$founduser = mysqli_num_rows($findinguser);
//ConfirmPassword
if ($founduser > 0)
{
session_start();
$_SESSION['username'] = $username;
$_SESSION['username'] = true;
if ($findinguser != false)
{
while ($fetchD = mysqli_fetch_array($findinguser, MYSQLI_ASSOC))
{
$fetchD['username'] = $usernn;
$fetchD['email'] = $email;
$fetchD['userid'] = $uid;
$fetchD['realname'] = $rlnm;
$fetchD['points'] = $pts;
$fetchD['type'] = $membertype ;
}
header("Location: start.php");
} else {
echo mysqli_error();
}
} else {
header("Location: index.php");
?><script>alert('Wrong details, please fill in correct password and email');</script><?php
}
}
I am not asking you to build a script.. just little help please? (Thank you so so so so so much, as i am a self-learner, you don't have to say everything.. just a clue is enough for me)
may be you can try this code
<?php
require_once 'require.inc.php';
//session_start();
if (isset($_POST['btn-login']))
{
$uname = mysqli_real_escape_string($_POST['uname']);
$upass = mysqli_real_escape_string($_POST['upass']);
$search = mysqli_query($connection, "SELECT username, userid, password from $user_table WHERE username='$uname' AND password='$upass'");
$match = mysqli_fetch_assoc($search);
if ($match == 1 and $match['password'] == md5($upass))
{
$_SESSION['username'] = $match['userid'];
} else {
?>
<script>alert('Password or E-mail is wrong. If you havent registered, Please Register');</script>
<?php
}
}
if (isset($_SESSION['username']) or isset($match['userid'])){
header("Location:start.php");
}
if (isset($_POST['btn-signup']))
{
$name = mysqli_real_escape_string($_POST['name']);
$usern = mysqli_real_escape_string($_POST['username']);
$email = mysqli_real_escape_string($_POST['email']);
$password = mysqli_real_escape_string($_POST['password']);
$repassword = mysqli_real_escape_string($_POST['repassword']);
$name = trim($name);
$usern = trim($usern);
$email = trim($email);
$password = trim($password);
$repassword = trim($repassword);
$query = "SELECT email FROM $user_table WHERE email='$email'";
$result = mysqli_query($connection, $query);
$count = mysqli_num_rows($result);
$querytwo = "SELECT username FROM $user_table WHERE username='$usern'";
$resulttwo = mysqli_query($connection, $querytwo);
$counttwo = mysqli_num_rows($resulttwo);
if ($count == 0 AND $counttwo == 0)
{
if ($password == $repassword) {
if (mysqli_query($connection, "INSERT INTO $user_table(username, email, password, realname) VALUES ('$usern','$email','$password','$name')"))
{
?>
<script> alert ('Successfully registered'); </script>
<?php
}
}else {
?>
<script> alert ('The Password you entered, doesnt match.. Please fill in the same password'); </script>
<?php
}
}
else {
?>
<script> alert('Username or E-mail already exist'); </script>
<?php
}
}
?>
and this is for require.inc.php
<?php
global $username;
//require 'dconn.php';
session_start();
$_SESSION["username"] = $username;
$connection = mysqli_connect("localhost","root","", "test") or die(mysqli_error());
// Check Login
if (isset($_SESSION['username']) and isset ($match['userid']))
{
$Selection = "SELECT * FROM $user_table WHERE username='$username'";
$selectQuery = mysqli_query($connection, $Selection);
if ($selectQuery != false)
{
while ($fetchD = mysqli_fetch_assoc($selectQuery))
{
$usernn = $fetchD['username'];
$email = $fetchD['email'];
$uid = $fetchD['userid'];
}
} else {
echo mysqli_error();
}
}
?>
#suggestion, create session after user login and authorized then for each page start session and take session which you created and perform SQL queries using that session variable.
for example :
$_SESSION['user_name']=$row['username'];
for each page:
session_start();
$user_name=$_SESSION['user_name'];
SQL query
mysqli_query($con,"SELECT * FROM users where column_name='$user_name'");
I think you need to include dconn.php file in all files where you want to perform the mysql operation. If you have included it only in require.inc.php then you you it in all your other files.

Storing multiple variables in a single $_SESSION(PHP)

How would I make this work, I asked before and didn't get a correct answer. This code is the user login, so when they log in I want username and avatar to be trackable through out the site. So far I just have username. I have tried methods and have failed every time.
$username = $_POST['username'];
$password = sha1($_POST['password']);
$sql = "SELECT * FROM users WHERE username = '$username' AND password = '$password'";
$result = mysqli_query($conn, $sql) or die('Error querying database.');
$count=mysqli_num_rows($result);
if ($count == 1)
{
$row = mysqli_fetch_array($result);
while ($_SESSION['username'] = $row['username'])
{
session_start();
header('Location: index.php');
}
}
else
{
echo 'Invalid Logins';
}
mysqli_close($conn);
?>
Supposing you have avatar stored in the avatar field in the database:
if ($count == 1)
{
session_start();
$row = mysqli_fetch_array($result);
$_SESSION['username'] = $row['username'];
$_SESSION['avatar'] = $row['avatar'];
header('Location: index.php');
}
else
{
echo 'Invalid Logins';
}

Categories