Header function not redirecting? - php

Please help
I have this php code(below) that creates and inserts a user into database after validating user inputs. I am storing the users input in an array. The problem is
It creates the user and inserts it to database but it does not redirect.
Here's the code
$validation = new Validate();
if($validation->passed()) {
//if success, insert(create) user
try {
$user = new User();
$salt = Crypt::salt(32);
$user->insert(array(
'username' => Accept::get('username'),
'password' => Crypt::make(Accept::get('password'), $salt),
'salt' => $salt,
'name' => Accept::get('name')
));
//After creation, redirect user
header('Location : index.php');
exit();
} catch(Exception $e) { //otherwise display errors
die("ERROR : CAN NOT REGISTER USER ".$e->getMessage());
}
This Code Creates user in database, but it does not redirect. I really don't understand why.

1) Make sure that you do not echo/output anything before the header() function not even blank space
2) write these at top of page to see errors
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
3) try ob_start(); or ob_flush();
ob_start();// at top of page
$validation = new Validate();
if($validation->passed()) {
//if success, insert(create) user
try {
$user = new User();
$salt = Crypt::salt(32);
$user->insert(array(
'username' => Accept::get('username'),
'password' => Crypt::make(Accept::get('password'), $salt),
'salt' => $salt,
'name' => Accept::get('name')
));
//After creation, redirect user
header('Location : index.php');
exit();
ob_flush();
} catch(Exception $e) { //otherwise display errors
die("ERROR : CAN NOT REGISTER USER ".$e->getMessage());
}

Related

How do I set custom user claims upon registration in PHP Firebase?

I am trying to set a role on users upon registration on my PHP Firebase database but I only ever see instructions on how to do it after registration.
Is it actually impossible? If not then how do I do it? I've tried this
if(isset($_POST['register_btn']))
{
$fullname = $_POST['full_name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$password = $_POST['password'];
$role = $_POST['role_as'];
$userProperties = [
'email' => $email,
'emailVerified' => false,
'phoneNumber' => '+63'.$phone,
'password' => $password,
'displayName' => $fullname,
'role_as' =>$role,
];
if($role == "registrar")
{
$createdUser = $auth->createUser($userProperties);
if($createdUser)
{
$auth->setCustomUserClaims($key, ['registrar' => true]);
$_SESSION['status'] = "User created successfully.";
header('Location: login.php');
exit();
}
else
{
$_SESSION['status'] = "User creation failed.";
header('Location: register.php');
exit();
}
}
}
but it clearly didn't work. I'm seeing that I am missing the $key, which is supposed to be the ID of the user but as it's not registered yet, there is none. How would I do this?
As ADyson commented, the call to createUser returns a UserRecord that contains a $uid property.
Also see:
the definition of UserRecord in the library code

Multiple User Connect to a Server with different Database

I am new to developing a website. I have question about user connection to server and database. For example, a server 'server1' have 2 database and website, 'webdata1' and 'webdata2'. (I am not using any framework for both website development because i still not familiar in framework.)
User A log in and create session to 'webdata1' and user B log in and create session to 'webdata2'. The problem is, when user A connect and create session to 'webdata1', for 'webdata2' also was connected with user A session instead of user B.
How can i split the user session and connection? It is by using framework (MVC Framework) solve this? Or is there another method for this?
session_start();
include "connectdatabase.php";
try
{
$connect = new PDO("mysql:host=$servername; dbname=$dbname", $username, $password);
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if(isset($_POST["login"]))
{
if(empty($_POST["username"]) || empty($_POST["password"]))
{
$message = '<label>All fields are required</label>';
}
else
{
$query = "SELECT * FROM User WHERE username = :username AND password = :password";
$statement = $connect->prepare($query);
$statement->execute(
array(
'username' => $_POST["username"],
'password' => $_POST["password"]
)
);
$count = $statement->rowCount();
if($count > 0)
{
$_SESSION["username"] = $_POST["username"];
header("location:index.php");
}
else
{
$message = '<label>Wrong Data</label>';
}
}
}
}
catch(PDOException $error)
{
$message = $error->getMessage();
}
I use this code in login.php for both website. "connectdatabase.php" contain code to connect to server and database.

Unable to insert a record in a table in php mysql

I am unable to insert the record in a table and even not getting any error but when I am trying to create a table with the same method the query is executing correctly. I stuck with this problem from last 2 days. can anyone please help me out. $database->create_database() function is used to create the dynamic database. $database->create_tables() function is used to create the tables with MySQL multi-query method.
index.php
<?php
ini_set('display_errors', '1');
error_reporting(E_ALL);
session_start();
$dbusername = $_SESSION['dbusername'];
$dbpassword=$_SESSION['dbpassword'];
$dbname=$_SESSION['dbname'];
$clienturl=$_SESSION['clienturl'];
$email=$_SESSION['email'];
error_reporting(0);
$db_config_path = '../application/config/database.php';
$_POST = array('hostname' => 'localhost' ,
'username' => $dbusername,
'password' => $dbpassword,
'database' => $dbname ,
'clienturl' => $clienturl ,
);
require_once 'includes/core_class.php';
require_once 'includes/database_class.php';
$core = new Core();
$database = new Database();
// Validate the post data
if ($core->validate_post($_POST) == true) {
// First create the database, then create tables, then write a config file
if ($database->create_database($_POST) == false) {
$message = $core->show_message('error', 'The database could not be created, please verify your settings.');
}
elseif($database->create_tables($_POST) == false) {
$message = $core->show_message('error', 'The database tables could not be created, please verify your settings.');
}
elseif ($core->write_config_url($_POST) == false) {
$message = $core->show_message('error', 'The database configuration url file could not be written, please chmod application/config/database.php file to 777');
}
elseif ($core->write_config($_POST) == false) {
$message = $core->show_message('error', 'The database configuration file could not be written, please chmod application/config/database.php file to 777');
}
elseif ($database->update_tables($_POST) == false) {
$message = $core->show_message('error', 'There is a problem while updating email id and password');
}
// If no errors, redirect to registration page
if (!isset($message)) {
$redir = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') ? 'https' : 'http');
$redir .= '://'.$_SERVER['HTTP_HOST'];
$redir .= str_replace(basename($_SERVER['SCRIPT_NAME']), '', $_SERVER['SCRIPT_NAME']);
$redir = str_replace('install/', '', $redir);
header('Location: '.$redir);
}
} else {
$message = $core->show_message('error', 'Not all fields have been filled in correctly. The host, username, password, and database name are required.');
}
//}
?>
database_class.php file
<?php
class Database
{
// Function to the database and tables and fill them with the default data
public function create_database($data)
{
// Connect to the database
$mysqli = new mysqli($data['hostname'], $data['username'], $data['password'], '');
// Check for errors
if (mysqli_connect_errno()) {
return false;
}
// Create the prepared statement
$mysqli->query('CREATE DATABASE IF NOT EXISTS '.$data['database']);
// Close the connection
$mysqli->close();
return true;
}
// Function to create the tables and fill them with the default data
public function create_tables($data)
{
// Connect to the database
$mysqli = new mysqli($data['hostname'], $data['username'], $data['password'], $data['database']);
// Check for errors
if (mysqli_connect_errno()) {
return false;
}
// Open the default SQL file
$query = file_get_contents('assets/install.sql');
// Execute a multi query
$mysqli->multi_query($query);
// Close the connection
$mysqli->close();
return true;
}
public function update_tables($data)
{
// Connect to the database
$mysqli = new mysqli($data['hostname'], $data['username'], $data['password'], $data['database']);
// Check for errors
if (mysqli_connect_errno()) {
return false;
}
$insert = "INSERT INTO xyz (firstname) VALUES ('Tacos')";
$mysqli->query($insert);
$mysqli->close();
return true;
}
}
and core_class.php class is used to validate the form data and write some config files.

Problems with log in check

I write the following loginCheck code and the database schema I use is as follows:
userinfo:
username varchar
password varchar
code:
<?php
//set the MIME type to application/json
//header("Content-Type: application/json");
//get the username and password
$username = $_POST['username'];
$password = $_POST['password'];
//require database operation
require 'database.php';
$stmt = $mysqli->prepare ("SELECT username, password, COUNT(*) FROM userinfo WHERE username=?");
if(!$stmt){
echo json_encode(array(
"success" => false,
"message" => "an error occured, please try again"
));
exit;
}
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($returnedUsername, $hashedPassword, $count);
$stmt->fetch();
if ($count==1 && crypt($password, $hashedPassword) == $hashedPassword) {
//all information provided is correct, start a session
ini_set("session.cookie_httponly", 1);
session_start();
$previous_ua = #$_SESSION['useragent'];
$current_ua = $_SERVER['HTTP_USER_AGENT'];
$_SESSION['username'] = $username;
if(isset($_SESSION['useragent']) && $previous_ua !== $current_ua){
die("Session hijack detected");
} else{
$_SESSION['useragent'] = $current_ua;
}
//create a token
$_SESSION['token'] = substr(md5(rand()), 0, 10);
echo json_encode(array(
"success" => true,
"token" => htmlentities($_SESSION['token']),
"username" => htmlentities($_SESSION['username'])
));
exit;
} else {
echo json_encode(array(
"success" => false,
"message" => "Incorrect Username or Password"
));
exit;
}
$stmt->close();
?>
The url is:
http://ec2-54-148-227-9.us-west-2.compute.amazonaws.com/~beibeixhb/Calendar/calendar.php
I am not sure why it prevent me from logging in, any suggestions?
You are using the hashed version of your password as a salt to the password entered and you expect that to be the same as the hashed password. I don't think this can ever happen.
crypt($password, $hashedPassword) == $hashedPassword
It's not clear from your code where you get the salt from, but if you didn't use salt to hash the password to start with, taking out that second argument of crypt should do the job for you.
Alternatively, use the right salt as a second argument to crypt.

Created login but when redirect doesnt work

I created a login page login.php, when the user logs in they are redirected to login-home.php, I then,
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
echo "Welcome to the member's area, " . $_SESSION['username'] . "!";
} else {
echo "Please log in first to see this page.";
}
and i get the the Please log in first.
Why wont this actually log in?
Login.php
<?PHP
error_reporting(9);
require_once("./include/membersite_config.php");
if(isset($_POST['submitted']))
{
$users['admin'] = array('password' => 'admin', 'redirect' => 'admin.php');
$users[$username] = array('password' => $password, 'redirect' => 'login-home.php');
if(array_key_exists($_POST['username'],$users)) {
if($_POST['password'] == $users[$_POST['username']]['password']) {
$_SESSION['loggedIn'] = true;
header('Location:'.$users[$_POST['username']]['redirect']);
exit();
}
}
if($fgmembersite->Login())
{
$fgmembersite->RedirectToURL("login-home.php");
}
}
?>
With logging in and using sessions, Make sure that you are using session_start() on any page that is using the $_SESSION var. Check out the php session manual for some more information on this.
With redirects, Im not sure if you are having a problem with this or not, but you need to make sure that there is nothing written to the browser before a redirect. a empty line before the redirect outside of the <?php will even cuase a redirect to not work. Any kind of echo or print will also cause this.
UPDATE
After seeing your code, This shows that you are not doing a session_start() See code below:
<?PHP
session_start();
error_reporting(9);
require_once("./include/membersite_config.php");
if(isset($_POST['submitted']))
{
$users['admin'] = array('password' => 'admin', 'redirect' => 'admin.php');
$users[$username] = array('password' => $password, 'redirect' => 'login-home.php');
if(array_key_exists($_POST['username'],$users)) {
if($_POST['password'] == $users[$_POST['username']]['password']) {
$_SESSION['loggedIn'] = true;
header('Location:'.$users[$_POST['username']]['redirect']);
exit();
}
}
if($fgmembersite->Login())
{
$fgmembersite->RedirectToURL("login-home.php");
}
}
?>
Then on your login-home.php page before anything is checked with sessions, put session_start(). Once a user logs out, you will want to do the following
session_start();
session_unset();
header('Location:url/to/redirect/to');

Categories