I got user login system where user page has its own id in URL. for eg. xxx/profile.php?id=1
My question is: how to prevent logged user from writing other user id in URL and entering his site ?
here is the code of file profile.php:
session_start();
require 'config2.php';
require_once 'user.class.php';
if (!user::isLogged()) {
echo '<p class="error">Przykro nam, ale ta strona jest dostepna tylko dla zalogowanych u?ytkowników.</p>';
}
else {
$id = $_GET['id'];
$userExist = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM users WHERE id = '$id'"));
if ($userExist[0] == 0) {
die ('<p>Przykro nam, ale u?ytkownik o podanym identyfikatorze nie istnieje.</p>');
}
$profile = user::getDataById ($id);
echo '<h1>Profil u¿ytkownika '.$profile['login'].'</h1>';
echo '<b>ID:</b> '.$profile['id'].'<br />';
echo '<b>Nick:</b> '.$profile['login'].'<br />';
echo '<b>Email:</b> '.$profile['email'].'<br />';
echo '<b>Obiekt:</b> '.$profile['obiekt'].'<br />';
echo '<b>Typ obiektu:</b> '.$profile['typ'].'<br />';
echo '<b>Kod pocztowy:</b> '.$profile['kod'].'<br />';
echo '<b>Adres:</b> '.$profile['adres'].'<br />';
echo '<b>Poczta:</b> '.$profile['poczta'].'<br />';
echo '<b>Tel. stacjonarny:</b> '.$profile['tels'].'<br />';
echo '<b>Tel. komórkowy:</b> '.$profile['telk'].'<br />';
echo '<b>Adres strony internetowej:</b> '.$profile['www'].'<br />';
echo "<img src ='wyslane/$profile[photo]'";
}
and here's user_class.php:
<?php
class user {
public static $user = array();
public function getData ($login, $pass) {
if ($login == '') $login = $_SESSION['login'];
if ($pass == '') $pass = $_SESSION['pass'];
self::$user = mysql_fetch_array(mysql_query("SELECT * FROM users WHERE login='$login' AND pass='$pass' LIMIT 1;"));
return self::$user;
}
public function getDataById ($id) {
$user = mysql_fetch_array(mysql_query("SELECT * FROM users WHERE id='$id' LIMIT 1;"));
return $user;
}
public function isLogged () {
if (empty($_SESSION['login']) || empty($_SESSION['pass'])) {
return false;
}
else {
return true;
}
}
public function passSalter ($pass) {
$pass = '$###$##$'.$pass.'q2#$3$%###';
return md5($pass);
}
}
?>
I've got also my main page code here:
if (user::isLogged() == $_GET['id']) {
$user = user::getData('', '');
echo '<p>You are logged '.$user['login'].'!</p>';
echo '<p>You may see your profil or wylogować</p>';
}
else {
echo '<p>You are not logged.<br />Zaloguj się lub zarejestruj jeśli jeszcze nie masz konta.</p>';
}
I tried, what Ryan advised but it ( page) worked only when I double clicked the profile link, otherwise link sent me again to the login page.
Instead of passing the ID of the user through the URL ($_GET) try and set a $_SESSION variable with the ID of the user when he logs in.
Then you can just go to xxx/profile.php and read the $_SESSION var to find out the id of the user whose profile you want to to display.
Now I don't know how you retrieve the current logged-in user's id, but say for example you can get it from user::loggedInID() - you would just match this against the id of the profile being accessed.
For example:
if(user::loggedInID() == $_GET['id']) {
/* Allow profile to be edited */
} else {
/* Unable to edit profile */
}
As a side note, your database is extremely vulnerable with queries like so:
mysql_query("SELECT COUNT(*) FROM users WHERE id = '$id'")
Seeing as $id is retrieved from the query string, without being sanitized, the query is open to injection.
I advise not only sanitizing your query input to begin with, but also using mysqli_* functions instead of mysql_* functions (due to deprecation). Even better, use prepared statements.
While logging in just store the logged in user ID to a session variable like $_SESSION['Loggedusr'] and in each page at starting check this
session_start();
if($_SESSION['Loggedusr'] != $_GET['id'])
header("Location: loginpage.php");
Related
Currently my php login form will only carry acrocss the username on the session, I want this to carry across the user id (automatically created when the user registers).
As shown below I have included the user_id but it is not displaying on my webpage, the username is however.
Just wondering if anyone can help me with this? (I'm new to PHP)
Login process:
require_once('connection.php');
session_start();
if(isset($_POST['login']))
{
if(empty($_POST['username']) || empty($_POST['PWORD']))
{
header("location:login.php?Empty= Please Fill in the Blanks");
}
else
{
$query="select * from users where username='".$_POST['username']."' and PWORD='".$_POST['PWORD']."'";
$result=mysqli_query($con,$query);
if(mysqli_fetch_assoc($result))
{
$_SESSION['User']=$_POST['username'];
$_SESSION['user_id'] = $row['user_id'];
header("location:../manage_event.php");
}
else
{
header("location:login.php?Invalid= Please Enter Correct User Name and Password ");
}
}
}
else
{
echo 'Not Working Now Guys';
}
Session on next page:
session_start();
if(isset($_SESSION['User']) || isset($_SESSION['user_id']))
{
echo ' Welcome ' . $_SESSION['User'].'<br/>';
echo ' User ID ' . $_SESSION['user_id'].'<br/>';
}
else
{
header("location:login/login.php");
}
Though your security is questionable, i’ll answer your question anyway. As stated in another response you aren’t assigning your variables the right way. See an example here
The following code will fix your problems contrary to the other solution:
$query="select * from users where username='".$_POST['username']."' and PWORD='".$_POST['PWORD']."'";
if ($result = mysqli_query($con, $query)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
$_SESSION['User']=$_POST['username'];
$_SESSION['user_id']=$row['user_id'];
header("location:../manage_event.php");
}
}else {
header("location:login.php?Invalid= Please Enter Correct User Name and Password ");
}
}
Make sure to replace this code with your old fetching code block. Thus in the first ‘else’ clause.
How about assigning the fetched result to $row:
$query="select * from users where username='".$_POST['username']."' and PWORD='".$_POST['PWORD']."'";
$result=mysqli_query($con,$query);
if( $row = mysqli_fetch_assoc($result))
{
$_SESSION['User']=$_POST['username'];
$_SESSION['user_id'] = $row['user_id'];
I am trying to implement my own class, functions and views to implement multi-user authentication and pages with php, mysql and pdo class.
Please let me know if I am doing it in proper way or I am on wrong path?
Mysql table will look like:
userID-----------int 1
userName---------varchar abc
userPassword-----varchar pass
userAccessCode---int 100
This is the html, and php which will pass the data via post to function called(aut) in class authen
note: session will be start in header login. and close on logout
//include authen class
if(isset(POST){
$authen->name= Check_Params($_POST['name ']);
$authen->pass= Check_Params($_POST['pass']);
$authen->accs= Check_Params($_POST['accs']);
$authen->aut()
}
<form method="post">
<input name="name" type="text">
<input name="pass" type="password">
<input name="access" type="password">
<input type="submit" value="login">
</form>
Now authen class will check if the user is in database:
public function auth() {
$name = Check_Param($this->name);
$pass = Check_Param($this->pass);
$accs = Check_Param($this->accs);
$passhashed = hash_pass(Check_Params($this->password));
$stm = "SELECT COUNT(*) FROM userTBL WHERE `userName`=:name AND `userPassword`=:pass AND `userAccessCode`=:accs LIMIT 1";
$stm = $this->conn->prepare($stmt9);
$stm->bindParam(':nameo', $name);
$stm->bindParam(':passs', $passhashed);
$stm->bindParam(':accs', $accs);
$stm->execute();
$checkstm = $stm->fetchColumn();
if ($checkstm == 1) {
$_SESSION['accs'] = Check_Params($accs);
$_SESSION['name'] = Check_Params($name);
header("location:../home");
exit;
} else {
header("location:logout.php");
exit;
}
}
Now in each page this will check if it's login request, here is the ifitislogin function
public function ifitislogin() {
if ($_SESSION['name'] == '' | $_SESSION['accs'] == '') {
header("location:logout.php");
} else {
$accs = Check_Params(preg_replace('#[^0-9]#i', '', $_SESSION["accs"]));
$name = Check_Params(preg_replace('#[^A-Za-z0-9]#i', '', $_SESSION["name"]));
$stm = "SELECT COUNT(*) FROM userTBL WHERE `userName`=:name AND `userAccessCode`=:accs";
stm = $this->conn->prepare($stmt9);
$stm->bindParam(':nameo', $name);
$stm->bindParam(':accs', $accs);
$stm->execute();
$checkstm = $stm->fetchColumn();
if ($checkstm != 1) {
header("location:logout.php");
exit();
}
}
}
Now for example this is the index page for all:
//include class authentic
$authen->ifitislogin(); // this will check if user is valid:
echo "<h1>" welcome to the document management system</h1> <br/>";
//this will befor admin and operator
if($_SESSION['accs'] = Check_Params('100')){
echo "<h1>welcome to admin page data....</h1>";
} elseif($_SESSION['accs']) == 101) {
echo "<h1>welcome to reporter page data....</h1>"
} else {
echo "welcome msg";
}
//this will be for clients or users, the function will get the result from database based on the user name and accs/
$accs = Check_Params($_SESSION['accs']);
$name = Check_Params($_SESSION['name']);
//get the result from database based on these tow variable which means $accs, $name it will select from database base where access = $accs and name = $name
In this code section querying the data from database based on the data i get from session variables is it ok? if not how can i know which data should display to which user? or which page is for which user?
regards in advances.
I have problem in little project,
how can I save table data in session?
<?php
session_start();
include 'connect.php';
if (isset($_POST["email"]))
{
$email = $_POST["email"];
$password = $_POST["password"];
$r=mysql_query("SELECT * FROM user_login WHERE `uemail` ='".$email."' AND `upass` = '".$password."'");
$s = $_POST["userid"];
$n=mysql_query("SELECT * FROM user_data WHERE `userid` ='".$s."'");
$q=mysql_fetch_assoc($n);
$_SESSION["name"]=$q["nfname"];
$k=mysql_num_rows($r);
if ($k>0)
{
header("location:user/index.php");
}
else
header("location:login.php");
}
?>
this code not working !! :(
please help !
You probably just missed the
session_start();
But here is the dildo (deal tho) xD
Your Login script is not secure, try this at the top of your index.php or whatever rootfile you have.
<?php
session_start();
function _login($email, $password) {
$sql = "SELECT * FROM user_login
WHERE MD5(uemail) ='".md5(mysql_real_escape_string($email))."'
AND MD5(upass) = '".md5(mysql_real_escape_string($password))."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user with that login found!
$sql = "UPDATE user_login SET uip = '".$_SERVER['REMOTE_ADDR']."', usession = '".session_id()."'";
mysql_query($sql);
return true;
} else {
return false;
}
}
function _loginCheck() {
$sql = "SELECT * FROM user_login WHERE uip = '".$_SERVER['REMOTE_ADDR']."' AND MD5(usession) = '".md5(session_id())."'";
$qry = mysql_query($sql);
if(mysql_num_rows($qry) > 0) {
// user is logged in
$GLOBALS['user'] = mysql_fetch_object($qry);
$GLOBALS['user']->login = true;
} else {
// user is not logged in
$GLOBALS['user'] = (object) array('login' => false);
}
}
if(isset($_POST['login'])) {
if(_login($_POST["email"], $_POST["password"])) {
// login was successfull
} else {
// login failed
}
}
_loginCheck(); // checkes every Page, if the user is logged in or if not
if($GLOBALS['user']->login === true) {
// this user is logged in :D
}
?>
Ok, I'll bite. First 13ruce1337, and Marc B are right. There is a lot more wrong with this than not being able to get your data into your session.
Using PDO ( as 13ruce1337 links you too ) is a must. If you want to keep using the same style of mysql functions start reading up on how. Marc B points out that session_start(); before any html output is required for sessions to work.
As for your code, you got along ways to go before it is ready for use but here is an example to get you started
if (isset($_POST["email"])) {
//mysql_ functions are being deprecated you can instead use
//mysqli_ functions read up at http://se1.php.net/mysqli
/* Manage your post data. Clean it up, etc dont just use $_POST data */
foreach($_POST as $key =>$val) {
$$key = mysqli_real_escape_string($link,$val);
/* ... filter your data ... */
}
if ($_POST["select"] == "user"){
$r = mysqli_query($link,"SELECT * FROM user_login WHERE `uemail` ='$email' AND `upass` = '$password'");
/* you probably meant to do something with this query? so do it*/
$n = mysqli_query($link,"SELECT * FROM user_data WHERE userid ='$userid'");
//$r=mysql_fetch_assoc($n); <- this overrides your user_login query
$t = mysqli_fetch_array($n);
$_SESSION["name"] = $t['nfname'];
/* ... whatever else you have going on */
I am trying to create two separate sessions- one for if the user is admin and another if the user is author. $type stored type as enum (can be either author or admin). But my code is creating author session even for admin. I am new to PHP and MySQL . can somebody tell me where the error is in my code.
<?php
include("dbconnect.php");
$con= new dbconnect();
$con->connect();
//create and issue the query
$sql = "SELECT type FROM users WHERE username = '".$_POST["username"]."' AND password = PASSWORD('".$_POST["password"]."')";
$result = mysql_query($sql);
//get the number of rows in the result set; should be 1 if a match
if (mysql_num_rows($result) == 1) {
$type_num=0;
//if authorized, get the values
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
}
if($type == "admin")
{
$_SESSION['type']=1;
$u = 'welcome.php';
header('Location: '.$u);
}
else
{
$_SESSION['type']=$type_num;
$u = 'welcome.php';
header('Location: '.$u);
}
}
else {
//redirect back to loginfailed.html form if not in the table
header("Location: loginfailed.html");
exit;
}
?>
My welcome.php is as below
<?php
session_start();
?>
<html>
<body>
<h2>Welcome.</h2>
<?
if($_SESSION['type']==1){
echo "You are of the usertype Admin and your session id is ";
echo session_id();
}
else {
echo "You are of the usertype Author and your session id is ";
echo session_id();
}
?>
</body>
</html>
Thank You so much in advance.
Try to use roles for your permissions.
In general you have just one session. I mean you don't have two variables called _SESSION.
With the concept of roles you can simply check if a user has the permission to do something.
You have to call session_start() in the first part of the code, before register the var $_SESSION['type'] in the session
No your code seams fine, I think.
I don't see where you are calling the database
And what you have in there
So here is how you trouble shoot
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
echo $type . '<br />';
}
OR
echo '<pre>';
while ($info = mysql_fetch_array($result)) {
$type =$info['type'];
print_r($info);
}
echo '</pre>';
If you never see admin in there, and it must be 'admin' not Admin or ADMIN; then the problem is in your database. You don't have admin as admin defined, or spelled right.
By the way. see how nicely I formatted that. It's easier to read that way.
Coders wont look at your code if you don't do that.
Try using session_regenerate_id(); method to create different session ids.
I'm really struggling with this now for a while and can't seem to get it working. In members.php (where I show all the registered users) I have a list printed out with a link "ADD TO FRIENDS" next to each user.
I managed, for testing purposes to display each members id well (so it gets the ID) but when I click the link it directs to the friends.php where it seems the fault is in. I don't know how to get that friend's id I clicked on IN THE friends.php file. Please have a look!
members.php
<?php
include 'connect.php';
include 'header.php';
if(isset($_SESSION['signed_in']) == false || isset($_SESSION['user_level']) != 1 )
{
//the user is not an admin
echo '<br/>';
echo 'Sorry! You have to be <b>logged in</b> to view all the <b>registered</b> members.';
echo '<br/><br/>';
}
else
{
echo '<h2>Registered users:</h2>';
$sql = "SELECT * FROM users ORDER BY user_name ASC";
$result = mysql_query($sql);
$num=mysql_numrows($result);
$i=0;
while ($i < $num)
{
//$name = mysql_result($result,$i,"user_name");
//$id = mysql_result($result,$i,"user_id");
//$picture = mysql_result($result,$i,"pic_location");
//?friend_id="'. $id .'
while($user = mysql_fetch_array($result)){
echo $user['user_name'].'<br/><br/>ADD TO FRIENDS<br/>';
echo $user['user_id'];
echo '<br/><br/>';
}
$i++;
}
///////////////////////////////
/// adding users as friends ///
///////////////////////////////
//while($user = mysql_fetch_array($result))
//echo $user['user_name'].'
//ADD TO FRIENDS<br/>';
//NOW I WANT TO MAKE A SPECIFIC "ADD AS FRIEND" LINK NEXT TO EACH USER
}
include 'footer.php';
?>
As I said I'm not sure how to get this so please have a look! Thanks!
J
friends.php
<?php
include "connect.php";
include "header.php";
if(isset($_SESSION['signed_in']) == false || isset($_SESSION['user_level']) != 1 )
{
//the user is not an admin
echo '<br/>';
echo 'Sorry! You have to be <b>logged in</b> if you want to add the person as a friend!';
echo '<br/><br/>';
}
else
{
$sql = "SELECT * FROM users";
$result = mysql_query($sql);
//friend_id is the ID of the friend that is clicked on...
//HOW DO I GET THAT ID THAT IS CLICKED ON IN THE WHILE "loop" in members.php?
$friends = ("INSERT INTO friends SET user_id='" . $_SESSION['user_id'] . "', friend_id='".$id."', status='0'");
$result_friends = mysql_query($friends);
if(!$friends)
{
//When you can't add this person as a friend this error will show!
echo 'You cannot add this user at this time. Please try again later!';
}
else
{
//When the friend is now added to the system!
echo 'Great! Now the user needs to approve before you can be friends!';
}
}
?>
On your friends.php use
$_GET['user_id']
Instead of $id, $id is undefined, to get the value of id from the query string you call it using an $_GET variable like,
$_GET['name_of_query_string_value']