Php Function Restricted area - php

Hey i have this function :
<?php
if(isset($_POST['login']) && $_POST['login'] == 'LOGARE') {
include('./inc/configurare.php');
mysql_select_db('account');
$user = mysql_real_escape_string($_POST['user']);
$pass = mysql_real_escape_string($_POST['pass']);
$check = "SELECT * from account where login = '" . $user . "' and password = PASSWORD('$pass')";
$query = mysql_query($check);
$num = mysql_num_rows($query);
if($num > 0) {
$array = mysql_fetch_array($query);
// SESSION variable start //
$_SESSION['id'] = $array['login'];
$_SESSION['coins'] = $array['coins'];
$_SESSION['isadmin'] = $array['isadmin'];
$_SESSION['pscadmin'] = $array['pscadmin'];
$_SESSION['email'] = $array['email'];
$_SESSION['real_name'] = $array['real_name'];
$_SESSION['social_id'] = $array['social_id'];
$_SESSION['user_admin'] = $array['web_admin'];
$_SESSION['user_id'] = $array['id'];
$_SESSION['user_name'] = $array['login'];
$_SESSION['user_coins'] = $array['coins'];
$_SESSION['user_email'] = $array['email'];
echo "<meta http-equiv='refresh' content='0; URL=index.php?s=home'>";
} else {
echo "<meta http-equiv='refresh' content='0; URL=index.php?s=login_error'>";
}
}
?>
And i wanna restrict acces on some page , you must login to intro in that page somting like this:
<?php
if(isset($_SESSION['user']) && isset($_SESSION['pass']))
{
auto_unban();
$username = $_SESSION['user'];
$sql = mysql_query("Select * from account.account where login='".$_SESSION['user']."'") or die(mysql_error());
$accc=mysql_fetch_object($sql);
$charss = mysql_query("Select * from player.player where account_id='".$accc->id."'") or die(mysql_error());
$chars = mysql_num_rows($charss);
?>
<script type='text/javascript'>
function myFunction()
{
var jmsg = "<? echo "Blocked : ".$acc->unban_date." pentru ".$acc->motiv_ban.".mlock."; ?>";
if(jmsg){
alert(jmsg);
}
window.onload=myFunction;
}
</script>
Script , script
<?php } else { echo "Please login!";} ?>
That script when i don't login show me this echo : Please login!
and when i'm login also show me that echo : Plase login!
I don't know how to create and read function in php can anyone show me how to make function like this :
if(isset($_SESSION['user']) && isset($_SESSION['pass']))

Your variable $_SESSION['login'] is empty because you forgot to call session_start(); at the beginning of your php script.
Place session_start(); before printing any chars on your page.
ex:
<?php session_start();
$_SESSION['login'] = 'login';
...

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.

Change text upon redirect from certain page...?

As the title suggests I am trying to use the same .php page and have it display something new upon being redirected from a particular location.
In context...
I have a login which upon successful login redirects to a home page but if unsuccessful, redirects to the index. Is there a way that I can tell my index page to display an "Error logging in" message when it has been redirected from my login page?
Here is my login code...
<?php
session_start();
include('conn.php');
$query = "SELECT * FROM User";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
if (isset($_POST["submit"])) {
$logEmail = $conn->real_escape_string($_POST['logEmail']);
$logPass = $conn->real_escape_string($_POST['logPass']);
$checkuser = "SELECT * FROM User WHERE Email='$logEmail' AND UserPassword=AES_ENCRYPT('$logPass', 'MyKey')";
$userresult = mysqli_query($conn, $checkuser) or die(mysqli_error($conn));
$loginsucc = (mysqli_num_rows($userresult) > 0);
if (mysqli_num_rows($userresult) > 0) {
while ($row = mysqli_fetch_assoc($userresult)) {
$userPriKey = $row['UserID'];
$userid = $row['Email'];
$accounttype = $row['IsAdmin'];
$firstname = $row['FirstName'];
$surname = $row['LastName'];
$_SESSION['userPriKey'] = $userPriKey;
$_SESSION['name'] = $firstname;
$_SESSION['surname'] = $surname;
$_SESSION['Email'] = $userid;
$_SESSION['IsAdmin'] = $accounttype;
if($accounttype == '1'){
header("Location: home.php");
}else if ($accounttype == '0'||$accounttype == NULL ) {
header("Location: userhome.php");
}
}
} else {
header("Location: index.php");
}
}
?>
Before you call header() set a session variable like so
$_SESSION['msg'] = 'success you are logged in';
header('Location: page.php');
exit;
Then in page.php,
session_start();
if (isset($_SESSION['msg'])) {
echo $_SESSION['msg'];
unset($_SESSION['msg']);
}
Also FYI, you should be using prepared statements. Your code is not totally safe

why session variable is empty to navigate the next page?

I have been working is a website I have been dealing with a problem from a while, and now I know why it is happening, but not how to solve it. Please help!!
Page 1:
In the first page, login page set the $_SESSION['user_id'] is stored the value that are fetch in database user id. In same page can print session and it work properly(the $_SESSION['user_id'] is print) and also navigate the next page(user home).
page 2:
In page 2(user home) the $_SESSION['user_id'] is turned into null value why this happen?
most probably see this problem in, forgot to set the session start but I was set session start both page...
page 1
<?php
if (isset($_POST['sub'])) {
$user = $_POST['user'];
$pass = $_POST['pass'];
$con = mysqli_connect("localhost", "root", "");
$db = mysqli_select_db($con, "Database");
$qry = "select * from TABLE where username='$user' and password='$pass'";
$res = mysqli_query($con, $qry) or die("could not connect to mysql");
$row = mysqli_fetch_array($res);
$len = mysqli_num_rows($res);
if ($len <= 0) {
echo "<script>";
echo "alert('Oops.Username Or Password Incorrect!');window.location.href='login.php';";
echo "</script>";
} else {
session_start();
$_SESSION['id'] = $row['id'];
$_SESSION['message'] = $user;
$_SESSION['logout'] = "";
$id = $_SESSION['id'];
echo "<script>";
echo "alert('log in Success $id ');window.location.href='login.php';"; //$id is print correctly
echo "</script>";
}
}
?>
page 2
<?php
ob_start();
session_start();
if (isset($_SESSION['id'])) {
$id = $_SESSION['id'];
echo "$user"; // not printed
}
if (isset($_SESSION['message'])) {
$msg = $_SESSION['message'];
$_SESSION['message'] = "";
}
if (isset($_SESSION['logout'])) {
$msg = $_SESSION['logout'];
if ($msg == 'logout') {
header("location:login.php");
$_SESSION['message'] = "you must login first";
exit(0);
}
}
?>
<?php
echo "welcome"; // only print this string the above session are not work
?>
I also use this code before some project and it work correctly then why this time the session value not working?
use session in the start in first page, like this. Hopefully this will work
<?php
session_start();
if (isset($_POST['sub']))
{
$user=$_POST['user'];
$pass=$_POST['pass'];
$con=mysqli_connect("localhost","root","");
$db=mysqli_select_db($con,"Database");
$qry="select * from TABLE where username='$user' and password='$pass'";
$res=mysqli_query($con,$qry)or die("could not connect to mysql");
$row=mysqli_fetch_array($res);
$len=mysqli_num_rows($res);
if($len<=0)
{
echo"<script>";
echo"alert('Oops.Username Or Password Incorrect!');window.location.href='login.php';";
echo"</script>";
}
else
{
$_SESSION['id']=$row['id'];
$_SESSION['message']=$user;
$_SESSION['logout']="";
$id=$_SESSION['id'];
echo"<script>";
echo"alert('log in Success $id ');window.location.href='login.php';"; //$id is print correctly
echo"</script>";
}
}
?>

Session if else statement

I am trying to display the information A if login as user and information B if login as admin. The problem here is that, I am only able to execute the first if statement and the else statement which means I am able to login. However, it will never get into the else if statement. Can anyone help me, I am not sure what is the problem here.
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpassword = "";
$dbdatabase = "test";
$db = mysql_connect($dbhost, $dbuser, $dbpassword);
mysql_select_db($dbdatabase, $db);
?>
somewhere.php
<?php
if(!isset($_SESSION)){
session_start();
}
include("configuration.php");
?>
<html>
<body>
<?php
if (isset($_SESSION['SESS_EXIST']) == true && isset($_SESSION['SESS_TYPE']) == 'A' ){ ?>
//this is the user html information form
<?php }
else if (isset($_SESSION['SESS_EXIST']) == true && isset($_SESSION['SESS_TYPE1']) == 'B' ){ ?>
//this is the admin html information form
<?php } else { ?>
//ask user/admin to login html form
<form action ="login.php">
<button type="submit" name="login" class="btn-primary">Sign Up</button>
</form>
<?php } ?>
</body>
</html>
login.php
<?php
session_start();
require("configuration.php");
if(isset($_SESSION['SESS_EXIST']) == TRUE) {
header("Location: somewhere.php");
die();
}
$email = $_POST['Email'];
$pass = $_POST['Pass'];
$sql = "SELECT * FROM user WHERE Email='$email' and Pass ='$pass' " ;
$res = mysql_query($sql);
$rows = mysql_num_rows($res);
$sql1 = "SELECT * FROM admin WHERE Email='$email' and Pass ='$pass' " ;
$res1 = mysql_query($sql1);
$rows1 = mysql_num_rows($res1);
if($rows == 1)
{
$row = mysql_fetch_assoc($res);
$_SESSION['SESS_EMAIL'] = $row['Email'];
$_SESSION['SESS_NAME'] = $row['Name'];
$_SESSION['SESS_PASS'] = $row['Pass'];
$_SESSION['SESS_TYPE'] = 'A';
$_SESSION['SESS_LOGGED'] = 1;
header("Location: somewhere.php");
die();
}
else if($rows1 == 1)
{
$row1 = mysql_fetch_assoc($res1);
$_SESSION['SESS_EMAIL1'] = $row['Email'];
$_SESSION['SESS_NAME1'] = $row['Name'];
$_SESSION['SESS_PASS1'] = $row['Pass'];
$_SESSION['SESS_TYPE1'] = 'B';
$_SESSION['SESS_LOGGED'] = 1;
header("Location: somewhere.php");
die();
}
else {
echo '<script language = "javascript">';
echo 'alert("Fail login")';
echo '</script>';
echo "<script>window.location.assign('somewhere.php')</script>";
die();
}
?>
I think you don't reset your SESSION when you Logout. Try this:
Login.php
<?php
session_start();
require("configuration.php");
if(isset($_SESSION['SESS_EXIST']) == TRUE) {
header("Location: somewhere.php");
die();
}
session_unset();
$email = $_POST['Email'];
$pass = $_POST['Pass'];
$sql = "SELECT * FROM user WHERE Email='$email' and Pass ='$pass' " ;
$res = mysql_query($sql);
$rows = mysql_num_rows($res);
$sql1 = "SELECT * FROM admin WHERE Email='$email' and Pass ='$pass' " ;
$res1 = mysql_query($sql1);
$rows1 = mysql_num_rows($res1);
if($rows == 1)
{
$row = mysql_fetch_assoc($res);
$_SESSION['SESS_EMAIL'] = $row['Email'];
$_SESSION['SESS_NAME'] = $row['Name'];
$_SESSION['SESS_PASS'] = $row['Pass'];
$_SESSION['SESS_TYPE'] = 'A';
$_SESSION['SESS_LOGGED'] = 1;
header("Location: somewhere.php");
die();
}
else if($rows1 == 1)
{
$row1 = mysql_fetch_assoc($res1);
$_SESSION['SESS_EMAIL1'] = $row['Email'];
$_SESSION['SESS_NAME1'] = $row['Name'];
$_SESSION['SESS_PASS1'] = $row['Pass'];
$_SESSION['SESS_TYPE1'] = 'B';
$_SESSION['SESS_LOGGED'] = 1;
header("Location: somewhere.php");
die();
}
else {
echo '<script language = "javascript">';
echo 'alert("Fail login")';
echo '</script>';
echo "<script>window.location.assign('somewhere.php')</script>";
die();
}
?>
Your If-Statement is also no correct. As mentioned in other answers it should be like this:
somewhere.php Edit
<?php
if(!isset($_SESSION)){
session_start();
}
include("configuration.php");
?>
<html>
<body>
<?php
if(isset($_SESSION['SESS_EXIST'])){
if ($_SESSION['SESS_EXIST'] == true && $_SESSION['SESS_TYPE'] == 'A' ){
?> //this is the user html information form <?php
}
else if ($_SESSION['SESS_EXIST'] == true && $_SESSION['SESS_TYPE1'] == 'B' ){
?> //this is the admin html information form <?php
}
} else { ?> //ask user/admin to login html form
<form action ="login.php">
<button type="submit" name="login" class="btn-primary">Sign Up</button>
</form>
<?php
}
?>
</body>
</html>
Hi your condition never gets true
if (isset($_SESSION['SESS_TYPE']) && $_SESSION['SESS_TYPE'] == 'A') {
// your code here
}
`isset` — Determine if a `variable` is set and is not `NULL`. `Returns` `TRUE` if var exists and has value other than NULL, FALSE otherwise.

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.

Categories