Jump to content

oz11

Members
  • Posts

    169
  • Joined

  • Last visited

Posts posted by oz11

  1. Hey. Been a while since I last posted here.

    Problem:  the first 8 lines of code work for the top box, but not the bottom box. 

    Code in question is this:

    <?php 
    // bottom
    if ($anon_comment== "1"){
    ?>
     <span style="color: black">Post as anonymous?</span> <input type="checkbox" id="anon" name="anon" value="set" checked>
    <?php
    } elseif($anon_comment == "2" ) {
    	?>
     <span style="color: black">Post as anonymous?</span> <input type="checkbox" id="anon" name="anon" value="set">
    	<?php
    }
    ?>

    And for illustration purposes here is the second box...

    <?php 
    // bottom
    if ($anon_comment== "1"){
    ?>
     <span style="color: black">Post as anonymous?</span> <input type="checkbox" id="anon" name="anon" value="set" checked>
    <?php
    } elseif($anon_comment == "2" ) {
    	?>
     <span style="color: black">Post as anonymous?</span> <input type="checkbox" id="anon" name="anon" value="set">
    	<?php
    }
    ?>

    Like I said it works on line 220 but not line 151. Both are very similar if not the same, but the bottom one never works at all. Its like the conditional statement above is not working the other box (aka "bottom"). The first box works fine and as expected.

    Whole code:

    
    
    
    <?php
    $stmt = $pdo->prepare("SELECT cooment_anon FROM `users` WHERE user_id = ?");
    $stmt->execute([$_SESSION['the_usr_id']]); 
    $is_anon_set = $stmt->fetch();
    
    if($is_anon_set['cooment_anon'] == 1){
    	echo $anon_comment =  "1";
    } else {
    	echo $anon_comment =  "0";
    }
    
    if (isset($_GET['anon'])){
    	echo "posting as anon";
    }
    
    // ---~ login check ~---
    
    // --- ~~ ---
    ?>
    
    <style>
    
    .generalclass {
      color: #ffffff;
      text-align: left;
      margin: 10px;
      padding: 10px;
      display: none;
    }
    
    </style>
    <?php //require_once "../config.php";
    // create/display nested comments
    
    // init
    $user_id = $_SESSION['the_usr_id'];
    
    
    	
    // fake some data
    //$_GET['news_id'] = $news['news_id'];
    $_GET['news_id'] = 0; //                                         <-------------------- TESTING
    $_COMMENTS_ID= $news['news_id'];
    
    $post = []; // array to hold a trimmed working copy of the form data
    $errors = []; // array to hold user/valdiation errors
    
    // post
    if($_SERVER['REQUEST_METHOD'] == 'POST')
    {
    	// trim all the data at once
    	$post = array_map('trim',$_POST); // if any input is an array, use a recursive trim call-back function here instead of php's trim
    	
    	// validate inputs here...
    	
    	// if no errors, use the form data
    	if ($post['anon'] == "set"){
    		$is_anon = 1;
    	} else {
    		$is_anon = 0;
    	}
    	if(empty($errors))
    	{
    		$sql = "INSERT INTO `comment` (`comment_id`, `parent`, `news_id`, `user_id`, `content`, `karma`, `removed`, `reference____`, 
            `date`, `last_update`, `aproved`, `anonymous`, `image_upld`) VALUES (NULL, ?, ?, ?, ?, '0', '0', '', NOW(), NULL, '1', ?, NULL)";
    		$stmt = $pdo->prepare($sql);
    		$stmt->execute([ $post['parent_id'], $_COMMENTS_ID, $user_id, $post['comment'], $is_anon ]);
    	}
    	
    	// if no errors, success
    	if(empty($errors))
    	{
    		die(header("Refresh:0"));
    	}
    }
    
    // get all the rows of data for the requested news id
    $sql = "SELECT comment.parent, comment.comment_id, comment.news_id, comment.user_id, comment.content, comment.karma, comment.removed, 
    comment.date, comment.last_update, comment.aproved, comment.anonymous, comment.image_upld, users.name, users.avatar FROM `comment` LEFT JOIN `users` 
    ON `comment`.`user_id` = `users`.`user_id` WHERE news_id = ? ORDER BY comment_id DESC LIMIT 800";
    $stmt = $pdo->prepare($sql);
    $stmt->execute([ $_COMMENTS_ID ]);
    $comment_data = $stmt->fetchAll(PDO::FETCH_GROUP);
    
    // recursive function to output parent/child data
    
    
    function list_comments($parent_id, $data, $level=0)
    {
    
    
    	// this just supplies a visual part to the output so you can see what the code does
    	//$indent = str_repeat("<span style='color: transparent;'>---- </span>", $level);
    	$indent = str_repeat("<span style='color: transparent;'>---- </span>", $level);
    
    	
        //echo "<pre>";
        //print_r($data);
        //echo "</pre>";
    	// loop over data for the current parent_id
    	foreach($data[$parent_id] as $arr)
    	{
    
    		// output the comment and any other information
    		if ($arr['anonymous'] == 1){
    			$pre_hash = $arr['name']."3434292";
    					echo $indent ."<a href='profile.php?anonymous'><img src='site-data/avatars/sir.png' style='width: 30px; float: left; margin: 15px; border-radius: 30px;'></a>";
    						echo "<a href='profile.php?anonymous' title='This user is in anonymous mode so cannot be seen'>Anonymous [hash ID: usranon".substr(md5($pre_hash), 0, -10)."</a><br>";
    
    				}else{
    							echo $indent ."<a href='profile.php?name={$arr['name']}'><img src='site-data/avatars/{$arr['avatar']}' style='width: 30px; float: left; margin: 15px; border-radius: 30px;'></a>";
    								echo "<a href='profile.php?name={$arr['name']}'>{$arr['name']}</a><br>";
    
    				}
    
    
    
    		echo "<b><p style='font-family: Arial, Helvetica, sans-serif;'>$indent{$arr['content']}</p></b>";
    		// determine and output any child count
    		$count = isset($data[$arr['comment_id']]) ? count($data[$arr['comment_id']]) : 0;
    		$pl = $count == 0 || $count > 1 ? 'ies' : 'y';
    		echo "<br>$indent$count Repl$pl<br>";
    		// allow a comment for the current parent
    		// you would probably want to use a javascript 'show' operation for this
    		?>
            <p>
            <?php echo $indent ?><button class="button" onclick="myFunction('button<?=$arr['comment_id']?>')">Reply</button>
            <div id="button<?=$arr['comment_id']?>" class="generalclass"  style="display:none;">
    		<form method="post">
    		<input type='hidden' name='parent_id' value='<?=$arr['comment_id']?>'>
    		<?=$indent?><label>Comment:<br> 
    		<?=$indent?><textarea name="comment" rows="4" cols="50" placeholder="remember to be polite!"></textarea></label>
    		<input type="submit"> <a href="includes/emojis.php"
       onclick="window.open(this.href,'targetWindow',
                                       `toolbar=no,
                                        location=no,
                                        status=no,
                                        menubar=no,
                                        scrollbars=yes,
                                        resizable=yes,
                                        width=300px;,
                                        height=500px`);
     return false; style='float: right; padding-left: 30px;'">Show emojissszz</a>
    <?php
    
    ?>
    <?php 
    // bottom
    if ($anon_comment== "1"){
    ?>
     <span style="color: black">Post as anonymous?</span> <input type="checkbox" id="anon" name="anon" value="set" checked>
    <?php
    } elseif($anon_comment == "2" ) {
    	?>
     <span style="color: black">Post as anonymous?</span> <input type="checkbox" id="anon" name="anon" value="set">
    	<?php
    }
    ?>
    		</form>
    		
     <br>
            </div>
    		<?php
    		// recurse if there are children of the current parent
    		if(isset($data[$arr['comment_id']]))
    		{
    			list_comments($arr['comment_id'], $data, $level+1);
    		}
    	}
    } 
    
    // html
    ?>
    
    <?php
    // display any errors
    if(!empty($errors))
    {
    	echo implode('<br>',$errors);
    }
    ?>
    
    <?php
    if( $_SESSION["loggedin"] != true){
    
    	echo "This category/board comment system is set to private. You must register/login and join to take part. Click <u><a href='login.php'>here</a></u> to login to your account or to register.</div>";
    	include 'footer.php';
    	exit();
    }
    
    
    // allow a comment on the main article
    ?>
    
    
    <form method="post">
    <input type='hidden' name='parent_id' value='0'>
    <label>Comment:<br>
    <textarea name="comment" rows="4" cols="50" placeholder="remember to be polite!" style="border-color: grey; width: 97%;"><?=$post['content']??''?></textarea></label><br>
    
    
    
    <input type="submit"><br>
    
     <a href="includes/emojis.php"
       onclick="window.open(this.href,'targetWindow',
                                       `toolbar=no,
                                        location=no,
                                        status=no,
                                        menubar=no,
                                        scrollbars=yes,
                                        resizable=yes,
                                        width=300px;,
                                        height=500px`);
     return false; style='float: right; padding-left: 50px;'">Show emojis</a><br>
    <?php 
    // top
    if ($anon_comment== "1"){
    ?>
     <span style="color: black">Post as anonymous?</span> <input type="checkbox" id="anon" name="anon" value="set" checked>
    <?php
    } elseif($anon_comment == "0") {
    	?>
     <span style="color: black">Post as anonymous?</span> <input type="checkbox" id="anon" name="anon" value="set">
    	<?php
    }
    ?>
    </form><br>
    
    <div style="overflow-y: scroll; height:400px; border: 1px dashed grey; padding: 30px; margin-right: 30px; border-radius: 10px; ">
    
    
    
    <?php
    if( $_SESSION["loggedin"] == true){
    if($count == 0){
        echo "No comments";
    }
    }
    ?>
    
    
    <?php
    // list comments, starting with parent 0
    list_comments(0, $comment_data, 0);
    
    ?>
    </div>
    
    <script>
    function myFunction(divid) {
    
      var x = document.getElementById(divid);  
      
      if (x.style.display == "none") 
      {
        x.style.display = "block";
      } 
      else {
        x.style.display = "none";
      }  
    }
    </script><br><br>
    

    It should be an anonymous checkbox to allow users to choose if they want to submit anonymously based on a flag stored in the DB - "cooment_anon" which can be true or false (0/1). But the decloration isnt working using the code in he first example, despite it being the same. Strange it should work on one but not the other.

     

    Tried pasting [this bellow] in other possible locations as a hack, but never worked :S

    $stmt = $pdo->prepare("SELECT cooment_anon FROM `users` WHERE user_id = ?");
    $stmt->execute([$_SESSION['the_usr_id']]); 
    $is_anon_set = $stmt->fetch();

    PS: By "box" i mean the initial comment box and the reply comment boxes. 

  2. How would that look like? Cant seem to get it to work.. tried this:

    Quote

    SELECT *, MATCH(terms) AGAINST(?) + MATCH(title) AGAINST(?) + MATCH(url) AGAINST(?) as `rank` FROM links  WHERE MATCH(terms) AGAINST(?) OR MATCH(title) AGAINST(?) OR MATCH(url) AGAINST(?) AND (MATCH(terms) AGAINST(?) + MATCH(title) AGAINST(?) + MATCH(url) AGAINST(?)) > 6  GROUP BY title ORDER BY `rank` DESC LIMIT 34

    but get "Fatal error: Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number " error..

  3. Hey. This is my query...

    SELECT *, MATCH(terms) AGAINST(?) + MATCH(title) AGAINST(?) + MATCH(url) AGAINST(?) as `rank` FROM links  WHERE MATCH(terms) AGAINST(?) OR MATCH(title) AGAINST(?) OR MATCH(url) AGAINST(?)  GROUP BY title ORDER BY `rank` DESC LIMIT 34

    It works on its own, but i want to limit the "rank" to being a number of 5 only ... so basically i added

    Quote

     AND `rank` > 6

    though that didnt work...and i got this error..

    Quote

    Fatal error: Uncaught PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'rank' in 'where clause' in

    How would I go about doing this?

     

    Thanks.

  4. Cleaned up the errors.. and deleted the content of coloumodes.php, changed it around abit and re placed it in the page... Worked without it so just had to fix it up.

     

    Anyway, since following the error it became clear! But with the help you you guys gizmola and ginerjm. So much thanks for your advice. 

    PS: cant believe i didn't know about error reporting, never used it before and makes me feel more secure now.

    :thumb-up:

     

    Going to sleep now, at it all day and has been like 10 hours.. lucky i can go to bed with a clear mind. Again, thanks ginerjm and gizmola :) 

     

  5. Whey. Seems like something is happening...

    Oky doky. Cookies seem to be working now.. could  I ask of another question, does anyone know what this Error message could suggest: (once I've logged in and sent to the dashboard). I've cleaned a fair few today but cannot solve this alone seemingly ..

     

    1447690790_Screenshotfrom2022-12-1622-23-44.png.facb593a3e8060e7d1186ca2b2431715.png

    _________

    ginerjm.. I'm still getting this result even when cookies have indeed been set.

    1617867883_Screenshotfrom2022-12-1622-15-00.png.ccbb3507557222a01b5e3788b986fe68.png

     

    @ ginerjmoh...

    And i define the cookie twice as it stops me needing to refresh the page for the cookie to be set. A hack i got from someone on SO,.

  6. Just tried with seven parameters (max all) based on the manual..

    function setRememberMeToken($pdo, $user_id) {
        $token = bin2hex(random_bytes('25'));
    
        $expirationDate = time() + (86400 * 7); // <-- 7 days later (make sure your comments are accurate)
        setcookie("token", $token, $expirationDate, '/', 'localhost', true, true);
        $test = true;
    
        $to = date('Y-m-d', $expirationDate);
    
        $sql = "INSERT INTO `user_token` (`user_id`, `expires`, `tokenHash`) VALUES (?, ?, ?);";
        $stmt= $pdo->prepare($sql);
        $stmt->execute([$user_id, $to, sha1($token)]);
        //echo "test----------------";
    
            if (!setcookie("token", $token, $expirationDate, "/"))
        {
            echo "Could not set cookie for $token using $expirationDate - aborting";
           // exit();
        } else {
            echo "Setcookie ran ok";
        }
    //    if (isset($_COOKIE['tip3']))
     //       echo "<br>good cookie";
    //    if (isset($_COOKIE["token"]))
    //        echo "<br>good cookie2";
    
    }

    Still getting errors. As you can see I'm using your testing method.

    Screenshot from 2022-12-16 21-38-33.png

  7. Sorry about the late reply, i have just spent ages solving the other error messages dotted all over my site and had a mental health issue before .. but feeling good and stable now.

    Like i suggested i added this config...

    Quote

     error_reporting(E_ALL); 

    ini_set('display_errors', '1');

    and got these results which i think are relative .. 

    233204_Screenshotfrom2022-12-1621-04-52.png.c558a80cf8e034056706f21b6b2cfa8b.png

     

    Current code [remember_token.php]:

    <?php
     function setRememberMeToken($pdo, $user_id) {
        $token = bin2hex(random_bytes('25'));
    
        $expirationDate = time() + (86400 * 7); // <-- 7 days later (make sure your comments are accurate)
        setcookie('token', $token, $expirationDate, "/");
        //$_COOKIE['token'] = $token;
        $test = true;
    
        $to = date('Y-m-d', $expirationDate);
    
        $sql = "INSERT INTO `user_token` (`user_id`, `expires`, `tokenHash`) VALUES (?, ?, ?);";
        $stmt= $pdo->prepare($sql);
        $stmt->execute([$user_id, $to, sha1($token)]);
        //echo "test----------------";
    
            if (!setcookie('token', $token, $expirationDate, "/"))
        {
            echo "Could not set cookie for $token using $expirationDate - aborting";
           // exit();
        } else {
            echo "Setcookie ran ok";
        }
        if (isset($_COOKIE['tip3']))
            echo "<br>good cookie";
        if (isset($_COOKIE['token']))
            echo "<br>good cookie2";
    
    }
    
    
    function getRememberMeCheck($pdo) {
        $stmt = $pdo->prepare("
        SELECT users.name, users.user_id
        FROM user_token, users 
        WHERE 
            tokenHash = ? 
            AND expires > NOW()
            AND users.user_id = user_token.user_id
        ");
        $stmt->execute([sha1($_COOKIE['token'])]); 
        $db_query = $stmt->fetch();
        
        if (!$db_query){
            return false;
        }
    
    
        $_SESSION["loggedin"] = true;
        $_SESSION["username"] = $db_query['name'];
        $_SESSION["the_usr_id"] = $db_query['user_id'];
        $_SESSION["userID"]  = $db_query['user_id']; // ADDED DUE TO DESCRIPTION ("PROB WILL BE OK")
        return true;
    }
    
    
    
    
    
    function isRemembered() {
        return isset($_COOKIE['token']);
    }
    ?>

    Current code [login.php]:

    <?php
        $the_page = " - Login/ Register";
    
         session_start();
        include 'includes/top_bottom/header.php';
    
        if((isset($_SESSION["loggedin"]) &&  $_SESSION["loggedin"] == true) && (isset($_SESSION["username"]))) {
                //header('Location: dash.php');
            }
    
    $base = basename(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_PATH));
    ?>
    
    
            <center>
    <?php include 'includes/logo.php'; ?><!--<img src="mark.png" alt="beta project" width="80px;" style="margin-left: -184px; margin-bottom: 150px;">--><br>
    
    <h2>Login/ register</h2>
    <?php
    
    if($_SERVER["REQUEST_METHOD"] == "POST"){
        $username = trim($_POST["username"]);
        $password = trim($_POST["password"]);
    
        // Check if username is empty
        if(empty(trim($_POST["username"]))){
            echo $username_err = "<span id='notification'>Please enter username.</span> ";
        } else{
            $username = trim($_POST["username"]);
        }
        
        // Check if password is empty
        if(empty(trim($_POST["password"]))){
            echo $password_err = "<span id='notification'>Please enter your password.</span> ";
        } else{
            $password = trim($_POST["password"]);
        }
        // continue...
        if(empty($username_err) && empty($password_err)){
            $sql = "SELECT user_id, name, password, active FROM users WHERE name = ?";
            $result = $pdo->prepare($sql);
            $result->bindParam(1, $_POST["username"]);
            $result->execute();
            $user = $result->fetch();
    
            if(!password_verify($_POST['password'], $user['password'])){
                echo "<span id='notification'>Invalid username/password.</span> ";
            }  else {
                if($user['active'] == '1') {
                  $_SESSION["loggedin"] = true;
                  $_SESSION["username"] = $_POST["username"];
                  $_SESSION["userID"] = $user['user_id'];
                  // cookie stuff
                  if (isset($_POST['remember-me'])){
                    echo setRememberMeToken($pdo, $user['user_id']); // <----- set token
                    echo "<--woo";
                  }
      
                  echo "Hey ".$_SESSION["username"].". You are Logged in, redirecting in a moment or click <a href='dash.php'>here</a> to be taken to your dashboard.";
                  //header("location:loggingin.php?id=true");
                  include 'includes/top_bottom/footer.php';
                  exit();
              }else {
                echo "User not active.";
              }
            }
        }
    }
             

    :)

     

  8. Both set but no errors when "logging in" aka "setRememberMeToken"...

    [whole functions]

    <?php
    
    // https://forums.phpfreaks.com/topic/315262-php-cookies-and-session-data-expiring-at-different-times/
    function setRememberMeToken($pdo, $user_id) {
        //$length wasn't a great name and is an unnecessary variable.
        $token = bin2hex(random_bytes('25'));
    
        $expirationDate = time() + (86400 * 7); // <-- 7 days later (make sure your comments are accurate)
        //setcookie("token", $token, $expirationDate, "/");
        setcookie("token", $token, time() + (86400 * 30)); // 86400 = 1 day
    
        $_COOKIE["token"] = $token;
        $test = true;
    
        //$_COOKIE['remember'] is unnecessary, just get rid of it
        //--deleted
    
        //You calculated your expiration timestamp above already, no need to do it again.
        $to = date('Y-m-d', $expirationDate);
    
        //Assuming token_id is an auto increment column, you can just omit it from the insert.
        $sql = "INSERT INTO `user_token` (`user_id`, `expires`, `tokenHash`) VALUES (?, ?, ?);";
        $stmt= $pdo->prepare($sql);
        $stmt->execute([$user_id, $to, sha1($token)]);
        //echo "test----------------";
    
            if (!setcookie("token", $token, $expirationDate))
        {
            echo "Could not set cookie for $token using $expirationDate - aborting";
            exit();
        } else {
            echo "Setcookie ran ok";
        }
    
    
    }
    
    
    function getRememberMeCheck($pdo) {
        //I find spacing out your queries makes them easier to read and understand.
        $stmt = $pdo->prepare("
        SELECT users.name, users.user_id
        FROM user_token, users 
        WHERE 
            tokenHash = ? 
            AND expires > NOW()
            AND users.user_id = user_token.user_id
        ");
        $stmt->execute([sha1($_COOKIE["token"])]); 
        $db_query = $stmt->fetch();
        
        //Your token and expiration date are validated as part of the query
        //All you need to do is check if you got a result or not.
        if (!$db_query){
            //If you didn't get a result, either the token is invalid or it has expired.
            //header("location: login.php");
            return false;
        }
    
    
        //Otherwise, if you did get a result, the token is valid.
        $_SESSION["loggedin"] = true;
        $_SESSION["username"] = $db_query['name'];
        $_SESSION["the_usr_id"] = $db_query['user_id'];
        $_SESSION["userID"]  = $db_query['user_id']; // ADDED DUE TO DESCRIPTION ("PROB WILL BE OK")
        return true;
    }
    
    
    
    //This method seems to just be a copy of the method above, why does it exist?
    //The only difference is $_SESSION["loggedin"] = true; which you could just do above.
    //function setSessionVarables($pdo) {
    //...
    //}
    //--deleted
    
    
    function isRemembered() {
        //Instead of a separate remember cookie, just check if the token cookie exists.
        //if ($whatever){ return true; } else { return false} can be simplified to just return $whatever
        return isset($_COOKIE['token']);
    }
    ?>

    Sorry Ginerjm, just having been doing it that long (PHP).

  9. :thumb-up:

    <?php
       include '../includes/config.php';
    function setRememberMeToken($pdo, $user_id) {
        $token = bin2hex(random_bytes('25'));
    
        $expirationDate = time() + (86400 * 7); // <-- 7 days later (make sure your comments are accurate)
        setcookie("token", $token, $expirationDate, "/");
        echo $_COOKIE["token"] = $token;
        $test = true;
    
        $to = date('Y-m-d', $expirationDate);
    
        $sql = "INSERT INTO `user_token` (`user_id`, `expires`, `tokenHash`) VALUES (?, ?, ?);";
        $stmt= $pdo->prepare($sql);
        $stmt->execute([$user_id, $to, sha1($token)]);
    
        if (!setcookie("token", $token, $expirationDate, "/"))
        {
            echo "Could not set cookie for $token using $expirationDate - aborting";
            exit();
        }
    }
    setRememberMeToken($pdo, 1);
    echo "<br>";
    
    ?>

    [test file]

    &&

    <?php
    // https://forums.phpfreaks.com/topic/315262-php-cookies-and-session-data-expiring-at-different-times/
    function setRememberMeToken($pdo, $user_id) {
        //$length wasn't a great name and is an unnecessary variable.
        $token = bin2hex(random_bytes('25'));
    
        $expirationDate = time() + (86400 * 7); // <-- 7 days later (make sure your comments are accurate)
        setcookie("token", $token, $expirationDate, "/");
        //$_COOKIE["token"] = $token;
        $test = true;
    
        //$_COOKIE['remember'] is unnecessary, just get rid of it
        //--deleted
    
        //You calculated your expiration timestamp above already, no need to do it again.
        $to = date('Y-m-d', $expirationDate);
    
        //Assuming token_id is an auto increment column, you can just omit it from the insert.
        $sql = "INSERT INTO `user_token` (`user_id`, `expires`, `tokenHash`) VALUES (?, ?, ?);";
        $stmt= $pdo->prepare($sql);
        $stmt->execute([$user_id, $to, sha1($token)]);
        echo "test----------------";
    
            if (!setcookie("token", $token, $expirationDate, "/"))
        {
            echo "Could not set cookie for $token using $expirationDate - aborting";
            exit();
        }
    
    
    }
    
    
    function getRememberMeCheck($pdo) {
        //I find spacing out your queries makes them easier to read and understand.
        $stmt = $pdo->prepare("
        SELECT users.name, users.user_id
        FROM user_token, users 
        WHERE 
            tokenHash = ? 
            AND expires > NOW()
            AND users.user_id = user_token.user_id
        ");
        $stmt->execute([sha1($_COOKIE["token"])]); 
        $db_query = $stmt->fetch();
        
        //Your token and expiration date are validated as part of the query
        //All you need to do is check if you got a result or not.
        if (!$db_query){
            //If you didn't get a result, either the token is invalid or it has expired.
            //header("location: login.php");
            return false;
        }
    
    
        //Otherwise, if you did get a result, the token is valid.
        $_SESSION["loggedin"] = true;
        $_SESSION["username"] = $db_query['name'];
        $_SESSION["the_usr_id"] = $db_query['user_id'];
        $_SESSION["userID"]  = $db_query['user_id']; // ADDED DUE TO DESCRIPTION ("PROB WILL BE OK")
        return true;
    }
    
    
    
    //This method seems to just be a copy of the method above, why does it exist?
    //The only difference is $_SESSION["loggedin"] = true; which you could just do above.
    //function setSessionVarables($pdo) {
    //...
    //}
    //--deleted
    
    
    function isRemembered() {
        //Instead of a separate remember cookie, just check if the token cookie exists.
        //if ($whatever){ return true; } else { return false} can be simplified to just return $whatever
        return isset($_COOKIE['token']);
    }
    ?>

    [functions]

     

     

  10. 20 minutes ago, ginerjm said:

    If you looked at the Official PHP Manual you would get the true way to use it.   W3schools?  Nah...

    You should be using:

    if (setcookie(.......))

    ok

    else

       not ok

    Ah. that's neat.  Also, could you point me to any code which says this is the best method, I cannot see it used in the manual for "setcookie" :confused:

     

    But getting a false now even when set ,... and i don't think it has to do with the cookie not being present.

    if (setcookie('token')){
        echo $_COOKIE['token'];
    } else {
        echo "false";
    }

     

  11. Oh, and the unusual thing, which i'll mention again because i think it's important is that if i run this code it  gives me a cookie (aka "token") which preserves when i restart browser..

    <?php
       include '../includes/config.php';
    function setRememberMeToken($pdo, $user_id) {
        //$length wasn't a great name and is an unnecessary variable.
        $token = bin2hex(random_bytes('25'));
    
        $expirationDate = time() + (86400 * 7); // <-- 7 days later (make sure your comments are accurate)
        setcookie("token", $token, $expirationDate, "/");
        echo $_COOKIE["token"] = $token;
        $test = true;
    
        //$_COOKIE['remember'] is unnecessary, just get rid of it
        //--deleted
    
        //You calculated your expiration timestamp above already, no need to do it again.
        $to = date('Y-m-d', $expirationDate);
    
        //Assuming token_id is an auto increment column, you can just omit it from the insert.
        $sql = "INSERT INTO `user_token` (`user_id`, `expires`, `tokenHash`) VALUES (?, ?, ?);";
        $stmt= $pdo->prepare($sql);
        $stmt->execute([$user_id, $to, sha1($token)]);
    }
    setRememberMeToken($pdo, 1);
    echo "<br>";
    
    ?>

    But cannot get it to work in the login.. could someone help or give me a write up/ suggestion. :)

    Edit: this is run in a separate experimental file and seems make things work-ish.

    Also, the $user_id is set to "1" for testing, normally this will be a value selected from the DB!

     

    Though: 

    • cannot get it to work by placing the code directly in the login system
    • etc.
  12. I want the cookie to be set so that the user is remembered once the browser is reopened. Currently it does not. The cookie vanished when I restart. 

    I use the code 

    Quote

         if (isset($_COOKIE['token'])) { getRememberMeCheck($pdo); }

    (header.php)

    .. at the top of each header to include the functions. 

    and the code..

    Quote

    setRememberMeToken($pdo, $user['user_id']);

    .. is run when the user logs in..

    the function points to .. ( "  include 'includes/remember_token.php';  ")

    <?php
    // https://forums.phpfreaks.com/topic/315262-php-cookies-and-session-data-expiring-at-different-times/
    function setRememberMeToken($pdo, $user_id) {
        //$length wasn't a great name and is an unnecessary variable.
        $token = bin2hex(random_bytes('25'));
    
        $expirationDate = time() + (86400 * 7); // <-- 7 days later (make sure your comments are accurate)
        setcookie("token", $token, $expirationDate, "/");
        //$_COOKIE["token"] = $token;
        $test = true;
    
        //$_COOKIE['remember'] is unnecessary, just get rid of it
        //--deleted
    
        //You calculated your expiration timestamp above already, no need to do it again.
        $to = date('Y-m-d', $expirationDate);
    
        //Assuming token_id is an auto increment column, you can just omit it from the insert.
        $sql = "INSERT INTO `user_token` (`user_id`, `expires`, `tokenHash`) VALUES (?, ?, ?);";
        $stmt= $pdo->prepare($sql);
        $stmt->execute([$user_id, $to, sha1($token)]);
        echo "test";
    }
    
    
    function getRememberMeCheck($pdo) {
        //I find spacing out your queries makes them easier to read and understand.
        $stmt = $pdo->prepare("
        SELECT users.name, users.user_id
        FROM user_token, users 
        WHERE 
            tokenHash = ? 
            AND expires > NOW()
            AND users.user_id = user_token.user_id
        ");
        $stmt->execute([sha1($_COOKIE["token"])]); 
        $db_query = $stmt->fetch();
        
        //Your token and expiration date are validated as part of the query
        //All you need to do is check if you got a result or not.
        if (!$db_query){
            //If you didn't get a result, either the token is invalid or it has expired.
            //header("location: login.php");
            return false;
        }
    
    
        //Otherwise, if you did get a result, the token is valid.
        $_SESSION["loggedin"] = true;
        $_SESSION["username"] = $db_query['name'];
        $_SESSION["the_usr_id"] = $db_query['user_id'];
        $_SESSION["userID"]  = $db_query['user_id']; // ADDED DUE TO DESCRIPTION ("PROB WILL BE OK")
        return true;
    }
    
    
    
    //This method seems to just be a copy of the method above, why does it exist?
    //The only difference is $_SESSION["loggedin"] = true; which you could just do above.
    //function setSessionVarables($pdo) {
    //...
    //}
    //--deleted
    
    
    function isRemembered() {
        //Instead of a separate remember cookie, just check if the token cookie exists.
        //if ($whatever){ return true; } else { return false} can be simplified to just return $whatever
        return isset($_COOKIE['token']);
    }
    ?>

    .. which contains all the necessary functions. Though these do not work for some reason, no cookies is preserved...

    , help me.

     

    PS: the getRememberMeCheck should preserve cookies to sessions.

  13. <?php
    // https://forums.phpfreaks.com/topic/315262-php-cookies-and-session-data-expiring-at-different-times/
    function setRememberMeToken($pdo, $user_id) {
        //$length wasn't a great name and is an unnecessary variable.
        $token = bin2hex(random_bytes('25'));
    
        $expirationDate = time() + (86400 * 7); // <-- 7 days later (make sure your comments are accurate)
        setcookie("token", $token, $expirationDate, "/");
        //$_COOKIE["token"] = $token;
        $test = true;
    
        //$_COOKIE['remember'] is unnecessary, just get rid of it
        //--deleted
    
        //You calculated your expiration timestamp above already, no need to do it again.
        $to = date('Y-m-d', $expirationDate);
    
        //Assuming token_id is an auto increment column, you can just omit it from the insert.
        $sql = "INSERT INTO `user_token` (`user_id`, `expires`, `tokenHash`) VALUES (?, ?, ?);";
        $stmt= $pdo->prepare($sql);
        $stmt->execute([$user_id, $to, sha1($token)]);
        echo "test";
    }
    
    
    function getRememberMeCheck($pdo) {
        //I find spacing out your queries makes them easier to read and understand.
        $stmt = $pdo->prepare("
        SELECT users.name, users.user_id
        FROM user_token, users 
        WHERE 
            tokenHash = ? 
            AND expires > NOW()
            AND users.user_id = user_token.user_id
        ");
        $stmt->execute([sha1($_COOKIE["token"])]); 
        $db_query = $stmt->fetch();
        
        //Your token and expiration date are validated as part of the query
        //All you need to do is check if you got a result or not.
        if (!$db_query){
            //If you didn't get a result, either the token is invalid or it has expired.
            //header("location: login.php");
            return false;
        }
    
    
        //Otherwise, if you did get a result, the token is valid.
        $_SESSION["loggedin"] = true;
        $_SESSION["username"] = $db_query['name'];
        $_SESSION["the_usr_id"] = $db_query['user_id'];
        $_SESSION["userID"]  = $db_query['user_id']; // ADDED DUE TO DESCRIPTION ("PROB WILL BE OK")
        return true;
    }
    
    
    
    //This method seems to just be a copy of the method above, why does it exist?
    //The only difference is $_SESSION["loggedin"] = true; which you could just do above.
    //function setSessionVarables($pdo) {
    //...
    //}
    //--deleted
    
    
    function isRemembered() {
        //Instead of a separate remember cookie, just check if the token cookie exists.
        //if ($whatever){ return true; } else { return false} can be simplified to just return $whatever
        return isset($_COOKIE['token']);
    }
    ?>

    - Ginerjm, is this you mean?

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.