This is my php for viewing user profile - php

My Profile php
<?php
//profile.php
require_once 'includes/global.php';
//check to see if they're logged in
if(!isset($_SESSION['logged_in'])) {
header("Location: login.php");
}
// finding user and viewing it
$tools = new FindUser();
$user = $tools->get($_REQUEST['userID']);
?>
This is my php for viewing user profile.
http://mywebsite.com/profile.php?userID=5 its working fine in this way.
i want my code to check if user is available in database for example if i add ?userID=10 which is not present in database it gives out mysql error or even if i use http://mywebsite.com/profile.phpthen also it give error.
so now i want if user is not available in database it should give that user is not available and when we use simple http://mywebsite.com/profile.php it should give auto add it to userID=1 OR REDIRECT it to home.php
If there is other way of doing this please let me know. well im very newbie in this field
Thanks for looking my question and answering :)
Solved
<?php
//profile.php
require_once 'includes/global.php';
//check to see if they're logged in
if(!isset($_SESSION['logged_in'])) {
header("Location: login.php");
}
$UserID = $_GET['userID'];
$CheckQuery = mysql_query("SELECT * FROM users WHERE id='$UserID'");
$CheckNumber = mysql_num_rows($CheckQuery);
if ($CheckNumber !== 1)
{
header("Location: index.php");
}
// finding user and viewing it
$tools = new FindUser();
$user = $tools->get($_REQUEST['userID']);
?>

You shouldn't use MySQL As it's depreciated,
If you really wish to use MySQL You could check at the start of the script if there is a row count for the User ID, Example:
<?
$UserID = $_GET['UserID'];
$UserID = mysql_real_escape_string($UserID);
$CheckQuery = mysql_query("SELECT * FROM users WHERE userID='$UserID'");
$CheckNumber = mysql_num_rows($CheckQuery);
if ($CheckNumber !== 1)
{
// Do something If user is Not Found
// Redirect to Another Page OR Something
}
?>

than check that query give with result if it wont found data in database than redirect
$result = mysql_query(...);
if(mysql_num_rows($result) !=1){ //
header("Location:signup.php");
exit();
}
You shouldn't use MySQL As it's depreciated, either use PDO or mysqli

Related

set session variable to user_id when user logs in

I'm setting up a login/logout and I'm trying to send the users id number to other pages in the website so that I can manipulate the database when I want.
I use a query to match email/password and log in user(n.b. this is not the full code and not the problem, I'm matching emails and passwords)
$find= mysqli_query("SELECT * FROM users WHERE email='$ema' and password="$pw");
Then I fetch an array and start a session which I then check on pages further on in the website.
if(mysql_num_rows($find) == 1){
$row = mysql_fetch_array($result, MYSQL_BOTH);
$id= $row ['id'];
session_start();
$_SESSION['Login']= $id;
// Redirect - I use JS to send users to next page
}
else {
echo '<script type="text/javascript">';
echo 'alert("Invalid Username or Password");';
echo 'history.back();';
echo '</script>';
}
mysql_close($link);
On other pages I have code that checks for the session and redirects users if they aren't logged in. Here's that code:
<?php
session_start();
if(!isset($_SESSION['Register'])){
if(!isset($_SESSION['Login'])){
header("location:../notLoggedIn.php");
}
}
$get_id = $_SESSION['Register'];
$get_id = $_SESSION['Login'];
?>
Then, when I check what's in the id variable passed from the login page with this:
$profile = mysql_query("SELECT * FROM profiles WHERE id= $id");
var_export($id);
I get a null value. What's going wrong?
You must check if session is not started then use session_start();
if (session_status() == PHP_SESSION_NONE) {//php >5.4
session_start();
}
and use $_SESSION['Login'] instead of $id
$profile = mysql_query("SELECT * FROM profiles WHERE id=".$_SESSION['Login']);
Multiple mistakes i have seen.
1)First revise your query :
$find= mysqli_query("SELECT * FROM users WHERE email='$ema' and password='$pw');
2) Secondly start session on the top of file.
3) mysqli_close($link); instead of mysql_close($link);
4) In the Last check if the session is properly set.
if(isset($_SESSION['Login'])) {
$get_id = $_SESSION['Login'];
$profile = mysql_query("SELECT * FROM profiles WHERE id= $id");
var_export($id);
}
Hi Please note these points
1) Start session_start on the top of page (before any echo or white space).
2) I don't see your $_SESSION['Register']. Have you set it
3) You are passing session variable not simple variable so use this
$profile = mysql_query("SELECT * FROM profiles WHERE id = $_SESSION['Login']");
var_export( $_SESSION['Login']);
As $id will be null here always

PHP Multiple Restricted Access

I am trying in my PHP to make it to where if the Account database value matches 0 or 1 or 2 or 3 then it makes the login go to a certain page but so far it doesn't log me in and it doesn't take me to the page. Before I had a log in page but it sent it to a universally restricted page, but what I want is depending on what the User signed up for then he gets put this value(which I have already implemented) that if this page were to work than it would send him to one of four restricted sites upon login. What I can't get is the value to get pulled and used to send him upon login to the specific page.I am using Mysqli. Here is the code:
<?php require 'connections/connections.php'; ?>
<?php
if(isset($_POST['Login'])){
$Username = $_POST['Username'];
$Password = $_POST['Password'];
$result = $con->query("select * from user where Username='$Username'
AND Password='$Password'");
$row = $result->fetch_array(MYSQLI_BOTH);
$AccountPerm = $con->query("SELECT * FROM `user` WHERE Account =
?");
session_start();
$AccountPerm = $_SESSION['Account'];
if($AccountPerm == 0){
header("Location: account.php");
}
if($AccountPerm == 1){
header("Location: Account1.php");
}
if($AccountPerm == 2){
header("Location: Account2.php");
}
if($AccountPerm == 3){
header("Location: Account3.php");
}
}
?>
so far it doesn't log me in
Just to be sure, your Account.php, Account1.php, Accout2.php and Account3.php rely on $_SESSION['Account'] right? (The code below assume so)
As for your problem with both login and redirecting you forget a line :
$_SESSION['Account'] = $row['Account'];
Also, I removed
$AccountPerm = $con->query("SELECT * FROM `user` WHERE Account =
?");
You code should look like :
<?php require 'connections/connections.php'; // NOTE: I don't close the php tag here ! See the "session_start()" point in the "Reviews" section below
if(isset($_POST['Login'])){
$Username = $_POST['Username'];
$Password = $_POST['Password'];
// TODO: Sanitize $Username and $Password against SQL injection (More in the "Reviews" section)
$result = $con->query("select * from user where Username='$Username'
AND Password='$Password'");
// TODO: Check if $result return NULL, if so the database couldn't execute your query and you must not continue to execute the code below.
$row = $result->fetch_array(MYSQLI_BOTH);
// TODO: Check if $row is NULL, if so the username/password doesn't match any row and you must not execute code below. (You should "logout" the user when user visit login.php, see the "Login pages" point in the "Reviews" section below)
session_start();
$_SESSION['Account'] = $row['Account']; // What you forgot to do
$AccountPerm = $_SESSION['Account'];
if($AccountPerm == 0){
header("Location: account.php");
}
if($AccountPerm == 1){
header("Location: Account1.php");
}
if($AccountPerm == 2){
header("Location: Account2.php");
}
if($AccountPerm == 3){
header("Location: Account3.php");
}
}
?>
Reviews
session_start()
Should be call at the top of your code. (It will probably end-up in a a shared file like connections.php that you will include in all of your file).
One reason is that session_start() won't work if you send ANY character to the user browser BEFORE calling session_start().
For exemple you close php tag after including connections.php, you may not know but you newline is actually text send to the browser !
To fix this you just have to not close your php tag, such as in
<?php require 'connections/connections.php'; ?>
if(isset($_POST['Login'])){
Login page
Make sure to logout (unset $_SESSION variables that you use to check if user is logged) the user in every case except if he enter the right username/password combinaison.
If the user is trying to login it may be a different user from the last time and we don't want him to be logged as somebody else if his username/password is wrong.
MySQL checks : You should always check what the MySQL function returned to you before using it ! (see the documentation !) Not doing so will throw php error/notification.
SQL injection : You must sanitize $Username/$Password before using them into your query.
Either you append the value with $con->real_escape_string() such as
$result = $con->query("SELECT * FROM user WHERE Account = '" . $con->real_escape_string($Username) . "' AND Password = '" . $con->real_escape_string($Password) ."')
or you use bind parameter, such as explained in this post (THIS IS THE RECOMMENDED WAY)
No multiple account pages
Your login page should redirect only to accout.php and within this page split the logic according with the $_SESSION['Account'] value.
Nothing stop you from including account1.php, account2.php, ... within account.php.
If you do so put your account1.php, account2.php, account3.php in a private folder that the user can't browse in.
(One of the method is to create a folder (such as includes) and put a file name .htaccess with Deny from all in it)

PHP MYSQL check if row data is the same as

I'm a little new to PHP and MYSQL. I'm creating an admin panel, in the MySQL database I have a column called admin.
I want it to check the column, So if admin has 0 on it, it will header to index.php but if it has 1 it will header to admin.php.
I would also like some help, For admin.php I want something like, if you were not on the database (checks if admin has 1 in the username), it will head somewhere else.
Admin.php code:
<?php
session_start();
include_once 'dbconnect.php';
if (isset($_SESSION['user']) != "") {
header("Location: home.php");
}
if (isset($_POST['btn-login'])) {
$uname = mysql_real_escape_string($_POST['uname']);
$admin = mysql_real_escape_string($_POST['admin']);
$upass = mysql_real_escape_string($_POST['pass']);
$res = mysql_query("SELECT * FROM users WHERE admin = '1'");
$row = mysql_fetch_array($res);
if ($row['admin'] == 1) {
header("Location: admin.php");
}
else {
echo 'Shithead';
}
}
?>
For a start you need to fetch the right row for the user. You are fetching only rows that are admins !!! Something like this.
$res=mysql_query("SELECT * FROM users WHERE uname='$uname' and pass='$pass'");
assuming that your db fields are called uname and pass.
You need to get this working and then ask a new question for the rest.

Updating user information

I know I can't use two session start codes in a same php page but for the sake of updating user account, I need the below code and I need to use session_start twice. One, to check if the user is not logged in, then redirect them and banned them from seeing the update info page and also the other session start has to be there so that my session variables could be set automatically in the update info page if the user is logged in.
anyways, I am getting this error can you guys please show me a work around way? if there's any?
thanks.
Notice: A session had already been started - ignoring session_start() in ....
<?php session_start();
if(isset($_SESSION['userid'])) {
} else {
header('Location: login.php');
}
?>
<?php
$user = $_SESSION['userid'];
$myquery = "SELECT * FROM our_users WHERE `userid`='$user'";
$result = mysqli_query($conn, $thequery);
$row = mysqli_fetch_array($result, MYSQLI_BOTH);
session_start(); /* Basically this right here gets ignored. */
$_SESSION["user_first_name"] = $row['fn'];
$_SESSION["user_last_name"] = $row['ln'];
$_SESSION["user_email"] = $row['em'];
$_SESSION["user_password"] = $row['pw'];
?>

Page protection for the Admin page not working

I have been trying to make a page protection for the Administrator page, and I can not get it to work. I am sure this would not have been a problem if I was not new to PHP coding, hehe.
So what I am trying to do is, when a normal user with the type '0' is trying to access the administrator page, index_admin.php, the user will get redirected to the normal user page, index.php. And if the user have the type '1', then the user/admin will stay on the page.
So here is the code I have been trying to get working. (This file is required in index_admin.php and it is called index_admin_check.php):
<?php
session_start();
?>
<?php
$vert = "localhost";
$brukarnamn = "root";
$passord = "";
$db_namn = "nettsidebunad";
$tbl_namn = "kunde_register";
// Connecting to the MySQL database.
mysql_connect("$vert", "$brukarnamn", "$passord") or die ("Kan dessverre ikkje koble til databasen.");
mysql_select_db("$db_namn") or die ("Kan ikkje finna den ynkjande databasen.");
?>
<?php
// *** Page protection *** \\
// Admin check. If `type` = 1, let the user (admin) stay on the site. If `type` = 0 kick the user (normal) off the site.
$sql = "SELECT `type` FROM $tbl_namn";
$res = mysql_query($sql);
$tell = mysql_num_rows($res);
if ($tell == 0) {
header ("location: index.php");
exit();
}
?>
Some of this text is in norwegian.
$vert = $host (in english)
$brukarnamn = $usernamn (in english)
$passord = $password (in english)
$db_namn = $db_name (in english)
$tbl_namn = $tbl_name (in english)
$sql = "SELECT `type` FROM $tbl_namn";
This SQL query will return a row for every user in your database. Using your method of simply checking whether the query returned a result or not, you need to select just the row for the current user, and then only if the user has type=1.
You need to make sure that:
The user has previously logged into the system using a username and password or some such
You have saved their details to the session.
If your user table has an ID column, and you saved the ID of the logged in user to the session as 'userid', you might use the query:
$sql = "SELECT `type` FROM $tbl_namn WHERE id = {$_SESSION['userid']} AND type = 1";
But of course that would be moot, because you would just have save the user's type in the session when you first logged them in, wouldn't you?
Well for what I can see, you don't actually check for user.
I will make some remarks to your code to make situation clear:
$sql = "SELECT `type` FROM $tbl_namn"; //Return all values of column "type" from table - instead you should search for specifyc user
$res = mysql_query($sql);
$tell = mysql_num_rows($res); //Count returned rows
So instead of finding out the user type, you get the count of registered users.
What you should do to search for user name and get user type for that name. So lets think of this table concept:
ID | name | type |
Now we can start our user check up. We will ask mysql for type of user "admin".
$name = $_POST["username"]; //username submited in POST HTML form
$name = mysql_real_escape_string($name); //Replace dangerous characters from name. This is important to avoid your database being hacked
$data = mysql_query("SELECT type FROM $tbl_namn WHERE name='$name'") or die(mysql_error()); //On failure, you will is if there is some error
$data=mysql_fetch_row($data); //Get actual data
if($data["type"]==0) {
header("HTTP/1.1 403 Acces Forbidden");
header("Location: forbidden.html"); //send user to page telling me he is not allowed to enter. As well you can use include here.
exit;
put this to login page:
<?php session_start();
if ($_POST['type'] = "1") {
Header('location: http://example.com/admin.php/');
$_SESSION['admin']; = "yes";
exit;
} else {
Header('location: http://example.com/user.php/');
$_SESSION['admin']; = "no";
exit;
}
//modify as needed
?>
and this one into admin.php filename can be any but extension needs to be .php:
<?php session_start():
if ($_SESSION['admin']; = "no") {
Header('location: http://example.com/user.php/');
exit;
}
//modify as needed
?>
and remember to put this in the very beggining of the file otherwise sessions won't work

Categories