How to get $_SESSION['id'] from a session - php

Hello I have 2 tables in my database one for courses and one for users, each of them has an id column.
I am trying to create a relationship between them, one user subscribe to one course. The result I am trying to store inside a 3rd table called subscription, which has a column for the course ID and column for user id.
The users are registering after passing log-in which is connected with a new session. After user click subscribe link which is
<a href='subscribe.php?id=".$row['id']."'>subscribe!</a>
they are taken to the backend php page where it is the inserted into database information:
<?php
session_start();
?>
$userid = $_SESSION['userID'];
$cursoid = $_GET['id'];
mysql_connect("localhost", "username", "password") or die(mysql_error()) ;
mysql_select_db("test") or die(mysql_error()) ;
mysql_query("INSERT INTO `subscriptions`
(curso_id, user_id)
VALUES ('$cursoid', '$userid ')")
or die(mysql_error());
at this point I have obtained the id of the course and it is inserted inside it, the problem is for the user ID I am not getting anything. How I can get the id for the current logged in user ?
here is the code of my class for the login function:
public function userLogin() {
$success = false;
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();
$valid = $stmt->fetchColumn();
if( $valid ) {
$success = true;
}
$con = null;
return $success;
}catch (PDOException $e) {
echo $e->getMessage();
return $success;
$user = $stmt->fetchObj();
if( $user->user_id > 0 ) {
$success = true;
// User has been successfully verified, lets sessionize his user id so we can refer to later
$_SESSION['userID'] = $user->user_id;}
}
}
and finally here is the code of the login function:
session_start();
$usr = new Users;
$usr->storeFormValues( $_POST );
if( $usr->userLogin() ) {
header( 'Location: cursos.php' ) ;
$_SESSION["loggedIn"] = true;
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$_SESSION['id'] = $_POST['id'];

You should NOT be using sessionIds as userIds, instead you should be using the primary key of the user table after you have inserted the user row. Also, probably being pedantic, but you should rename your user variable to $user, $usr makes me wince.
Another way to get session id is: session_id
-- Edit --
public function userLogin() {
....
$user = $stmt->fetchObj();
if( $user->user_id > 0 ) {
$success = true;
// User has been successfully verified, lets sessionize his user id so we can refer to later
$_SESSION['userId'] = $user->user_id;
}
}
// We sessionized user id after validation, so we now have access to it
$userid = $_SESSION['userId'];
// Using straight mysql api is frowned upon, this should be converted to PDO before production use
mysql_query("INSERT INTO `subscriptions` (curso_id, user_id) VALUES ('$cursoid', '$userid ')")
or die(mysql_error());

Every time you want to work with a session, you must call session_start function at the beginning of the file. You called it in login function, but don't call in subscribe.php. Try this:
session_start();
$userid = $_SESSION['id'];
$cursoid = $_GET['id'];
//rest of the code

Also you have a minor error here as well, you had a space in this line VALUES ('$cursoid', '$userid ')")
mysql_query("INSERT INTO `subscriptions`
(curso_id, user_id)
VALUES ('$cursoid', '$userid')")
or die(mysql_error());

Related

Problems php and MySQL

I have 2 tables, user log that is where the people make a register with their email and password, and another table with the name user where the people make complete their own profile.
How can I make with an SQL query to insert the data that insert in the form?
Taking into account that table user makes reference with table user log with the id...
I mean
User log
Id
Email
Password
User
Id
User_id fk id reference userlog(id)
Name
Surname
This is the code wich i made the log in
<?php
session_start();
if (isset($_SESSION['usuario'])) {
header('Location: index.php');
}
$errores = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$email = filter_var(strtolower($_POST['email']), FILTER_SANITIZE_STRING);
$password = $_POST['password'];
$password = hash('sha512', $password);
try {
$conexion = new PDO('mysql:host=localhost;dbname=DATABASE, 'USER', 'PASS');
} catch (PDOException $e) {
echo "Error:" . $e->getMessage();;
}
$statement = $conexion->prepare('
SELECT * FROM userlog WHERE email = :email AND password = :password'
);
$statement->execute(array(
':email' => $email,
':password' => $password
));
$resultado = $statement->fetch();
if ($resultado !== false) {
$_SESSION['usuario'] = $resultado;
header('Location: index.php');
} else {
$errores .= '<li>Datos Incorrectos</li>';
}
}
I make a var_dump() to see what the array in $resultado bring, and it brign me the data of the table, but, when I want to use the data to fill an input it fails
If your data will be coming from POST method, please always use precautions to avoid SQL injection..
I will be using a very elementary example. You can enhance this one for your own use.
$servername = "localhost";
$username = "yourUser";
$password = "yourPass";
$dbname = "youtDB";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$sql = "INSERT INTO Userlog (email, password)
VALUES ('some_email#example.com', 'some_safe_password')";
$conn->exec($sql);
$last_id = $conn->lastInsertId();
$userSql = "INSERT INTO Userlog (userId, name, lastName) VALUES ($last_id, 'some_name', 'some_lastName')";
$conn->exec($userSql);
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
You can pass your data by using post method.
try this code.
$sql = "INSERT INTO users (Userlog, Id, Email, Password)
VALUES ('".$_POST["Userlog"]."','".$_POST["Id"]."','".$_POST["Email"].",'".$_POST["Password"]."')";

Using a variable to direct traffic

I am mostly sure that my error is with the variable not being gotten from the table. However I can not see the error I am asking for that data at the same time I am asking for the username and password. The table consists of [username],[password],[company]. The goal is to have the user get directed based on the name in company after the username and password have been verified. I keep getting the echo at the end.
Here is the code
function RegisterUser($usename, $password, $company)
{
// hash the pwd
$hpwd = hash('sha256',$password);
$q ='insert into users values(username, password, company) values(?,?,?)';
$stmt = PDO::prepare($q);
$stmt->exectue(array( $username, $hpwd, $company));
}
// validate user and return the company if successfull
function ValidateUser($username, $password, &$company)
{
$hpwd = hash('sha256',$password);
$q ='select company from users where username=? AND password=?';
$stmt = PDO::prepare($q);
$stmt->exectue(array( $username, $hpwd));
if( ($company = $stmt->fetch(PDO::FETCH_COLUMN)) === false )
{
$company = header( 'Location: login.php' );
}
elseif($company == "monkeynones"){
header( 'Location: admin1.php' );
}
Your query is wrong:
$sql = "SELECT 'password' and 'company' from users where 'username' = '$username';";
should be
$sql = "SELECT `password`, `company` from `users` where `username` = '$username'";
Use backticks, not quotes, around identifiers. and is replaced by a comma, and the trailing semicolon in the query isn't required.
It is so important that new programmers learn to do username/password authentication properly I felt it necessary to write this longer post.
Firstly, as eicto pointed out, the mysql extension is both deprecated and should really not even be used ever.
So to the metal.
visit php.net and learn about PDO
Never store unencoded passwords.
here is what you should do:
set up PDO:
// you need to store $link somewhere. in a class preferrably
function InitPDO(&$link)
{
// havet the database handle all strings as UTF-8.
$options = array('PDO::MYSQL_ATTR_INIT_COMMAND' => 'set names utf8');
$link = new PDO ( 'mysql:host='.$config['dsn_host'].';dbname='.$config['dsn_db'], $config['username'], $config['password'], $options ) ;
// If there is an error executing database queries, have PDO to throw an exception.
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$link->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
upon registration of user.
function RegisterUser($username, $password, $company)
{
// hash the pwd
$hpwd = hash('sha256',$password);
$q ='insert into users values(username, password, company) values(?,?,?)';
$stmt = $link->prepare($q);
$stmt->execute(array( $username, $hpwd, $company));
}
// validate user and return the company if successfull
function ValidateUser($username, $password, &$company)
{
$hpwd = hash('sha256',$password);
$q ='select company from users where username=? AND password=?';
$stmt = $link->prepare($q);
$stmt->execute(array( $username, $hpwd));
if( ($company = $stmt->fetch(PDO::FETCH_COLUMN)) === false )
{
$company = 'invalid'; // because user auth failed';
}
//else all is good
}
example test usage.
// assumes there is a 'login.php' and a 'invalid.php' file
$link = null;
InitPDO( $link );
RegisterUser('tester','password','login');
VerifyUser('tester','password', $redir );
if( file_exists( $redir . '.php' ) )
{
header( 'Location: '. $redir . '.php' );
exit;
}
echo 'error. no valid page found to fullfill query';

Set userid into the session array how?

Hello I am posting maybe 4th question about this issue but nobody can help me so far, so let's start from the begining, what I need is simple I need to: Set userID variable from column name "userID' inside table named "users" into the Sessions array: $_SESSION['userID']
here is my login page code:
<?php
session_start();
include_once("config.php"); //include the settings/configuration
?>
<?php if( !(isset( $_POST['login'] ) ) ) { ?>
<?php
//else look at the database and see if he entered the correct details
} else {
session_start();
$usr = new Users;
$usr->storeFormValues( $_POST );
if( $usr->userLogin() ) {
header( 'Location: cursos.php' ) ;
$_SESSION["loggedIn"] = true;
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
and here is my user class which operates the function login:
public function userLogin() {
$success = false;
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT * FROM users WHERE username = :username AND password = :password LIMIT 1";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();
$result = $sth->fetch(PDO::FETCH_ASSOC);
$success = true;
if ($result!==false) { // Check there is a match
$_SESSION['userID']= $result['userID'];
}
$success = true;
$con = null;
return $success;
}catch (PDOException $e) {
echo $e->getMessage();
return $success;
The code is working fine I just want to add addition to it which will get the userID value from the column of the users table inside the database ans store it to the $_SESSION['userID'] after user is loged in.
So any idea how to reach this goal in my code ? thanks!
If you just want the UserID from the table, you're going to have to do a $stmt->fetch() to load it first, then you can store it in your SESSION.
So after the execute in function userLogin() do:
$result = $stmt->fetch(PDO::FETCH_ASSOC);
If the user was found $result will then contain all of the fields from the users table. So:
if ($result!==false) { // Check there is a match
$_SESSION['userID']= $result['userID'];
}

Login redirecting to specific page based on user name

I'm in the process of learning PHP and MySQL.
I would like from the script to recognize a specific name and redirect it to admin.php. For example "if Username is Brian redirect him to admin.php, if the username is everything except Brian, redirect him to account.php".
Both Brian and the other persons must be registered in the database to be able to login. I thought on redirect based on MySQL user id, but I don't know how to write the code. Or if you know another simple solution.
Here is the script:
<?php
class Users {
public $username = null;
public $password = null;
public $salt = "";
public function __construct( $data = array() ) {
if( isset( $data['username'] ) ) $this->username = stripslashes( strip_tags( $data['username'] ) );
if( isset( $data['password'] ) ) $this->password = stripslashes( strip_tags( $data['password'] ) );
}
public function storeFormValues( $params ) {
//store the parameters
$this->__construct( $params );
}
public function userLogin() {
$success = false;
try{
$con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "SELECT userID FROM users WHERE username='username' AND password= :password AND userTypeId = 1 LIMIT 1";
$stmt = $con->prepare( $sql );
$stmt->bindValue( "username", $this->username, PDO::PARAM_STR );
$stmt->bindValue( "password", hash("sha256", $this->password . $this->salt), PDO::PARAM_STR );
$stmt->execute();
$valid = $stmt->fetchColumn();
if( $valid ) {
$success = true;
}
$con = null;
return $success;
}catch (PDOException $e) {
echo $e->getMessage();
return $success;
}
}
And this is the script from index.php (where the user writes his name and password)
<?php
} else {
$usr = new Users;
$usr->storeFormValues( $_POST );
if( $usr->userLogin() ) {
echo "Welcome";
} else {
echo "Incorrect Username/Password";
}
}
?>
Rather than recognizing a name (which you would have to parse) I believe it would be more efficient (and easier to implement) if you instead direct by user number (or whatever you're calling your primary key).
So if your user name is "Brian" and is the first user, with user number 1 then point to your table where the 1 is located, assuming it's stored as the integer 1 and not the string "1" instead.
Computers generally have an easier time dealing with integers rather than arrays. You can do it by string, but it's always going to be more work for you and the machine.
As far as redirecting goes, upon logging in, just do a check:
if user number is equal to [Brian's user number] then redirect to admin.php
else redirect to account.php
(Also you'll want to make sure that admin.php requires Brian be the logged in user, or anybody else could just navigate there manually)
The method $user->userLogin should return the id of current login user when successful login and return FALSE when failure login . then redirect to a admin.php or or account.php depend the returned id
First, try to fetch username and correct binding name for username:
$sql = "SELECT username FROM users WHERE username = :username AND ...
instead of:
$sql = "SELECT userID FROM users WHERE username='username' AND ...
//^ //^
Also just return fetched username on successful status. It returns a single column from the next row of a result set or FALSE if there are no more rows.
return $stmt->fetchColumn();
And then check logged in username by if condition to redirect desired page:
$usr = new Users;
$usr->storeFormValues( $_POST );
$username = $usr->userLogin();
if( $username !== false ) {
if(strtolower($username) == "brian"){
header("Location: admin.php");
} else {
header("Location: account.php");
}
} else {
echo "Incorrect Username/Password";
}

Retrieve data from mysql database

I have made a database with columns Email, FirstName, LastName, Password.. etc
My login page uses email and password for logging in
I want to retrieve the name typed in LastName column in the same row as Email
I would like to know how to do so
My code looks like this:-
$query=mysql_query("SELECT * FROM Users WHERE email='$email' AND
`password`='$encrypted_pass' ");
After this, I want to be able to assign a variable to the LastName so I could create a session along with login
Then you specify the column in the column list:
SELECT LastName
FROM Users
WHERE email = '$email'
...
You then need fetch the result set to assign it to a variable.
mysql_ functions are officially deprecated and no longer maintained/safe to use.
You should use PHP's PDO instead as it is a safer and more object-oriented approach.
Just fill in DB_NAME, DB_USER_NAME, and DB_USER_PASS with your specific credentials and this code should work for you.
$database = new PDO( 'mysql:host=localhost;dbname=DB_NAME;charset=UTF-8', 'DB_USER_NAME', 'DB_USER_PASS' );
$query = $database->prepare( "SELECT * FROM Users WHERE `email` = ? AND `password` = ? " );
$query->bindValue( 1, $email );
$query->bindValue( 2, $encrypted_pass );
$query->execute();
if( $query->rowCount() > 0 ) { # If rows are found for query
$result = $query->fetch( PDO::FETCH_ASSOC );
echo $result[ 'LastName' ]; # <-- The LastName field you were looking for!
}
else { echo "No Rows Returned!"; }
For more information of PHP PDO, please see http://www.php.net/manual/en/book.pdo.php
I think this covers everything you asked for. Starts a session, checks if it is good, setup a couple of variables for our post data, do some data validation, setup the query, query the db, check results, set var lastname in session.
<?php
header('Content-type: text/html');
session_start();
if (session_id() === '') {
echo 'session_id is null!';
exit;
}
$myemail = null;
$mypassword = null;
if (isset($_POST['Submit']) == true) {
//assuming you have a db connection
//mysql_connect($host, $user, $password) || die(mysql_error());
//mysql_select_db($database) || die(mysql_error());
if ((isset($_POST["username"]) === false)||
(isset($_POST["password"]) === false)) {
echo 'Please fill in all fields';
exit;
} else {
// get the post data
$myemail = ($_POST["username"]);
$mypassword = ($_POST["password"]);
}
// check the form in database
$sql = "SELECT * FROM Users WHERE email = '".$myemail."'
AND password = '".$mypassword."'";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$_SESSION['loggedin'] = false;
if ($count === 1) {
$userrecord = mysql_fetch_array($result);
$_SESSION['username'] = $userrecord['username'];
$_SESSION['password'] = $userrecord['password'];
$_SESSION['loggedin'] = true;
$_SESSION['lastname'] = $userrecord['lastname'];
// assign last name to a session var
echo 'You have been logged in successfully";
} else {
echo 'Wrong username or password';
exit;
}
} else {
echo "No form post detected.<br><br>";
}
?>
Here's some basic stuff using Mysqli since mysql_ commands are deprecated. Again, it uses some common names so adjust accordingly.
/********************************/
// using mysqli (untested but should work)
/********************************/
$mysqli = new mysqli("localhost", "dbuser", "dbpassword", "default_dbname");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
// ecsape the query params
$myemail = $mysqli->real_escape_string($myemail);
$mypassword = $mysqli->real_escape_string($mypassword);
if ($mysqli->query("SELECT * FROM Users WHERE email = '$myemail'
AND password = '$mypassword'")) {
printf("%d Rows returned.\n", $mysqli->affected_rows);
// here is where you can set the $_SESSION vars
// and do any other work you want to do on login.
}
$mysqli->close();
/********************************/
//end mysqli
/********************************/
One last thing. Get yourself a GitHub.com repository setup so you can easily rollback to a prior version. It really is a must have IMO.

Categories