PHP sdk - redirection error - php

I have a website in which I have the following files :-
index.php - homepage
f-login.php - page which redirects user to facebook to ask for permissions
add.php - which is given below - this page checks if the user is old or new. If the user is new, it redirects the page to username-choice.php or else it redirects the user to the main page after setting the required cookies.
username-choice.php - This page is for the NEW user to choose a username for himself. If the cookie - "tempuid" is set, it shows the correct page or else it shows an error page that "COOKIES ARE NOT ENABLED!"
The problem is that in the username-choice.php page the error message shows up. I cannot understand the problem. I have given my code for the add.php page. Please tell me what's wrong. Any help shall be appreciated.
The following is my add.php page :-
<?php
include "config.php"; /* contains mysqli_connect */
require "src/facebook.php"; /* for facebook login php-sdk */
include "app_details.php"; /* app-id and secret */
$user = $facebook->getUser();
if ($user) {
try {
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
error_log($e);/* ERROR TO BE DISPLAYED */
$user = null;
}
}
$uid=$user_profile['id'];
$email=$user_profile['email'];
$fullname = $user_profile['name'];
$birthday = $user_profile['birthday'];
if($uid==null){
echo "Sanp! Something went wrong";
}
$n=0;
$result = mysqli_query($con,"SELECT * FROM Users
WHERE UID='$uid'");
/* TO CHECK IF THE USER IS NEW OR OLD*/
while($row = mysqli_fetch_array($result))
{
$n++;
$username=$row['Username'];
$ppic=$row['Ppic_url'];
}
if($n>0)
{
$expire=time()+60*60*24*30;
setcookie("name" , "$fullname", $expire);
setcookie("uid" , "$uid", $expire);
setcookie("logintype", "facebook", $expire);
setcookie("username", "$username", $expire);
setcookie("ppic", "$ppic", $expire);
header("Location: http://mysite.com");
exit;
}
else if($n==0)
{
$expire=time()+60*60*24*30*365;
setcookie("tempname", "$fullname", $expire);
setcookie("tempuid" , "$uid", $expire);
setcookie("tempemail", "$email", $expire);
setcookie("tempbday", "$birthday", $expire);
setcookie("tempppic", "$ppic", $expire);
header("Location: http://mysite.com/username-choice");
exit();
mysqli_close($con);
}
?>

This means that the program is going into the last if statement. Now, your webpage can display "COOKIES NOT ENABLED" only if the uid is null. So, according to me the $uid is null.

Related

Code From Book Doesn't Log Me in Automatically PHP & MariaDB

I register my user, but when I log in after registration I'm told to log in again. Please help.
Here's my code:
<?php
// include function files for this application
require_once('bookmark_fns.php');
session_start();
//create short variable names
if (!isset($_POST['username'])) {
//if not isset -> set with dummy value
$_POST['username'] = " ";
}
$username = $_POST['username'];
if (!isset($_POST['passwd'])) {
//if not isset -> set with dummy value
$_POST['passwd'] = " ";
}
$passwd = $_POST['passwd'];
if ($username && $passwd) {
// they have just tried logging in
try {
login($username, $passwd);
// if they are in the database register the user id
$_SESSION['valid_user'] = $username;
}
catch(Exception $e) {
// unsuccessful login
do_html_header('Problem:');
echo 'You could not be logged in.<br>
You must be logged in to view this page.';
do_html_url('login.php', 'Login');
do_html_footer();
exit;
}
}
do_html_header('Home');
check_valid_user();
// get the bookmarks this user has saved
if ($url_array = get_user_urls($_SESSION['valid_user'])) {
display_user_urls($url_array);
}
// give menu of options
display_user_menu();
do_html_footer();
?>
I tried using this member.php code but it doesn't work the way I want it to. Please help me get the book example to work properly and log me in right after registration

How to fix "redirected you too many times."

I was created simple login and register system and have some issue. But not sure is it with cookie or cookie and php. My code is next:
On index.php ( login page i have this code in header ):
<?php
include('includes/config.php');
if(!$user->is_logged_in()){
header('Location: index.php');
exit;
}
if(isset($_POST['submit'])){
$username = $_POST['username'];
$password = $_POST['password'];
if($user->login($username,$password)){
$_SESSION['username'] = $username;
header('Location: home.php');
exit;
} else {
$error[] = 'Wrong username or password or your account has not been activated.';
}
}
?>
And on home page when user is successfully logged in:
<?php include('includes/config.php');
if(!$user->is_logged_in()){
header('Location: index.php');
exit;
}
?>
Config file:
<?php
ob_start();
session_start();
date_default_timezone_set('Europe/London');
define('DBHOST','localhost');
define('DBUSER','root');
define('DBPASS','pass');
define('DBNAME','db_name');
define('DIR','http://example.com/');
define('SITEEMAIL','noreply#domain.com');
try {
$db = new PDO("mysql:host=".DBHOST.";dbname=".DBNAME, DBUSER, DBPASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo '<p class="bg-danger">'.$e->getMessage().'</p>';
exit;
}
include('classes/user.php');
include('classes/phpmailer/mail.php');
$user = new User($db);
?>
Problem is next, when user successfully logged in and redirected to home page, when user is log out everything is fine, but when user logged in and without log out go back to index page ( log in page ) i get this error:
This page isn’t working website.com redirected you too many times. Try clearing your cookies. ERR_TOO_MANY_REDIRECTS
And when i clear my cookie from google chrome browser, error is fixed but user must login again and when same step do again i get again same error.
You should break this up into three scripts, with the following logic:
Home page (and all other content pages): If they're not logged in, it redirects to the login page.
Login page: If they're already logged in, redirect to the home page.
Password checker: This is the action of the login form on the login page. It checks the username and password. If they're correct, it sets the session variable that says that the user is logged in, and redirects to home page. If they're not correct, it redirects back to the login page.
Problem was on index page ( login page ):
OLD code
if( $user->is_logged_in()){
header('Location: index.php'); --> THIS IS WHERE PROBLEM IS
}
NEW code
if( $user->is_logged_in()){
header('Location: home.php'); // Work correctly
}

How to prevent php sessions getting wrong values?

I have a php site that some times when I load a page gets $_SESSION values from another user, but when I refresh the page it's all ok.
For example, I logged in as User A, navigate through the site and then in a page I get the session from User B. I refresh the page and get again the correct info from User A.
This is the file "db.php" that use with require_once in every file in my site. I put this at the very beginning of all my scripts:
<?php
if(!isset($_SESSION)){session_start();}
$mysqli = new mysqli("localhost", "", "", "");
if ($mysqli->connect_errno) {
echo "Error: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$mysqli->set_charset("utf8");
include("functions.php");
date_default_timezone_set('America/Mexico_City');
?>
Also I use a shared hosting, which has this values set:
session.gc_maxlifetime = 604800;
session.save_path = /var/cpanel/php/sessions/ea-php56;
I have a "header.php" required once in each page, that has this query to get and show the username of the current user. This is where I get noticed that something is wrong with the session, but I don't know why:
$query=sprintf("SELECT * FROM tblusers WHERE user=%s",$_SESSION['ADMINID']);
$info=$mysqli->query($query);
$c=$info->fetch_assoc();
The login is done in this way. cpass() is a function that crypts the pass to check it against the database. The login is done ok, and after some browsing I encounter the problem:
<?php
if(isset($_POST['user'])&&isset($_POST['pass'])){
$user=$mysqli->real_escape_string(trim($_POST['user']));
$pass=cpass($mysqli->real_escape_string(trim($_POST['pass'])));
$query=sprintf("SELECT * FROM tblusers WHERE user=%s AND pass='%s'",$user,$pass);
$check=$mysqli->query($query);
if($check->num_rows==1){
$r=$check->fetch_assoc();
$_SESSION['ADMINID']=$r['userid'];
session_regenerate_id(true);
header("Location: /");exit;
}
}
?>
The logout is handled this way:
<?php
if(!isset($_SESSION)){session_start();}
$_SESSION=array();
unset($_SESSION);
session_unset();
session_destroy();
if(isset($_GET['url'])){
header("Location: ".$_GET['url']);
}else{
header("Location: /");
}
?>
Thanks in advance!
Simple fix, when you have a login script that works, you can provide something like this at the end of it to give them a $SESSION tied in with their userID in your database.
Login.php
//login code
.....
//
//if successful
$_SESSION['user_id'] = $user['username'];
$_SESSION['logged_in'] = time();
header( "Location: /home.php" );
die();
And then at the top of your homepage ( I presume this is where you want an echo like you are logged in as 'user123'
home.php
<?php
session_start();
if(isset($_SESSION['user_id']) || isset($_SESSION['logged in'])){
echo 'whatever you want here'
?>

PHP redirect on login failure

SITUATION
I have made the following login form:
<?php
session_start();
session_regenerate_id(TRUE);
$username = $_POST['username'];
$password = $_POST['password'];
$url_to_open_after_success_login = $_POST['sezione'];
//Connect to my database
try {
$pdo = new PDO('mysql:host=0.0.0.0;dbname=name', 'user', 'passw');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "non riesco a connettere. perchè -> " . $e->getMessage();
exit();
}
//The table "accessi" has 2 fields that are "username" and "password"
//From this table I grab the data
try {
$query_mag = $pdo->prepare("SELECT * FROM accessi WHERE username = ?");
$query_mag->bindParam(1 , $username, PDO::PARAM_INT);
$query_mag->execute();
} catch (PDOException $e) {
echo "Unable to execute the query. ". $e->getMessage();
exit();
}
$dati_utente = $query_mag->fetch();
//CHECK IF THE PASSWORD IS CORRECT OR NOT
if ( password_verify($password, $dati_utente[1]) ) {
//login executed
$_SESSION["login"] = 1;
if ($url_to_open_after_success_login == 'something') {
header('location: /blabla/aaa.php');
} else {
header('location: /blabla2/bbb.php');
}
} else {
//WRONG PASSWORD! You are not allowed to access so go back to the home
header('location: /');
}
?>
The code above is pretty easy. I connect to the database, then I make a query to get the password (hashed of course) of a particular user. Then if the password is correct I am redirected to a page.
Only if the login successfully happened, I am using $_SESSION["login"] = 1;.
PROBLEM
On the top of each page I have the following code:
<?php
session_start();
if (!isset($_SESSION["login"])) { header('location: /error_page.php'); }
?>
<html>
<head>
//html/css/js code here...
If you look at the PHP code, you can understand that (if the user did not log in successfully) the page immediatly redirects to the error page. My question is the following.
Q: is this a safe way to check if the user logged in? should I avoid this redirect-way and try something else?
When a logged member wants to log out, I have made a logout.php file that looks like this:
<?php
session_start();
session_regenerate_id(TRUE);
$_SESSION = array();
//delete the session cookie
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
session_destroy();
header('location: /');
?>
A couple of points for you
After you issue a header for redirection, I would issue an exit; next, to stop execution of the script. Redirection should be the last thing you do anyways, so this ensures nothing else in your script runs accidentally.
$_SESSION is safe enough, provided your end users don't have a direct way to set or unset the data there. There's always the risk of a session hijack, but that's a different problem.
Your solution is not really safe because it missed some checks against session highjacking.
Additional you should store during the login the remote ip, remote agent and similar data on server side and compare it on every request to make (mostly) sure that the request comes from the right user.
See Proper session hijacking prevention in PHP and Preventing session hijacking

PHP Page isn't storing cookies

I am new to php and I am making a basic login script.
All I want to do is log in and have the cookie for my user_id stored.
It works on all of my other pages, except my index page which is one directory up.
So on my index page, I have this if statement:
<?php
if (!isset($_COOKIE['user_id'])) {
sign_in();
} else {
echo "You're already logged in!";
}
?>
No matter what I do, the sign_(); function always shows.
But here's the kicker:
On my login script, the whole thing goes through as if I successfully logged in.
I send it back to this page using:
header("Location: ../index.php");
(It is up one directory)
However, when I make it link to a page in the same directory, it registers the cookie and everything is alright.
header("Location: show_user.php");
If you want a hands on view, you can go to http://patti-bee2.dcccd.edu/coleman/wonder%20penguin/php/signup.php to make your account. And http://patti-bee2.dcccd.edu/coleman/wonder%20penguin/php/show_user.php to view it. And notice how the index page doesn't register the cookie.
How I tried to set the cookie:
if (isset($_POST['usernamelogin'])) {
$user_login = $_REQUEST['usernamelogin'];
$pass_login = $_REQUEST['passwordlogin'];
$pass_login = trim(crypt($pass_login, $user_login));
$login_query = sprintf("SELECT username, user_id FROM user WHERE username = '%s' and password = '%s';", mysql_real_escape_string($user_login), mysql_real_escape_string($pass_login));
$loginresult = mysql_query($login_query, $dbConn);
echo $login_query;
if (mysql_num_rows($loginresult) == 1) {
$userinfo = mysql_fetch_array($loginresult);
$username = $userinfo['username'];
$userid = $userinfo['user_id'];
setcookie('username', $username);
setcookie('user_id', $userid);
header("Location: show_user.php");
exit();
} else {
echo "Couldn't find your account!";
}
}
Please excuse my unrefined page and amateur mistakes. I have a lot to learn.
Any ideas?
Thank you for your time.
Check if you have the cookie with the following
<?php
var_dump($_COOKIE);
//if (!isset($_COOKIE['user_id']))
if (empty($_COOKIE['user_id']))
{
sign_in();
}
else {
echo "You're already logged in!";
}
?>

Categories