简体   繁体   中英

Verify existence of an element in a database table in a web site based with restful service

I have a web site based with restful service, my problem is the verify of existence of the user autentication token situated in the localstorage of the browser using html5.

I use jQuery to pass the token from client to server to verify if the token exist, but if the token exist or not, the http status code returned is ever 200, I don't understand why.

My code for this work is divided in two page: one for the client and one for the server.

Home.html

<script type="text/javascript">

//other code 

 $(document).ready(function(){
    localStorage.getItem("tokenMyWebSite");
    document.getElementById("tokenhtml").innerHTML = localStorage.getItem("tokenMyWebSite");

    if (localStorage.getItem("tokenMyWebSite") === null) {
      window.location.replace("index.html");
    } else {
      var token = localStorage.getItem("tokenMyWebSite");
      $.ajax( {
        url: 'verify.php',
        method: 'GET',
        data: {
          token: token,     /* (backend): (frontend)*/
        },

        error:function(response){
          // Simulate an HTTP redirect:
          alert("Token is not present in database");
          //localStorage.removeItem("tokenListenMe"); 
          //window.location.replace("index.html");
        }
      });
    }
 });

    //other code

</script>

verify.php

<?php

  require ("debug.php");

  $conn = new mysqli('localhost', 'root', '', 'MyWebSite');

  $token = $conn->real_escape_string($_GET["token"]);

  $sql = $conn->query("SELECT token FROM credenziali where token = '$token' LIMIT 1");

  if (!$sql) {
    http_response_code(404);
    die(mysqli_error());
  }

  if(mysql_fetch_array($sql) !== false) {
    http_response_code(200); 
  } else {
    http_response_code(404);
  }

  mysqli_close($conn);

?>

You're mixing mysqli with mysql (deprecated). Note the lack of i here:

if(mysql_fetch_array($sql) !== false) {

Change that to mysqli_fetch_array and !== false to !== null (becuase mysqli_fetch_array() returns null, not false, on failure) and you should be good.

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