Pulling data off of sql table with php using sessions - php

I'm trying to pull data off my sql table with php unique to the session's ID, however I only get the position that the user is in when I echo anything out!
<?php
include 'core/init.php';
$user_info = $_SESSION['user_id'];
?>
<html>....
<h1><?php echo $user_info['firstname'];?>&nbsp<?php echo $user_info['firstname'];?> </h1>
displays as:
5 5
if I log in with the fifth position in the database!

The reason why you are getting 5 is for this code:
<?php echo $user_info['firstname'];?>
is that $_SESSION['user_id'] 's value is 5. So after the assignment $user_info's value is 5. Now because the $_SESSION['user_id'] is not set to an array as your intention seems to be. The result is that $user_info is taken as a string and ['firstname'] evaluates to [0]. If you like, you can update the ID 5 to 54, etc. You will always get the first character of your ID.
To correct this, try changing the last 2 lines before the return in your user_data function to:
$data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `users` WHERE `user_id` = $user_id"));
$data = array_merge(array($user_id), $data);
return $data;
if (logged_in() === true) {
$user_data = user_data($_SESSION['user_id'], 'username', 'first_name', 'last_name', 'email');
$user_data = user_data($session_user_id, 'user_id', 'username', 'first_name', 'last_name', 'email');
}
to:
if (logged_in() === true) {
$user_data = user_data($_SESSION['user_id'], 'username', 'first_name', 'last_name', 'email');
$_SESSION['user_id'] = $user_data;
}

if (logged_in === true) {
should be
if (logged_in()) {

for me it seems like you forgot to update data in session.
lets say here:
if (logged_in() === true) {
$user_data = user_data($_SESSION['user_id'], 'username', 'first_name', 'last_name', 'email');
$user_data = user_data($session_user_id, 'user_id', 'username', 'first_name', 'last_name', 'email');
$_SESSION = array_merge($_SESSION, $user_data);
}
hope it helps you to resolve your problems.

What I see that your in this line
<h1><?php echo $user_info['firstname'];?>&nbsp<?php echo $user_info['firstname'];?> </h1>
you are using "firstname", whereas in database it is named as "first_name", see underscore
<h1><?php echo $user_info['first_name'];?>&nbsp<?php echo $user_info['first_name'];?> </h1>
Let me know if this solves or not as I too want to know its answer

May help you some changes in your code
function user_data($user_id) {
$data = array ();
$user_id = (int)$user_id;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
if ($func_num_args > 1) {
unset($func_get_args[0]);
$fields = '`'. implode('`, `', $func_get_args). '`';
echo '<br>'.
$que = "SELECT $fields FROM `users` WHERE `id` = $user_id";
$data = mysql_fetch_assoc(mysql_query($que));
print_r ($data);
return $data;
}
}
function logged_in() {
return (isset($_SESSION['id'])) ? true : false;
}
if (logged_in() === true) {
$user_data = user_data($_SESSION['user_id'], 'username', 'firstname', 'email');
//$user_data = user_data($session_user_id, 'user_id', 'username', 'firstname', 'email');
print_r($user_data);
}
echo
$user_info = $user_data;//$_SESSION['user_id'];
?>
<h1><?php echo $user_info['firstname'];?>&nbsp<?php echo $user_info['firstname'];?> </h1>

function user_data($data=array(),$whereData=array()) {
$str='';
if(isset($whereData) && is_array($whereData))
{
foreach($whereData as $key=>$val)
{
if($val!='')
if($str=='')
$str = $key." = '".$val."'";
else
$str .= " AND ".$key." = '".$val."'";
}
}
$condition =
$fields = implode(',' , $data);
if($str!=''){
$data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `users` WHERE $str"));
}
else
{
$data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `users` ));
}
return $data;
print_r ($data);
}
}
and
if (logged_in() === true) {
$data = array('username', 'first_name', 'last_name', 'email');
$where=array('user_id'=>$_SESSION['user_id'])
$_SESSION['data'] = user_data($data, $where);
}
and
<?php
include 'core/init.php';
$user_info = $_SESSION['data'];
?>
<html>....
<h1><?php echo $user_info['firstname'];?>&nbsp<?php echo $user_info['firstname'];?> </h1>

From experience of creating large code bases in PHP and when you expand the application you will find you are using more and more data all over the place from the users table. Also, the table should only really contain the most vital data that is comonly used and you do NOT want to be sending more than 1 or 2 queries to the users table per page hit as it can soon become a bottle neck. For this reason you are better storing all of the data data (move large fields to another table or fields rarely used). Then store the whole user record in a session which means any function, class etc can use it as it becomes a superglobal and you can trust it enough to use it throughout the entire application without needed to re-query the users table again and again.
I have written a working example (suing your db table structure) and commented it all throughout explaining why i have done it the way i have and some points you might want to consider.
//change from user_data() to get_user_data() so we know we are "getting" it, makes it a little clearer
function get_user_data($user_id) {
//protect agains sql injections
$user_id = mysql_real_escape_string($user_id);
//you should also be using mysqli or PDO, not the outdated mysql library - just check the php documentation if you don't believe me ;)
$result = mysql_query("SELECT * FROM `users` WHERE `id` = '{$user_id}' LIMIT 1");
//only if the previous query returned a result do we want to fetch an array from it
if ($result) {
return mysql_fetch_assoc($result);
}
//query didn't work (syntax error for example) so return blank array
return array();
}
//start and restore the session
session_start();
//if first page hit, set the user details element
if (isset($_SESSION['user_details']) == false) {
$_SESSION['user_details'] = array();
}
//if already logged in, refresh their user details incase there were any changes
if (isset($_SESSION['user_details']->user_id)) {
//refresh the user data
$_SESSION['user_details'] = get_user_data($_SESSION['user_details']->user_id);
}
//login
if (empty($_POST['id']) == false) {
$_POST['id'] = trim($_POST['id']);
if (is_numeric($_POST['id'])) {
$_SESSION['user_details'] = get_user_data($_POST['id']);
}
}
//logout
if (isset($_GET['logout'])) {
if ($_GET['logout'] == session_id()) {
$_SESSION['user_details'] = array();
}
}
//see if logged in so we know what to display
if (empty($_SESSION['user_details'])) {
//not logged in
print "<form method='post' action=''><label>User ID</label><input type='text' name='id' value='5' /><input type='submit' value='Login' /></form>";
} else {
//is logged in
print "<a href='?logout=" . rawurlencode(session_id()) . "'>logout</a>";
}
//proof that it works
print '<pre>';
print_r($_SESSION['user_details']);
print '</pre>';
P.S. Also you may want to start using LIMIT in your SQL queries as LIMIT 1 in the query above tells mysql that it can stop searching after it finds 1 result - and you should have an index on that column (preferably a primary index or unique index) to keep it lightening fast (or at least in the beginning anyway >< ).

Related

proper way to check if input "promo code" matches with a database column

I would like to ask, what will be the best way to code using SQL and PHP, on how to check if the input in a textfield matches with a value in an SQL column?
I only have three values in the table. my targets are:
retrieve (POST) the value of the input
check the whole column to see if any matches the "promo code" typed
the "tinyint" used value will turn to 1
echo or affect other database tables if conditions are met
pseudocode will be alright, I would just like the proper procedure.
UPDATE: I tried the solution from #Bitwise Creative, im not getting an echo to appear, which part did i do wrong? also, i got my db where the table is located using a variable.
<form method="get">
<input type="text" name="lux_code" placeholder="ENTER PROMO CODE" style="text-align:center;">
<input type="submit" class="full_width btn color-white mwc-orange-background-color" name="redeem" value="REDEEM">
</form>
<?php
$routePath = "../";
require_once($routePath . "_config/db.php");
$dbConfig = new config_db();
$db = $dbConfig->init();
if (isset($_POST['redeem']) && $_POST['redeem'] == 'REDEEM'){
if (isset($_POST['lux_code']) && $_POST['lux_code']) {
// Short-cutting the DB code for demonstration...
$rows = $db->query('SELECT * FROM promocode_3 WHERE coupon_code = ? AND used = ?', array($_POST['lux_code'], 0));
if (!$rows) {
// Code not found (however you want to handle that...)
echo 'Code not found.';
} else {
// Code found and marked as used in DB
$db->query('UPDATE promocode_3 SET used = ? WHERE coupon_code = ?', array(1, $_POST['lux_code']));
// Additional handling...
echo 'Code accepted!';
}
}
}
?>
Assuming coupon_code has a unique index... Something like:
<?php
if (isset($_POST['code']) && $_POST['code']) {
// Short-cutting the DB code for demonstration...
$rows = $db->query('SELECT * FROM coupons WHERE coupon_code = ? AND used = ?', array($_POST['code'], 0));
if (!$rows) {
// Code not found (however you want to handle that...)
echo 'Code not found.';
} else {
// Code found and marked as used in DB
$db->query('UPDATE coupons SET used = ? WHERE coupon_code = ?', array(1, $_POST['code']));
// Additional handling...
echo 'Code accepted!';
}
}
You can do like this-
$couponcode = $_POST['coupon'];
$sql = "update table_name set used = 1 where coupon_code = $couponcode && used = 0";
The best way is to retrieve all your unused coupon codes and then iterate over the collection and check if the posted value is a match.
I would write a function in my functions.php file as so:
function getCoupons() {
global $db;
try {
$stmt = $db->prepare("SELECT * FROM coupons WHERE `used` = 0");
$stmt->execute();
return $stmt->fetchall();
} catch (Exception $e) {
echo $e->getMessage();
}
}
I would then call the function and store the results into an array in my test.php file like so:
$coupons = getCoupons();
I would also need the posted value, I'll retrieve it like so:
$couponCode = $_POST['coupon'];
I would then iterate over the result set to check for a match in the same file:
$match = false;
foreach($coupons as $coupon){
if($coupon['coupon_code'] == $couponCode){ //check to see if posted value matches
$match = true;
$stmt2 = $db->prepare("UPDATE coupons SET used =
'1' WHERE p3id = :id");
$stmt2->execute(array(
':id'=>$coupon['id']
));
break;
}
}
if($match){
echo 'Coupon code exists!';
} else {
echo 'No Coupon code exists!';
}

PHP login using Array Not DB

As a practice, I am trying to create a script to log a user in using array.
So I have created a associate multidimensional array which holds 'user' and 'password',
The idea is to use this array to compare data entered by the user through a HTML form.
The problem I am having is that, the password entered by the user is checked against all the password stored in array not the only one the password belongs to. So I am struggling with a logic to check the password entered by the user with the values stored in array, one by one and not as a whole.
My script:
<?php
$data = Array();
$data['email'] = $_POST['email'];
$data['pass'] = $_POST['pass'];
$data['passM'] = $_POST['passM'];
$users = Array(
'tomasz' => '123',
'mario' => 'abc',
);
if($_SERVER['REQUEST_METHOD']=='POST'){
$hello='';
foreach($users as $u => $p){
if($data['passM'] == $p){
header("Location: ../home.php");
}else{
echo "nooooo";
}
}
var_dump($users);
var_dump($data['email']);
var_dump($data['pass']);
var_dump($data['passM']);
}
Could anyone please suggest a solution?
Try This code, I hope you will find answer to your question.
$data = Array();
$data['email'] = $_POST['email'];
$data['pass'] = $_POST['pass'];
$data['passM'] = $_POST['passM'];
//var_dump($_POST);
$users = Array(
'tomasz' => '123',
'mario' => 'abc',
);
if($_SERVER['REQUEST_METHOD']=='POST'){
$hello='';
if(in_array($data['passM'],$users)){
echo "Found";
}else{
echo "nooooo";
}
}
Check the username first, then the pass for these user.
Right now I don't see any logic that provides any way of knowing what user to check against. If you knew what user was logging in you could check that the username of the array was the same as the username the form provided.
$data['user'] = $_POST['user'];
foreach($users as $u => $p){
if($u == $data['user']){
if($data['passM'] == $p){
header("Location: ../home.php");
}else{
echo "nooooo";
}
}
}
I assume you know which user tries to log in.
So, you could just check if this user exists and if the password is correct.
$data['user'] = $_POST['user'];
if(array_key_exists($data['user'], $users) && $data['passM'] == $users[$data['user']]) {
header("Location: ../home.php");
} else {
echo "nooooo";
}
Well Mr. Tomari in_array() method look for only value in array. if you have stored you email in array as value then no issue. if you have store 'email' as key and 'passm' as value of the that email then you have to use this code:
if($_SERVER['REQUEST_METHOD']=='POST'){
$hello='';
if(array_key_exists($data['email'],$users) && in_array($data['passM'],$users)){
echo "Found";
}else{
echo "nooooo";
}
}

How to make echo results in table hyperlinks

I have retrieved data from DB and inserted into a html table however I want to make each value in the table a hyperlink to another page. Below I have tried making the pupil_id and link to a profile.php but all pupil_id values have now vanished!
(if (!isset($_POST['search'])) {
$pupils = mysql_query("SELECT * FROM pupil") or die("Cant find Pupils");
$count = mysql_num_rows($pupils);
if ($count == 0) {
$totalpupil = "There are currently no Pupils in the system.";
} else {
while ($row = mysql_fetch_array($pupils)) {
?>
<tr>
<td><?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?></td>
<td><?php echo $row['pupil_name'] ?></td>
<td><?php echo $row['class_id'] ?></td>
</tr>
<?php
}
}
})
The finishing table should display every hyperlink as a hyperlink to another page. Any help?
Because your HTML is invalid, you are missing a closing > and you have no text defined for the hyperlink
<?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?> //Wrong
Correct would be
<?php echo ''.$row['pupil_id'].''; ?>
Try replace this:
<?php echo '<a href="profile.php?id=' .$row['pupil_id'] . '"</a>' ?>
with this:
<?php echo "<a href='profile.php?id=".$row['pupil_id']."'>link</a>"; ?>
Also, you dont have <table> tags at all.
You don't put any text between your link tags, text here
Maybe this will help you:
<td><?php echo ''.$row['pupil_name'].'' ?></td>
http://uk3.php.net/mysql_query
Watch out, which ever resource you are learning from may well be quite old. mysql_query is now deprecated.
http://uk3.php.net/manual/en/ref.pdo-mysql.php is a replacement.
Here is a kick starter to using PDO (this is much much safer) i write a while ago.
Include this file in which ever php script needs to access your db. An example file name would be 'database.php' but that is your call. Set the namespace from 'yourproject' to whatever your project is called. Correct the database credentials to suit your database
This will save you a lot of headaches hopefully!
I have given some example uses at the bottom for you. I remember when i started out getting clear advice was sometimes hard to come by.
//***** in a database class file*****/
namespace yourproject;
class Database {
private $db_con = '';
/*** Function to login to the database ***/
public function db_login()
{
// Try to connect
try{
// YOUR LOGIN DETAILS:
$db_hostname = 'localhost';
$db_database = 'yourdatabasename';
$db_username = 'yourdatabaseusername';
$db_password = 'yourdatabasepassword';
// Connect to the server and select database
$this->db_con = new \PDO("mysql:host=$db_hostname;dbname=$db_database",
"$db_username",
"$db_password",
array(\PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
// Prevent emulation of prepared statements for security
$this->db_con->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
$this->db_con->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return true;
}
// If it fails, send user to maintenance page
catch(PDOException $e)
{
header("location:http://yourwebsiteurl.com/maintenance.php");
exit();
}
}
/*** Function for database control ***/
public function db_control($query , $parameters, $returnID = false)
{
if(!is_array($query) && is_array($parameters))
{
try{
//prepare the statement
$statement = $this->db_con->prepare($query);
//execute the statement
$statement->execute($parameters);
//check whether this is a select, if it is then we need to retrieve the selected data
if(strpos($query, 'SELECT') !== false)
{
//fetch the results
$result = array();
while( $row = $statement->fetch(\PDO::FETCH_ASSOC) )
{
$result[] = $row;
}
//count the results
$count = count($result);
//return the array
return array( 'results' => $result, 'result_count' => $count );
}
//else return the number of affected rows
else{
//count the affected rows and place into a returnable array
$affected_rows = $statement->rowCount();
$returnArray = array('result_count' => $affected_rows);
//check to see if we are to return a newly inserted autoincrement ID from an INSERT
if($returnID)
{
//find the newly created ID and add this data to the return array
$insertID = $this->db_con->lastInsertId();
$returnArray['ID'] = $insertID;
}
return $returnArray;
}
}
catch(PDOException $e)
{
return false;
}
}
else{
return false;
}
}
}
// Start the database class and connect to the database then create a globally accessible function for ease of reference
$db = new \yourproject\Database();
$db->db_login();
function _db( $sql , $params , $returnID = false ){
return $GLOBALS['db']->db_control( $sql , $params , $returnID );
}
When you include this file you now have a new function: _db(). As the function is global it can be called from within any class or std file. When called into a variable as demonstrated below will result in an array like this:
array(
'result_count' => 3,
'results' => array(
array(/*row 1*/),
array(/*row 2*/),
array(/*row 3*/),
.. etc etc
)
)
Now include your database file in your php script:
//call in the database file
require_once 'database.php';
//your query as in the op
$sql = 'SELECT * FROM pupil';
//your params for the query
$params = array();
//running the query and getting the results returned into a variable called $query
$query = _db($sql,$params);
//if no results
if( $query['result_count'] == 0 )
{
echo 'sorry no pupils in the system';
}
else
{
//looping through each result and printing into a html table row
for( $i = 0 ; $i < $query['result_count'] ; ++$i )
{
echo '<tr><td><a href="profile.php?id=' . $query['results'][$i]['pupil_id'] . '"</a></td>';
echo '<td>'. $query['results'][$i]['pupil_name'] . '</td>';
echo '<td>'. $query['results'][$i]['class_id'] . '</td></tr>';
}
}
Your original query but with some parameters passed through
//Passing parameters to the query
//your query
$sql = 'SELECT * FROM pupil WHERE pupil_id = :pupil_id AND class_id = :class_id';
//your params for the query
$params = array(
':pupil_id' => 12,
':class_id' => 17,
);
//running the query and getting the results returned into a variable called $query
$query = _db($sql,$params);
//deal with the results as normal...
If you set the 3rd param as true you can return the automatic id of the row just entered eg:
//where $sql is a query that will INSERT a row
$query = _db($sql,$params, true);

PHP Redirect Depending on users Column data in MySQL

I have created a login page with Facebook login API. And i have stored the users data (name, gender and etc) into MySQL database (except the column "gorg" in my table) when they are login.
Then, I'll redirect the users to "newgg.php" which is have two links "Giver" and
"Gatherer". So, users can choose either one of them.
My sample code:
<?php
session_start();
error_reporting(E_ALL);
include('src/sql_handler.php');
include('src/facebook_handler_core.php');
$new_fb = new facebook_handler_core;
$new_fb->run();
if (isset($_SESSION['gorg']) == "Gatherer") {
header('Location: map.php');
}
?>
My goal is to redirect them depending on the button they push for there FIRST time visiting the page, heres the button code
<form method="post" action="<?php echo $PHP_SELF;?>">
<input type="submit" class="button orange" name="Giver" value="Giver">
</form>
<form method="post" action="<?php echo $PHP_SELF;?>">
<input type="submit" class="button orange" name="Gatherer" value="Gatherer">
</form>
and now last but not least, IF they have already previously chosen their type of user it needs to just redirect them depending on what the 'gorg' column reads in the users table.
any ideas to why my codes not working properly?
just in case you need them, here are the sql_handlers
<?php
class MySQL_Con {
private $host = 'localhost',
$user = 'NUNURBSINESS',
$pass = 'ASKMEANDMAYBE',
$db = 'teknolog_fruitforest',
$_CON;
function MySQL_Con() {
$this->_CON = mysql_connect($this->host, $this->user, $this->pass);
if(!$this->_CON)
die(mysql_error());
else {
$select_db = mysql_select_db($this->db);
if(!$select_db)
die('Error Connecting To Database'.mysql_error());
}
}
function End_Con() {
mysql_close($this->_CON);
}
}
?>
and now the facebook_handler_core.php
<?php
class facebook_handler_core extends MySQL_Con {
public $session,$_INFO = array(),$U_INFO = array();
public function run() {
require('src/facebook.php');
$set_fb = new Facebook(array(
'appId' => 'MYAPPID',
'secret' => 'CANTTELLYOU',
'cookie' => true));
$this->session = $set_fb->getUser();
if($this->session != 0) {
$this->_INFO = $set_fb->api('/me');
if(!empty($this->_INFO))
$this->fb_session_handler();
}
}
function fb_session_handler() {
$SQL_CON = new MySQL_Con;
$SQL_CON->MySQL_Con();
$query = mysql_query("SELECT * FROM users WHERE oauth_provider = 'facebook' AND email = '" .mysql_real_escape_string($this->_INFO['email'])."'") or die(mysql_error());
if(mysql_num_rows($query) > 0) {
$this->U_INFO = mysql_fetch_array($query) or die(mysql_error());
} else {
$photolink = 'http://graph.facebook.com/'.$this->session.'/picture?type=square';
$query = mysql_query("INSERT INTO users(oauth_uid, oauth_provider, username, first_name, last_name, email, pic_square, gorg, gender)VALUES('".mysql_real_escape_string($this->session)."','facebook', '".mysql_real_escape_string($this->_INFO['name'])."', '".mysql_real_escape_string($this->_INFO['first_name'])."','".mysql_real_escape_string($this->_INFO['last_name'])."','".mysql_real_escape_string($this->_INFO['email'])."','".mysql_real_escape_string($photolink)."','null','".mysql_real_escape_string($this->_INFO['gender'])."')") or die(mysql_error());
$query = mysql_query("SELECT * FROM users WHERE email='".mysql_real_escape_string($this->_INFO['email'])."'") or die(mysql_error());
$this->U_INFO = mysql_fetch_array($query) or die(mysql_error());
}
$SQL_CON->End_Con();
$gorg = $this->U_INFO['gorg'];
if($gorg != null) {
$_SESSION['gorg'] = $gorg;
}
$_SESSION['email'] = $this->U_INFO['email'];
$_SESSION['image'] = $this->U_INFO['pic_square'];
$_SESSION['gender'] = $this->U_INFO['gender'];
if($gorg != null) {
if($gorg == 'Giver') {
//redirect to Giver
header('Location: picktreetype.php');
}
if($gorg == "Gatherer") {
//redirect to Gatherer
}
}
return true;
}
function update_user($param) {
$SQL_CON = new MySQL_Con;
$SQL_CON->MySQL_Con();
if($param == 'Giver')
$query = mysql_query("UPDATE users SET gorg='".mysql_real_escape_string($param)."', FF_Points='100' WHERE email='".mysql_real_escape_string($_SESSION['email'])."'") or die(mysql_error());
if($param == 'Gatherer')
$query = mysql_query("UPDATE users SET gorg='".mysql_real_escape_string($param)."', FF_Points='30' WHERE email='".mysql_real_escape_string($_SESSION['email'])."'") or die(mysql_error());
$SQL_CON->End_Con();
if(!$query)
return false;
else
return true;
}
}
?>
Thanks in advance, i just cant get enough out of this site when it comes to gaining help and proper guidance i really appreciate all the help anyone has ever given me in the past.
The problem is you're doing
isset($_SESSION['gorg']) == "Gatherer"
as isset() returns a boolean result which, using ==, will match any non-explicitly-false value. You would have had direct evidence of the problem if you would have used === (identity comparison operator).
So, in your case, "Gatherer" is evaluated as non-FALSE, aka TRUE.
Every time.
You shouldn't use this kind of comparison; instead try:
isset($_SESSION['gorg']) && $_SESSION['gorg'] == "Gatherer"
if you wish to keep checking whether gorg is set before doing any other evaluation.

How set a session after user has logged in with his Facebook account?

I'm working on a website and I quite new to php and programming in general. I managed to log in the user and I can access my user data from anywhere in my webpage with this:
if (logged_in() === true){
global $user_data;
$session_user_id = $_SESSION['user_id'];
$user_data = user_data($session_user_id,'username', 'id', 'password', 'first_name', 'last_name', 'email', 'imagename');
if (user_active($user_data['username']) === false) {
session_destroy();
header ('Location: logout.php' );
}
}
$errors = array();
?>
Hope it's clear so far. Now I also managed to register my user using his Facebook account.
fbfunctions.php:
require 'include.php';
function retrieve_fields($sf) {
return json_encode($sf);
}
function verify_fields($f,$sf) {
$fields = json_encode($sf);
return (strcmp($fields,$f) === 0);
}
function register_fbuser($resp) {
extract($resp["registration"],EXTR_PREFIX_ALL, "fb");
// prepare values
$fb_id = mysql_real_escape_string($resp["user_id"]);
$fb_birthday = date("Y-m-d" , strtotime($fb_birthday));
$fb_name = mysql_real_escape_string($fb_name);
$fb_first_name = mysql_real_escape_string($fb_first_name);
$fb_last_name = mysql_real_escape_string($fb_last_name);
$fb_username = mysql_real_escape_string($fb_username);
$fb_location = mysql_real_escape_string($fb_location["name"]);
$query_str = "INSERT INTO users(oauth_provider, oauth_uid, username, first_name, last_name, gender, birthday, location , email, imagename) VALUES ('facebook','$fb_id','$fb_name','$fb_first_name','$fb_last_name','$fb_gender', '$fb_birthday', '$fb_location','$fb_email','". $fb_id .".jpg')" or die(mysql_error());
mysql_query($query_str);
$imageData = file_get_contents("https://graph.facebook.com/" . $fb_id ."/picture");
file_put_contents("upload_img/" . $fb_id . ".jpg", $imageData);
}
function check_registration($fb, $fb_fields) {
if ($_REQUEST) {
$response = $fb->getSignedRequest();
if ($response && isset($response["registration_metadata"]["fields"])) {
$verified = verify_fields($response["registration_metadata"]["fields"], $fb_fields);
if (!$verified) { // fields don't match!
header("location: bad.php");
} else { // we verifieds the fields, insert the Data to the DB
$GLOBALS['congratulations'] = TRUE;
register_fbuser($response);
}
}
}
}
So now i have all my user data in the sql database and the user picture in a folder. I want to access the user data using for instance user_data['first_name'] instead of using Facebook graph api user_profile['first_name'] since I have already fetched all I need from Facebook.
Is there a way to verify if the user as logged in with Facebook and then set the session so I can simply use my functionlogged_in()?
I know that is a lot of code to go through and you may get lost in translation but I'm really confused.

Categories