PHP - Expiring Token
Hello
I am looking to create an expiring token for use with our password reset system. We want tokens to be valid for a set period, let's say 24hrs.
Currently we md5 the username and userid, and send this as a token to the users registered email... It's OK, but means that token is valid indefinitely. I am not keen on adding more fields to the database to store the time the request was made, so wondered if anyone had a suggestion?
Is there a way I can encrypt a token including a timestamp and then decrypt it to separate the elements out to check the timestamp?
Thanks
Similar TutorialsHi guys, Need your expertise again I need to generate a token that will be difficult to reverse engineer to prevent it from being forged. The token will carry some IP address info and some hash info from a file on the system. It also must carry a current datetime stamp, because the token will expire some minutes after being issued. All of this data info needs to be embedded into the token and then the token itself needs to be secured via some sort of encryption. It must then be passed as a URL string. Last, I would like to be able to build in a checksum into the final token string so that the receiving server can quickly determine if the token itself is complete before it looks to decrypt it. 1. My source data (IP address info, file hash data, datetime stamp). 2. Encryption/Decryption 3. URL-safe characters. 4. Checksum to quickly determine if complete/valid token. I have my own ideas on how to accomplish this but I could use your feedback. Please don't be shy with the details thanks and hope you guys had a Happy Thanksgiving. Hello, I have been trying many different ways to complete this and I am totally stuck. I can use the cURL in my terminal fine and it does what I want it to do. I am creating a system where I want the people offering the position to have an automatic system in place.
this code works when I add my information, The problem I seem to be having is that it is not connecting to the cPanel?
Is this because I am on a shared hosting plan?
$cpanel = new CPANEL(); // Connect to cPanel - only do this once. // Create the user@example.com email address. $new_email = $cpanel->uapi( 'Email', 'add_pop', array( 'email' => 'user', 'password' => '12345luggage', 'quota' => '0', 'domain' => 'example.com', 'skip_update_db' => '1', ) ); What am I doing wrong apart from something obvious, I have managed to get everything working how I want in this site apart from this part. Thank you in advance, Greg Hi, i need to know for what is using tokens, for security or ? And if someone can give me some little example ? Thanks.. Hello guys
I have a problem figure out how I can get value out from this string:
userId ?userSessionToken=cd89584f-5711-4e0a-899a-ae9247fdcf0c
I will be needing the: cd89584f-5711-4e0a-899a-ae9247fdcf0c only for my user api.
Regards
Brian Olsen
hey guys,
i need a little help on the best way to generate a seo friendly token...at the moment i use password_hash() with a peice of users information to create a key so that the user can verifiy account by a url sent via email.
now the problem i'm having with that is it contains forward slashes which is killer for my uri and not to mention all the other seo friendly characters it conatins.
how do i make the hash url friendly?...any advise would be great
thank you
Ok, I have a script that when you buy counter strike server and you get that gpanel from where you can stop/restart your server etc. And you get token for each server on gpanel. Now, I made script to make people easier to restart their servers when they are down...I made it with api. But script contains couple of files...and you have to edit config.php and put your token there ! Now I want to make like mass server restarter...So I made website restartuj.info and now I need to make a script that can allow members to login on my website with their token and that will automatically allow them to restart their server... But I have a problem...I have no idea have to make that script...It must edit config.php when some member login with his token ! So any help with that ??? Thanks in advance. Hi all, I'm writing my own MVC framework purely to improve my oo php skills and I've created a CSRF token validation class to help prevent CSRF attacks. I just need some feedback on it really, is it insecure, is there a better way to validate tokens, etc. Code: [Select] <?php // Security measure. if (!defined('BASE_PATH')) { exit(); } class CSRF { private static $tokens = array(); private static $session_name = 'csrf_data'; /** * Loads CSRF token data from session into $tokens array. * * This is called before the controller is loaded. * * @return void */ public static function init() { $session_name = self::$session_name; // Move CSRF token data from session to class field. if (isset($_SESSION[$session_name])) { self::$tokens = unserialize($_SESSION[$session_name]); unset($_SESSION[$session_name]); } } /** * Saves the CSRF data to a session. * * @static * @return void */ private static function save() { $session_name = self::$session_name; unset($_SESSION[$session_name]); $_SESSION[$session_name] = serialize(self::$tokens); } /** * Creates a new token. * * @static * @param string $name * @return string */ private static function generateToken($name) { $token = md5(uniqid(rand(), true)); self::$tokens[$name] = $token; self::save(); return $token; } /** * Validate a token by its name. * * @static * @param string $name * @param string $token The CSRF token included with the form data. * @return bool */ public static function validateToken($name, $token) { if (!isset(self::$tokens[$name])) { return false; } return ($token == self::$tokens[$name]); } } // End of CSRF class. im trying to create a basic login page and after checking username and password and navigating to next page i get this error on the page it suppose to navigate to and the section of code its referring too Parse error: syntax error, unexpected token ";" in C:\xampp\htdocs\bubbleandbalm\index.php on line 4 <?php session_start(); if(isset($_SESSION['id']) && (isset($_SESSION['user_name'])){ ?> this is the full code for that page aswell
<?php session_start(); if(isset($_SESSION['id']) && (isset($_SESSION['user_name'])){ ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" > <title>RedStore | Ecommerce Website Design</title> <link rel="stylesheet" href="style.css"> <link rel="preconnect" href="https://fonts.gstatic.com"> <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@200;500;600;700&display=swap" rel="stylesheet"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.3/css/fontawesome.min.css"> </head> <body> <div class="header"> <div class="container"> <div class="navbar"> <div class="logo"> <img src="images/logo.png" width="125px"> </div> <nav> <ul id="MenuItems"> <li><a href="">Home</a></li> <li><a href="">Products</a></li> <li><a href="">About</a></li> <li><a href="">Contact Us</a></li> <li><a href="">Account</a></li> </ul> </nav> <img src="images/cart.png" width="30px" height="30px" > <img src="images/menu.png" class="menu-icon" onclick="menutoggle()"> </div> <div class="row"> <div class="col-2"> <h1>Give Your Workout<br>A New Style?</h1> <p>Success isnt always about greatness. It's about consistency. consistent<br>hard work gains success, Greatness will come. </p> <a href="" class="btn">Explore Now →</a> </div> <div class="col-2"> <img src="images/image1.png"> </div> </div> </div> </div> <!--featured categories--> <div class="categories"> <div class="small-container"> <div class="row"> <div class="col-3"> <img src="images/category-1.jpg"> </div> <div class="col-3"> <img src="images/category-2.jpg"> </div> <div class="col-3"> <img src="images/category-3.jpg"> </div> </div> </div> </div> <!--featured products--> <div class="small-container"> <h2 class="title">Featured Products</h2> <div class="row"> <div class="col-4"> <img src="images/product-1.jpg"> <h4>Red Printed T-Shirt</h4> <p>£25.00</p> </div> <div class="col-4"> <img src="images/product-2.jpg"> <h4>Red Printed T-Shirt</h4> <p>40.00</p> </div> <div class="col-4"> <img src="images/product-3.jpg"> <h4>Red Printed T-Shirt</h4> <p>£30.00</p> </div> <div class="col-4"> <img src="images/product-4.jpg"> <h4>Red Printed T-Shirt</h4> <p>£20.00</p> </div> </div> <!--latest products--> <h2 class="title">Latest Products</h2> <div class="row"> <div class="col-4"> <img src="images/product-5.jpg"> <h4>Red Printed T-Shirt</h4> <p>£25.00</p> </div> <div class="col-4"> <img src="images/product-6.jpg"> <h4>Red Printed T-Shirt</h4> <p>40.00</p> </div> <div class="col-4"> <img src="images/product-7.jpg"> <h4>Red Printed T-Shirt</h4> <p>£30.00</p> </div> <div class="col-4"> <img src="images/product-8.jpg"> <h4>Red Printed T-Shirt</h4> <p>£20.00</p> </div> <div class="row"> <div class="col-4"> <img src="images/product-9.jpg"> <h4>Red Printed T-Shirt</h4> <p>£25.00</p> </div> <div class="col-4"> <img src="images/product-10.jpg"> <h4>Red Printed T-Shirt</h4> <p>40.00</p> </div> <div class="col-4"> <img src="images/product-11.jpg"> <h4>Red Printed T-Shirt</h4> <p>£30.00</p> </div> <div class="col-4"> <img src="images/product-12.jpg"> <h4>Red Printed T-Shirt</h4> <p>£20.00</p> </div> </div> </div> </div> <!--offer--> <div class="offer"> <div class="small-container"> <div class="row"> <div class="col-2"> <img src="images/exclusive.png" class="offer-img"> </div> <div class="col-2"> <p>Exclusively Available on RedStore</p> <h1>Smart Band 4</h1> <small>TheMi Smart Band 4 features a 39.9% larger AMOLED color full-touch display with adjustable brightness, so everything is clear as can be. </small> <a href="" class="btn">Buy Now →</a> </div> </div> </div> </div> <!--Brands--> <div class="brands"> <div class="small-container"> <div class="row"> <div class="col-5"> <img src="images/logo-godrej.png"> </div> <div class="col-5"> <img src="images/logo-oppo.png"> </div> <div class="col-5"> <img src="images/logo-coca-cola.png"> </div> <div class="col-5"> <img src="images/logo-paypal.png"> </div> <div class="col-5"> <img src="images/logo-philips.png"> </div> </div> </div> </div> <!--footer--> <div class="footer"> <div class="container"> <div class="row"> <div class="footer-col-1"> <h3>Download Our App</h3> <p>Download Appfor Android<br>and IOS mobile phone.</p> <div class="app-logo"> <img src="images/play-store.png"> <img src="images/app-store.png"> </div> </div> <div class="footer-col-2"> <img src="images/logo-white.png"> <p>Our purpose is to sustainably make the pleasure and<br>benefits of sports accessible to the many.</p> </div> <div class="footer-col-3"> <h3>Useful Links</h3> <ul> <li>Coupons</li> <li>Blog Posts</li> <li>Return Policy</li> <li>Join Affiliate</li> </ul> </div> <div class="footer-col-4"> <h3>Follow Us</h3> <ul> <li>Facebook</li> <li>Twitter</li> <li>Instagram</li> <li>Youtube</li> </ul> </div> </div> <hr> <p class="copyright">Copyright 2021 - Easy Tutorials</p> </div> </div> <!--js for toggle menu--> <script> var MenuItems = document.getElementById("MenuItems"); MenuItems.style.maxHeight = "0px"; function menutoggle(){ if(MenuItems.style.maxHeight == "0px"){ MenuItems.style.maxHeight = "200px"; } else{ MenuItems.style.maxHeight = "0px"; } } </script> </body> </html> <?php } else{ header("Location: account.php"); exit(); } ?> my login in page <?php session_start(); include "db_conn.php"; if (isset($_POST['uname']) && isset($_POST['password'])){ function validate($data){ $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } $uname = validate($_POST['uname']); $pass = validate($_POST['password']); if(empty($uname)){ header("Location: account.php?error=User Name is required"); exit(); } else if (empty($pass)){ header("Location: account.php?error=Password is required"); exit(); } else{ $sql = "SELECT * FROM login WHERE user_name = '$uname' AND password = '$pass'"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) === 1){ $row = mysqli_fetch_assoc($result); if($row['user_name'] === $uname && $row['password'] === $pass){ $_SESSION['user_name'] = $row['user_name']; $_SESSION['name'] = $row['name']; $_SESSION['id'] = $row['id']; header("Location: index.php"); exit(); } else{ header("Location: account.php?error=Incorrect username or password"); exit(); } } else{ header("Location: account.php?error=Incorrect username or password"); exit(); } } } else{ header("Location: account.php"); exit(); } ?> db_conn page <?php $sname = "localhost"; $uname = "root"; $password = ""; $db_name = "users"; $conn = mysqli_connect($sname,$uname,$password, $db_name); if (!$conn){ echo "Connection failed!"; } ?>
Hi, I am new to linux and was trying my first experience using cygwin on Windows 7. I am trying to run the following simple script named parsescript3 in the home directory and keeps getting the error 'syntax error near unexpected token `(''. Can anyone please help and let me know what is exactly wrong with the syntax?
~/bin/parsescript3 content
#!/bin/bash
FOR /F "TOKENS=1,2 DELIMS=," %%A IN ("serverA,D") DO @ECHO %%A %%B
Execution and output on cygwin64:
~/bin
$ ./parsescript3
./parsescript3: line 3: syntax error near unexpected token `('
./parsescript3: line 3: `FOR /F "TOKENS=1,2 DELIMS=," %%A IN ("serverA,D") DO @ECHO %%A %%B'
Hello I've recently been made aware that I need to hash the token I use when allowing users to reset their password. I have a working solution but I'm hoping someone could let me know if this is an adequate way of doing it; 1. User enters their email, I check whether their actually a member and then... create a passcode (1) create a salt (2) hash them together to create a passcode_hash (3) insert the (2) and (3) into the database send an email to the user with a link using (1) and the userid in the address 2. When the link is followed... $_GET the userid and lookup the salt and passcode_hash for that id hash together the passcode in the URL with the salt, and compare that to passcode_hash if that is successfull then allow an update of the password (show the update form) 3. The password update form is sent along with two hidden fields (the passcode and userid from the URL) On the form processing script I perform the same check as on Step 2 to check the passcode and user id have not been messed with Update the password and delete the passcode Hopefully that makes sense... is that correct? Here is my code that compares the passcode with the passcode_hash.... // get the passcode and email from URL (I will sanitize these) $passcode = $_GET['passcode']; $member_id = $_GET['uid']; // find the salt associated with the userid $stmt = $db->prepare("SELECT passcode,salt FROM members_verify WHERE members_id = ?"); $stmt->bind_param('i',$member_id); $stmt->execute(); $stmt->bind_result($db_passcode,$salt); $stmt->fetch(); $stmt->close(); // Create salted password $passcode_hash = hash('sha512', $passcode . $salt); if($passcode_hash===$db_passcode){ $allowUpdate = 'yes'; }Any advice would be great Edited by paddyfields, 07 June 2014 - 08:18 AM. As part of the registration procedure, my PHP application generates the mail below and presents the option to a user to click on the url in the mail to activate his account.
Please click on this link http://www.example.org.ng/activate.php?token=XeZNYf8uDVYxAY5+RBqldOosI1hm/FjB0cLnXB8R to activate your account.The activate.php script returns that their is no record of this token in the database, even though it is there. In troubleshooting, i printed the $token = $_GET["token"] in the activate.php script; and this is what i got XeZNYf8uDVYxAY5 RBqldOosI1hm/FjB0cLnXB8R. Notice that the $token variable is missing one character, (the +), which is the 16th character form the left!! Why this would happen is unclear. Any thoughts. If it helps, the is the script generating my random tokens: function generateToken($length = 40) { if(function_exists('openssl_random_pseudo_bytes')) { $token = base64_encode(openssl_random_pseudo_bytes($length, $strong)); if($strong == TRUE) return substr($token, 0, $length); //base64 is about 33% longer, so we need to truncate the result } //fallback to mt_rand if php < 5.3 or no openssl available $characters = '0123456789'; $characters .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz^!$'; $charactersLength = strlen($characters)-1; $token = ''; //select some random characters for ($i = 0; $i < $length; $i++) { $token .= $characters[mt_rand(0, $charactersLength)]; } return $token; } $token=generateToken($length = 40); Edited by terungwa, 09 June 2014 - 05:17 PM. Hi everybody ! I have this current problem .. I need to login into a website via cUrl .. website : www.v-tac [dot] ro/ Now based on the headers and based on the input fields I wrote a php function, but I hit a wall with the token . HEADERS : username=username&password=password&Submit=Conectare&option=com_users&task=user.login&return=aW5kZXgucGhwP0l0ZW1pZD0yMTY%3D&0dbf64fe20e2395a7d72ed5b64b3cf7c=1FORM FIELDS - copy paste - this is the login form <fieldset class="userdata"> <p id="form-login-username"> <label for="modlgn-username">Nume Utilizator</label> <input id="modlgn-username" type="text" name="username" class="inputbox" size="18"> </p> <p id="form-login-password"> <label for="modlgn-passwd">Parola</label> <input id="modlgn-passwd" type="password" name="password" class="inputbox" size="18"> </p> <p id="form-login-remember"> <label for="modlgn-remember">Retine utilizator</label> <input id="modlgn-remember" type="checkbox" name="remember" class="inputbox" value="yes"> </p> <input type="submit" name="Submit" class="button" value="Conectare"> <input type="hidden" name="option" value="com_users"> <input type="hidden" name="task" value="user.login"> <input type="hidden" name="return" value="aW5kZXgucGhwP0l0ZW1pZD0yMTY="> <input type="hidden" name="11b09608b3184e6258012d44846c81ed" value="1"> </fieldset>And this is the function I wrote to do the cUrl login : function login_to_website($targetURL){ global $browser_user_agent; if(empty($targetURL)) { return; } if(empty($login_url)) { $login_url = $targetURL; } $url = $login_url; $login_user = "loginusername"; $login_password = "loginpassword"; $thetoken = "this-is-my-problem-the-token-from-the-hidden-input"; $post_data = array(); $post_data['username'] = "$login_user"; $post_data['password'] = "$login_password"; $post_data['Submit'] = "Conectare"; $post_data['option'] = "com_users"; $post_data['task'] = "user.login"; $post_data['return'] = "aW5kZXgucGhwP0l0ZW1pZD0yMTY%3D"; $post_data[$thetoken] = "1"; $postthis = http_build_query($post_data); $login = curl_init(); curl_setopt($login, CURLOPT_COOKIEJAR, dirname(__FILE__) . "/cookie.tmpz"); curl_setopt($login, CURLOPT_COOKIEFILE, dirname(__FILE__) . "/cookie.tmpz"); curl_setopt($login, CURLOPT_VERBOSE, true); curl_setopt($login, CURLOPT_URL, $url); curl_setopt($login, CURLOPT_USERAGENT, random_user_agent()); curl_setopt($login, CURLOPT_FOLLOWLOCATION, TRUE); curl_setopt($login, CURLOPT_RETURNTRANSFER, TRUE); curl_setopt($login, CURLOPT_POST, TRUE); $timeout = 5; curl_setopt( $login, CURLOPT_CONNECTTIMEOUT, $timeout ); curl_setopt( $login, CURLOPT_TIMEOUT, $timeout ); curl_setopt( $login, CURLOPT_MAXREDIRS, 10 ); curl_setopt($login, CURLOPT_POSTFIELDS, $postthis); // POST vars curl_setopt($login, CURLOPT_HEADER, 0); // debug headers sent - 1 $data = curl_exec ($login); curl_setopt($login, CURLOPT_URL, $targetURL); $datax = curl_exec ($login); return $datax; // close cURL resource, and free up system resources curl_close($login); }The problem is this the last array input. the token is generated each time the page is loaded, located on the page as an input hidden field . So the question is how do I get a fresh token that will work ? Also I have tried to get the token with a xpath extract like this : $htmlx = file_get_contents('http://www.v-tac.ro'); $htmlx = mb_convert_encoding($htmlx, 'UTF-8', mb_detect_encoding($htmlx)); //make sure this is utf8 if(!strlen($htmlx)) {echo "No HTML here . stoping execution ."; return;} $doc = new DomDocument; @$doc->loadHTML($htmlx); $xpath = new DOMXPath($doc); echo $xpath->query('//fieldset[@class="userdata"]/input[5]')->item(0)->getAttribute("name"); $thetoken = $xpath->query('//fieldset[@class="userdata"]/input[5]')->item(0)->getAttribute("name");Help !? I am working on a simple authentication system and something has came to light regarding the access token and potential brute force. For the access token there is an expiry date/time where the client will need to send a refresh token to get a new access token. However, what is stopping an attempt to run a brute force attack against an endpoint and firing lots of random values for the access token? I know it will be a guessing game but potentially if you have a few million users all with valid tokens then there is a possibility that it could guess it after a few days/weeks of trying? I know, csrf token is like a random string. Does every form need a csrf token? Does every form need to have a different csrf token or all forms have a same csrf token for one logged in user? When an user logged in, I set $_SESSION['key']=$useremail; is it ok to set email for a logged in session? Do I have to set or add another $_SESSION with csrf token? How does csrf token add security for form submission? After form submission, what would PHP do with the hidden input field or with the csrf token? Someone parses the html login form and gets the csrf token from hidden field. Now can he request with that csrf token to login through jquery ajax?
Hello, i got a problem with my codes, it says Parse error: syntax error, unexpected token "endwhile" . Please help me, Here's my code:
<?php
while($rows=mysqli_fetch_array($result)); |