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 */
Related
I have code, which should use access levels, but from the database my code is not requesting the access level and I do not get into my "admin.php"
Can you help?
Login page is here:
Login-Page
Credentials: test / test
I want to let users login into my page, which is access for recruiters of me. So I can create users, they see my CV and others. Therefor it is neccessary to set user levels like "1" for admin.php "2" for admin2.php and so on.
Here's the check.php which is a form from the index.php
<?php
session_start();
require_once("inc/config.inc.php");
require_once("inc/functions.inc.php");
$error_msg = "";
if(isset($_POST['uname']) && isset($_POST['pwd'])) {
$email = $_POST['uname'];
$passwort = $_POST['pwd'];
$statement = $pdo->prepare("SELECT * FROM users WHERE email = :uname");
$result = $statement->execute(array('uname' => $email));
$user = $statement->fetch();
//Überprüfung des Passworts
if ($user !== false && password_verify($passwort, $user['pwd'])) {
$_SESSION['userid'] = $user['id'];
$access_level = $user['access_level'];
$_SESSION['access_level'] = $access_level;
//Möchte der Nutzer angemeldet beleiben?
if(isset($_POST['angemeldet_bleiben'])) {
$identifier = random_string();
$securitytoken = random_string();
$insert = $pdo->prepare("INSERT INTO securitytokens (user_id, access_level, identifier, securitytoken) VALUES (:user_id, :access_level, :identifier, :securitytoken)");
$insert->execute(array('user_id' => $user['id'], 'access_level' => $access_level, 'identifier' => $identifier, 'securitytoken' => sha1($securitytoken)));
setcookie("identifier",$identifier,time()+(3600*24*365)); //Valid for 1 year
setcookie("securitytoken",$securitytoken,time()+(3600*24*365)); //Valid for 1 year
}
if ($access_level==0){
header("Location:user.php");
}
else if($access_level==1){
header("Location:admin.php");
}
}
else{
header("Location:index.php?err=1");
}
} else {
$error_msg = "E-Mail oder Passwort war ungültig<br><br>";
}
$email_value = "";
if(isset($_POST['email']))
$email_value = htmlentities($_POST['email']);
?>
The problem was here in line
<?php
$statement = $pdo->prepare("SELECT * FROM users WHERE email = :uname");
there's no table named "email" - so it's not possible to get a true request.
I changed it to:
<?php
$statement = $pdo->prepare("SELECT * FROM users WHERE uname = :uname");
After that, my page gives me the output:
Hello This is admin page.
Thanks at all of you for your help! :)
May be your mistake is here.
$access_level = ['access_level'];.
it should be like
$access_level = $user['access_level'];.
and I don't get your situation.
other mistake is may be here.
if(isset($_POST['angemeldet_bleiben'])) {
$identifier = random_string();
$securitytoken = random_string(); //remaining code....
}
else if ($access_level==0){
header("Location:user.php");
}
else if($access_level==1){
header("Location:admin.php");
}
don't you think it should be like.
if ($access_level==0){ //removed else.
header("Location:user.php");
}
else if($access_level==1){
header("Location:admin.php");
}
because if first if condition worked then it skips all other else if statements.
Did you check print_r($user)? What is returned? What datatype has your column "access_level" in your database?
Maybe you have to check $access_level=='0', if it is type string.
I have a two forms from one form. I can sucessfully store the data to database.when that form submitted user will directed to the second form. I am passing variable $uniqueid in the url from first form to second form. But, when I tried stored the data of the second form into the database that relevant to the same user its not stored.
I want to store mobile number of the user from second page.databse column also mobile number.
This is my code
<?php
include_once 'dbconnect.php';
$a = $_GET['uniquekey'];
if(isset($_POST['btn-signup']))
{
$mobilenumber = $_POST['mobilenumber'];
$xxx = mysql_query("SELECT * FROM who WHERE uniquekey = '$a'")or die(mysql_error());
$yyy = mysql_fetch_row($xxx);
if(mysql_num_rows($xxx) > 0) {
$aaa = mysql_query("INSERT INTO who(mobilenumber) VALUES('$mobilenumber')");
}
else{
echo 'wrong';
}
}
?>
$xxx = mysql_query("SELECT * FROM who WHERE uniquekey = '$a'")or die(mysql_error());
$yyy = mysql_fetch_row($xxx);
if(mysql_num_rows($xxx) > 0) {
$aaa = mysql_query("UPDATE who setmobilenumber='$mobilenumber' where uniquekey = '$a' ");
}
else{
echo 'wrong';
}
Here you can use update query for update user mobile number.
include_once 'dbconnect.php';
$a = $_GET['uniquekey'];
if(isset($_POST['btn-signup']))
{
$mobilenumber = $_POST['mobilenumber'];
$xxx = mysql_query("SELECT * FROM who WHERE uniquekey = '$a'")or die(mysql_error());
$yyy = mysql_fetch_row($xxx);
if($yy>0)
{
$update="update who set mobilenumber=$mobilenumber where uniquekey='$a'";
$query=mysql_query($update);
}
else
{
echo "wrong";
}
}
Here it's I have a problem with my PHP Code + Oracle Login form.
In this PHP file, I make login function. But I have an error like this :
Warning: oci_num_rows() expects parameter 1 to be resource, string given in C:\xampp\htdocs\developers\it\session.php on line 12
Wrong
-
<?php
session_start();
include ("config.php");
$username = $_POST['username'];
$password = $_POST['password'];
$do = $_GET['do'];
if($do=="login")
{
$cek = "SELECT PASSWORD, USER_LEVEL FROM T_USERS WHERE USERNAME='$username' AND PASSWORD='$password'";
$result = oci_parse($conn, $cek);
oci_execute($result);
if(oci_num_rows($cek)==1)
{
$c = oci_fetch_array($result);
$_SESSION['username'] = $c['username']; ociresult($c,"USERNAME");
$_SESSION['USER_LEVEL'] = $c['USER_LEVEL']; ociresult($c,"USER_LEVEL");
if($c['USER_LEVEL']=="ADMINISTRATOR")
{
header("location:supervisor.php");
}
else if($c['user_level']=="User")
{
header("location:user.php");
}
else if($c['user_level']=="Root")
{
header("location:administrator.php");
}
else if($c['user_level']=="Manager")
{
header("location:manager.php");
}
else if($c['user_level']=="Admin")
{
header("location:admin.php");
}
else if($c['user_level']=="Director")
{
header("location:director.php");
}
}
else
{
echo "Wrong";
}
}
?>
I have tried to search in google, but still don't find anything.
Someone knows, what's the problem ?
Thanks for advance.
According to your script instead of
if(oci_num_rows($cek)==1)
you should call
if(oci_num_rows($result)==1)
You probably want to use $result and not $cek when you're asking for the number of rows returned from oci_num_rows(). However, you really want to avoid using $username and $password directly in the string like that. It'll make you wide open for SQL injection attacks, so look into using oci_parse together with oci_bind_by_name.
After that you should also always call exit() after the sequence of redirects, as the script will continue running if you don't (and that might be a security issue other places).
I also got the same case, so I tricked it with a script like this, but I don't know whether there was an impact or not. because the session and validation went smoothly.
$username =$_POST['username'];
$password = $_POST['password'];
$conn = oci_connect('xxx', 'xxx', 'localhost/MYDB');
$pass_encription = md5($password);
$query = "SELECT * from *table_name* WHERE *field1*='".$username."' and *field2*='".$password."'";
$result = oci_parse($conn, $query);
oci_execute($result);
$exe = oci_fetch($result);
if ($exe > 0)
{
oci_close($conn);
oci_execute($result);
$row =oci_fetch_array($result);
$sid = $row['field_1_parameter'];
$snama = $row['field_2_parameter'];
$sjab = $row['field_3_parameter'];
$session = array (
'field_1_array' =>$sid,
'field_2_array' =>$snama,
'field_3_array' =>$sjab
);
if($sjab == 'Administrator')
{
$this->session->set_userdata($session);
redirect('redirecting_page');
}
`
Trying to add some extra elements to my session variables for filesystem directory work, and I noticed that I can't add some. Here's what I have:
<?php
#login.php
// This page processes the login form submission.
// Upon successful login, the user is redirected.
// Two included files are necessary.
// Check if the form has been submitted:
if(isset($_POST['submitted']))
{
// For processing the login:
require_once ('login_functions.php');
// Need the database connection:
require_once ('../mysqli_connect.php');
// Check the login:
list ($check, $data) = check_login($dbc, $_POST['email'], $_POST['pass']);
if ($check) //OK!
{
// set the session data:
session_start();
$_SESSION['user_id'] = $data['user_id'];
$_SESSION['first_name'] = $data['first_name'];
$_SESSION['company_name'] = $data['company_name'];
$_SESSION['email'] = $data['email'];
// Store the HTTP_USER_AGENT:
$_SESSION['agent'] = md5($_SERVER['HTTP_USER_AGENT']);
//Redirect:
$url = absolute_url ('loggedin.php');
header("Location: $url");
exit(); // Quit the script.
}
else // Unsuccessful!
{
// Assign $data to $errors for error reporting
// in the login_functions.php file.
$errors = $data;
}
mysqli_close($dbc); // Close the database connection
} //End of the main submit conditional
//Create the page:
include('login_page_inc.php');
?>
here are the login functions:
<?php #login_functions.php
//This page defines two functions used by the login/logout process.
/*This function determines and returns an absolute URL.
* It takes one argument: the page that concludes the URL.
* The argument defaults to index.php
*/
function absolute_url ($page = 'about.php')
{
//Start defining the URL...
//URL is http:// plus the host name plus the current directory:
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
// Remove any trailing slashes:
$url = rtrim($url, '/\\');
// Add the page:
$url .= '/' . $page;
// Return the URL:
return $url;
}//End of absolute_url() function.
/*This function validates the form data (email address and password).
* If both are present, the database is queried.
* The function requires a database connection
* The function returns an array of information, including:
* - a TRUE/FALSE variable indicating success
* - an array of either errors or the database result
*/
function check_login($dbc, $email = '', $pass = '')
{
$errors = array(); // Initialize error array.
// Validate the email address:
if (empty($email))
{
$errors[] = 'You forgot to enter your email address.';
}
else
{
$e = mysqli_real_escape_string($dbc, trim($email));
}
// Validate the password:
if (empty($pass))
{
$errors[] = 'You forgot to enter your password.';
}
else
{
$p = mysqli_real_escape_string($dbc, trim($pass));
}
if(empty($errors)) //If everything's OK.
{
// Retrieve the user_id and first_name for that email/password combo
$q = "SELECT user_id, first_name, email FROM
user WHERE email='$e' AND pass=SHA1('$p')";
$r = #mysqli_query ($dbc, $q); // Run the query.
//Check the result:
if (mysqli_num_rows($r)==1)
{
//Fetch the record:
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
// Return true and the record:
return array (true, $row);
}
else //Not a match for writer, check the publisher table
{
$q = "SELECT pub_id, company_name, cemail FROM
pub WHERE cemail='$e' AND password=SHA1('$p')";
$r = #mysqli_query ($dbc, $q);
if (mysqli_num_rows($r)==1)
{
//Fetch the record:
$row = mysqli_fetch_array($r, MYSQLI_ASSOC);
// Return true and the record:
return array (true, $row);
}
else
{
echo '<p>Invalid Credentials</p>';
}
}
} // End of empty($errors) IF.
// Return false and the errors:
return array(false, $errors);
} // End of check_login() function.
?>
Note: $_SESSION['first_name'] and $_SESSION['company_name'] have always worked correctly, however adding email and user_id is not working. Thanks in advance.
email and user_id will never work for the publisher: as the login function returns "pub_id" and "cemail". To fix this, you could change the SQL to:
$q = "SELECT pub_id as user_id, company_name, cemail AS email FROM
pub WHERE cemail='$e' AND password=SHA1('$p')";
I have the following function which retrives the currently logged in users' username and finds out their access level from the database (either 'requested','user', or 'admin')
function fetchAccess()
{
global $con;
$username = $_SESSION['username'];
$q = "SELECT access FROM users WHERE username = '$username' LIMIT 1";
$result = mysql_query($q, $con);
$row = mysql_fetch_assoc($result);
$access = $row['access'];
if(isset($_SESSION['username']))
{
if($access == 'user')
{
return 1; // Returns 1 if access level is user
}
elseif($access == 'admin')
{
return 2; // Returns 2 if access level is admin
}
elseif($access == 'requested')
{
return 3; // Returns 3 if access level is requested
}
}
}
When I am checking whether the user is an admin using the follow code, this works correctly.
/* Redirects user if access level does not equal admin */
$result = fetchAccess();
if($result != 2)
{
header("location:index.php");
}
However when I check to see whether the access is 'requested' - this following is NOT working correctly.
<?php
/* Redirects user if access level does is 'requested' */
$result = fetchAccess();
if($result == 3)
{
header("location:redirect.php");
}
?>
Does anyone know why this is?
You can do this:
function fetchAccess()
{
global $con;
$username = $_SESSION['username'];
$q = "SELECT access FROM users WHERE username = '$username' LIMIT 1";
$result = mysql_query($q, $con);
$row = mysql_fetch_assoc($result);
global $access
$access = $row['access'];
}
then:
global $access
if($access != admin){
header("location:redirect.php");
}
Have you verified that $result actually equal to 3? it may very well be that in the first instance $result == "" which is != 2 so it is not working at all. Try debugging it by including a header like:
<?php
$result = fetchAccess();
header("X-my-result: [$result]");
if ( $result == 3 ) {
header("Location: redirect.php");
}
?>
and see what you get back for value of $result in the headers.
do an echo statement to see what is return in the $result variable. btw, i'm not sure if your logic in your first redirect statement is to encompass both 'user' and 'requested', but those users will be redirected to index.php