Проверка, вошел ли пользователь в систему, не работает в другом файле. Почему? - PullRequest
0 голосов
/ 06 февраля 2020

Итак, я использую этот код, чтобы проверить, вошел ли пользователь в систему и работает ли он, но только в одном файле:

$.ajax({

    url: 'loginAndSingupAction.php',
    type: 'post',
    data: {
        'username': username,
        'password': password,
        'action': 'login'
    },
    success: function(data) {
        console.log(data);
        if (data == 1) {
            alert("hi")
            $("#msg").text('Login efetuado com sucesso');
            setTimeout(function() {
                window.location.href = 'inicio'
            }, 2000);
        } else {
            alert("bye");
            $("#msg").text('credenciais inválidas');

        }
    }
});

Это полный файл, над которым работает приведенный выше код, и выдает предупреждение ( "Привет"). «login. php» (⬆️ приведенный выше код):

<?php
session_start();
if (isset($_SESSION['ip'])) {
    $ip = $_SESSION['ip'];
    //header("Location: index.php"); 
}
?>
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Felinefi</title>
    <script src="https://kit.fontawesome.com/3da1a747b2.js"></script>
    <link href="https://fonts.googleapis.com/css?family=Catamaran&display=swap" rel="stylesheet">

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
    <link rel="icon" href="upload/felinefilogo.png">
    <link rel="stylesheet" href="package/dist/sweetalert2.min.css">
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="style_new.css">
    <!-- css files imported inside style.css are: styles.css and simplelightbox.min.css -->
    <!-- <link rel="stylesheet" type="text/css" href="semantic/dist/semantic.min.css"> -->

</head>

<body>
    <div class="container" id="navmobile" style="display: none">
        <img src="upload\felinefilogo.svg" style="margin-top: 1rem" height="100px" width="250px" alt="">
        <img src="upload\felinefi.svg" height="20px" width="62.5px" alt="">
        <nav class="navbar" style="padding: 0; margin-right: 16px">
            <ul class="nav">
                <li><a href='inicio'>Início</a></li>
                <li><a href="#">Sobre</a></li>
                <li><a href='contato'>Contato</a></li>
                <li><a href='carrinho' display="none" class="nav-item nav-link active">
                        <h5 class="px-5 cart" style="display: flex;">
                            &nbsp;Carrinho&nbsp;
                            <span id="cart-item" class="cart-item text-warning bg-light"></span> &nbsp;
                            <i class="fas fa-shopping-cart fa-flip-horizontal" aria-hidden="true"></i>
                        </h5>
                    </a></li>
                </li>
            </ul>
        </nav>
    </div>
    <nav class="navbar" id="navdesktop">
        <div class="container">
            <div class="imagem"><img src="upload\felinefihorizontalmedium.svg" height="100px" width="250px" alt="">
            </div>
            <ul class="nav">
                <li><a href='inicio'>Início</a></li>
                <li><a href="#">Sobre</a></li>
                <li><a href="contato">Contato</a></li>
                <li><a href='carrinho' display="none" class="nav-item nav-link active">
                        <h5 class="px-5 cart" style="display: flex;">
                            &nbsp;Carrinho&nbsp;
                            <span id="cart-item" class="cart-item text-warning bg-light"> </span> &nbsp;
                            <i class="fas fa-shopping-cart fa-flip-horizontal" aria-hidden="true"></i>
                        </h5>
                    </a></li>
                </li>
            </ul>
        </div>
    </nav>

    <body>
        <div class="cont">
            <p style='text-align: center !important;' id='msg' class='text-center'></p>
            <div class="form">
                <form>
                    <h1 style='text-align:center' class='text-center'>Entrar</h1>
                    <div class='form-group'>
                        <input require type="text" id="user" class='form-control' placeholder="Nome de usuário ou Email" />
                        <div id='uerr' class="errors"></div>
                    </div>
                    <div class='form-group'>
                        <input require type="password" id="pass" class='form-control' placeholder="Senha" />
                        <div id='perr' class="errors"></div>
                    </div>

                    <button type="button" onClick='login()' class="login">Entrar</button>
                    <div class='signupbotom'>
                        <a href='cadastro' class='pull-left'>Clique aqui para criar sua conta antes de entrar</a>
                    </div>
                </form>
            </div>
        </div>


        <script>
            function login() {
                var username = $('#user').val();
                var password = $('#pass').val();

                if (username == '') {

                    $('#uerr').text('Campo é obrigatório');
                } else if (password == '') {
                    $('#perr').text('Campo é obrigatório');
                } else {

                    $.ajax({

                        url: 'loginAndSingupAction.php',
                        type: 'post',
                        data: {
                            'username': username,
                            'password': password,
                            'action': 'login'
                        },
                        success: function(data) {
                            console.log(data);
                            if (data == 1) {
                                alert("hi")
                                $("#msg").text('Login efetuado com sucesso');
                                setTimeout(function() {
                                    window.location.href = 'inicio'
                                }, 2000);
                            } else {
                                alert("bye");
                                $("#msg").text('credenciais inválidas');

                            }
                        }
                    });
                }
            }

            $(document).ready(function() {
                if ($(this).width() < 500) {
                    $('#navdesktop').hide();
                    $('#navmobile').show();
                } else if ($(this).width() > 500) {
                    $('#navmobile').hide();
                    $('#navdesktop').show();
                }
            });
            //a condição surte efeito apenas quando mexe na "responsividade" da página.
            $(window).resize(function() {
                if ($(this).width() < 500) {
                    $('#navdesktop').hide();
                    $('#navmobile').show();
                } else if ($(this).width() > 500) {
                    $('#navmobile').hide();
                    $('#navdesktop').show();
                }
            });
        </script>
    </body>

</html>

Но когда я использую этот же код для индекса. php, он не выдает предупреждение («привет»), когда пользователь входит в систему. в. Работает только оповещение ("пока"). Почему? И как я могу это исправить?

вот индекс. php файл с включенным кодом (мне очень жаль, если файл слишком длинный, я обрезал до максимально возможного):

  <?php
    ini_set('display_errors', 0);
    if (empty($_SESSION)) {
        @session_start();
    } /**/

    if (isset($_SESSION['ip'])) {
        $ip = $_SESSION['ip'];
    }


    if (isset($_GET['action']) && $_GET['action'] == 'logout') {

        //unset($ip);
        // header('Location:logout.php');

    }

    ?>
  <!DOCTYPE html>
  <html lang="en">

  <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Felinefi</title>
      <script src="https://kit.fontawesome.com/3da1a747b2.js"></script>
      <link href="https://fonts.googleapis.com/css?family=Catamaran&display=swap" rel="stylesheet">
      <link rel="icon" href="upload/felinefilogo.png">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/simplelightbox/1.17.3/simplelightbox.min.css">
      <link rel="stylesheet" href="style.css">

  </head>

  <body>
      <div class="container" id="navmobile" style="display: none">
          <?php if (!isset($ip)) { ?>
              <p><a href='login'>Login</a> | <a href='cadastro'>Cadastro</a></p>
          <?php } else { ?>
              <p><a href="index.php?action=logout">Sair</a></p>
          <?php } ?>
          </nav>
      </div>

      <nav class="navbar" id="navdesktop">

          <?php if (!isset($ip)) { ?>
              <li><a href='login'>Login</a> | <a href='cadastro'>Cadastro</a></li>
          <?php } else { ?>
              <li><a href="logout.php">Sair</a></li>
          <?php } ?>
      </nav>

      <div class="productViewBox">
          <div id="message"></div>
          <h3>TAPETE FELINEFI ANTI-SUJEIRA</h3>
          <div class="productViewBoxCloseBtn"><i class="fas fa-times"></i></div>
          <?php
            include 'config.php';
            $stmt = "SELECT * FROM product";
            //  print_r($stmt);exit;
            // $stmt->execute();
            $result = mysqli_query($conn, $stmt);
            //$result = $stmt->get_result();
            while ($row = mysqli_fetch_assoc($result)) :
            ?>
              <div class="tryingtoFlex">
                  <div class="productViewBoxImg">
                      <img src="<?= $row['product_image'] ?>">
                  </div>
              </div>
          <?php endwhile; ?>
      </div>
      <br>

      <!-- Product View Box / Quick Product View Start -->

      <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
      <!-- <script src="simplelightbox-master/dist/js/simple-lightbox.min.js"></script> -->
      <script src="https://cdnjs.cloudflare.com/ajax/libs/simplelightbox/1.17.3/simple-lightbox.min.js"></script>
      <script>
          $.ajax({
              url: "loginAndSingupAction.php",
              type: "post",
              data: {
                  username: username,
                  password: password,
                  action: "login"
              },
              success: function(data) {
                  console.log(data);
                  if (data == 1) {
                      alert("hi");
                      $("#msg").text("Login efetuado com sucesso");
                      setTimeout(function() {
                          window.location.href = "inicio";
                      }, 2000);
                  } else {
                      alert("bye");
                      $("#msg").text("credenciais inválidas");
                  }
              }
          });
          $(document).ready(function() {
              $(".addItemBtn").click(function(e) {
                  e.preventDefault();
                  var $form = $(this).closest(".form-submit");
                  var pid = $form.find(".pid").val();
                  var pname = $form.find(".pname").val();
                  var pprice = $form.find(".pprice").val();
                  var pimage = $form.find(".pimage").val();
                  var pcode = $form.find(".pcode").val();
                  $.ajax({
                      url: "action.php",
                      method: "post",
                      data: {
                          pid: pid,
                          pname: pname,
                          pprice: pprice,
                          pimage: pimage,
                          pcode: pcode
                      },
                      success: function(response) {
                          console.log(response);
                          if (response == 1) {
                              $("#message").html("Adicionado com sucesso");
                              load_cart_item_number();
                              location.href = location.href = "carrinho";
                          } else {
                              $("#message").html("");
                              location.href = location.href = "cadastro";
                          }
                      }
                  });
              });
              load_cart_item_number();

              function load_cart_item_number() {
                  $.ajax({
                      url: "action.php",
                      method: "get",
                      data: {
                          cartItem: "cart-item"
                      },
                      success: function(response) {
                          console.log(response);
                          $(".cart-item, #cart-item").html(response);
                      }
                  });
              }
          });
      </script>

  </body>

  </html>

loginAndSingupAction. php:

<?php
session_start();
require 'config.php';
if (isset($_POST['action']) && $_POST['action'] == 'signup') {

    $stmt1 = "SELECT * FROM users where username='" . $_POST['username'] . "'";
    $ret1 = mysqli_query($conn, $stmt1);
    $rowcount1 = mysqli_fetch_assoc($ret1);
    if (empty($rowcount1)) {


        $query = "INSERT INTO users (username, password, email, cpf)VALUES( '" . $_POST['username'] . "', '" . $_POST['password'] . "', '" . $_POST['email'] . "', '" . $_POST['cpf'] . "')";
        //echo $query;exit;
        echo  mysqli_query($conn, $query);
    } else {
        echo 'username already Exist';
    }
}


if (isset($_POST['action']) && $_POST['action'] == 'login') {


    $stmt = "SELECT * FROM users where (username='" . $_POST['username'] . "' || email='" . $_POST['username'] . "') and password= '" . $_POST['password'] . "' ";


    $ret = mysqli_query($conn, $stmt);
    $rowcount = mysqli_fetch_assoc($ret);
    if (empty($rowcount)) {
        echo 0;
    } else {

        $_SESSION['ip'] = $rowcount['id'];
        $_SESSION['user'] = $rowcount['username'];
        echo 1;
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...