简体   繁体   中英

Having problems comparing strings (PHP)

My goal is to check if the value of the "token" stored in a cookie is the same as the value in the loginTable table in the db. I am able to save the value of the cookie in the variable $token. The problem I have is here --> if ($row["token"] == $token). For example the value of the $token is bm0h8sdigs and the value in the row is bm0h8sdigs, but it does not enter the if. I also tried strcmp function but it didn't work. if(strcmp($row["token"], $token) == 0) I also tried $sqlToken = "select * from loginTable where token='" . $token . "'"; but it does not work.

echo $token; prints what is in my cookie - bm0h8sdigs

<!-- https://github.com/js-cookie/js-cookie This is a library to make handling cookies easier -->
<script>
   var token = Cookies.get('token');
</script>

<?php
   $token = "<script>document.write(token)</script>";

   $var = 0;
   include "connectDB.php";
                                
   $sqlToken = "SELECT * FROM loginTable";
   $resultToken = $mysqli->query($sqlToken);

   while($row = $resultToken->fetch_assoc()){
        if ($row["token"] == $token){
            $var = 1;
        }
   }
   $mysqli->close();
                                
   if ($var == 1){
   //Token found in db
   }
   else{
   //Token not found in db
   }
?>

connectDB.php

<?php
    $host = "localhost";
    $username = "root";
    $password = "usbw";
    $database = "test";

    $mysqli = new mysqli($host, $username, $password, $database);
    $mysqli -> set_charset("utf8");

    if ($mysqli->connect_errno) {
        echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error; 
    }
?>

loginTable - prnt.sc/u7nidn

Create table loginTable(
    loginID int AUTO_INCREMENT,
    userID int not null,
    token varchar(20) not null,
    Constraint PK_loginTable Primary Key(loginID),
    Constraint FK_loginTable_userID Foreign Key (userID) References usersTable (userID)
)

The example you provided shows that $token holds the value <script>document.write(token)</script>; Of course comparison will fail then.

Your approach of passing the javascript variable to php will not work. php has no acces to the javascript scope. Try passing your variable via form submit or try to access the cookie values directly in php, via $_COOKIE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM