Viewed   102 times

I'm a beginner working on a login script in PHP. This is the form token statement that I have so far:

$_SESSION["form_token"] = md5(rand(time (), true)) ;

The statement is issued just after the user indicates that he/she wants to login.

My limited understanding is that the tokens purpose is to identify a unique user at a unique point in time and to disguise the form token information.

Then everything becomes fuzzy. Here are my 3 open questions:

  1. When is the best time to "check" the form token for security purposes?

  2. How do I check it?

  3. When, if ever, do I "destroy" the form token? (IOW, would the form token stay "active" until the user logs out?

 Answers

3

There is no need to do what you are attempting. When you start a session in PHP with session_start() a unique SESSIONID is already generated for you. You should not be putting this on the form. It is handled via cookies by default. There is also no need to check the SESSIONID either, that again is handled for you.

You are responsible for authenticating the user and storing their authenticated identity (e.g. $_SESSION['user_id'] = $userId in the SESSION. If a user logs out you destroy their session with session_destroy.

You should ensure session_start() is one of the first things for all pages in your site.

Here is a basic example:

<?php
session_start(); // starts new or resumes existing session
session_regenerate_id(true); // regenerates SESSIONID to prevent hijacking

function login($username, $password)
{
    $user = new User();
    if ($user->login($username, $password)) {
        $_SESSION['user_id'] = $user->getId();
        return true;
    }
    return false;
}

function logout()
{
    session_destroy();
}

function isLoggedIn()
{
    return isset($_SESSION['user_id']);
}

function generateFormHash($salt)
{
    $hash = md5(mt_rand(1,1000000) . $salt);
    $_SESSION['csrf_hash'] = $hash
    return $hash;
}

function isValidFormHash($hash)
{
    return $_SESSION['csrf_hash'] === $hash;
}

Edit: I misunderstood the original question. I added the relevant methods above for generating and validating form hashes;

Please see the following resources:

  • PHP Session Handling
  • session_start()
  • session_destroy()
Wednesday, August 3, 2022
5

I've had the same problem with what you state because of single CSRF and it gets replaced unless they submit the latest page, but if you use a array w/session it should solve your problem(s). Also you might want to include a captcha, I'd recommend Google's Recaptcha.

session_start();
function createToken(){
    $token = sha1(uniqid(mt_rand(), true));
    $_SESSION['Tokens']['Token'][] = $token;
    $_SESSION['Tokens']['Time'][] = time() + (10 * 60); #10 min limit
    #you can omit/change this if you want to not limit or extend time limit
    return $token;
}

function checkToken($token){
    clearTokens();
    foreach($_SESSION['Tokens']['Token'] as $key => $value){
        if($value === $token){
            return true;
        }
    }
    return false;
}

function clearTokens(){
    foreach($_SESSION['Tokens']['Time'] as $key => $value){
        if($value <= time()){
            unset($_SESSION['Tokens']['Token'][$key], $_SESSION['Tokens']['Time'][$key]);
            #remove last parameter if you aren't using token time limit
        }
    }
}

your HTML:

<input type="hidden" name="token" value="<?php createToken(); ?>">

PHP Token Checker

if(isset($_POST['token']) && checkToken($_POST['token'])){
    #valid token
}else{
    #create error message saying that they tried to repost data or session token expired
}
Tuesday, October 25, 2022
3

Hi i faced same issue over here

https://.com/a/52096688/1234825

and tried a different approach

Facebook seems to have "short of" break its own code. By enabling enfore https, the Validate OAuth url no longer validates.

I have added the following param on my redirect url to bypass the issue

https://mysubdomain.mysite.gr/index.php?r=site/callbackfb&enforce_https=1
Sunday, December 25, 2022
 
2

Well, without looking at the rest of your code it's difficult to say. But with headers, the header must be sent before anything is written to the response stream (ie before any echo statements OR any code that is not included inside of <?php ... ?> tags) so that could be why it isn't redirecting. The code you supplied looks good to me.

Monday, October 3, 2022
 
ailnlv
 
3

In short:

Dont put this :

$message = 'Bedrijfsnaam: ' . $bedrijfsnaam;

Before this:

$bedrijfsnaam = $_POST['bedrijfsnaam'];

Same things for all others variables used for your mail() function

Your php script should be like this:

<?php
$servername = "youdliketoknowthat.com";
$username = "butitssecret";
$password = "hunter123";
$dbname = "yougettheidea";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

if(isset($_POST['submit'])){

$bedrijfsnaam = $_POST['bedrijfsnaam'];
$volledigenaam = $_POST['volledigenaam'];
$telefoonnummer = $_POST['telefoonnummer'];
$email = $_POST['email'];
if($volledigenaam !=''||$email !='');
$website = $_POST['website'];
$webshop = $_POST['webshop'];
$app = $_POST['app'];
$onlinemarketing = $_POST['onlinemarketing'];

{

$sql = "INSERT INTO intake_formulier_test (bedrijfsnaam, volledigenaam, telefoonnummer, email, website, webshop, app, onlinemarketing)
VALUES ('$bedrijfsnaam', '$volledigenaam', '$telefoonnummer', '$email', '$website', '$webshop', '$app', '$onlinemarketing')";
}
if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
    // Now we can send email
    $to = 'me@myemail.com';
    $subject = 'Content formulier';
    $headers = "From: me@myemail.comrn";
    $message = 'Bedrijfsnaam: ' . $bedrijfsnaam;
    $message .= 'Volledige naam: ' . $volledigenaam;
    $message .= 'Telefoonnummer: ' . $telefoonnummer;
    $message .= 'email: ' . $email;
    mail($to, $subject, $message, $headers);
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}
}

$conn->close();
?>

You were adding things to your $message var like this: $message = 'Bedrijfsnaam: ' . $bedrijfsnaam; But at that point, for this particular exemple, the var $bedrijfsnaam wasn't declared... So your $message var was empty ! In my example, i put all the things related to emailing infos after DB query, and after all your $var = $_POST["var"]..

Friday, December 23, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :