Ir para conteúdo
Fórum Script Brasil
  • 0

Login incorreto


INous

Pergunta

Scripts de registro e login de usuário:

- registro usuário.php

- server.php

- login.php

O de registro de usuário está ok. Faz o registro no bd (mysql).

Mas quando faço login, não recconhece user/email já registrado.

login.php
<?php include('server.php') ?>
<!DOCTYPE html>
<html>
<head>
  <title>Login</title>
  <link rel="stylesheet" type="text/css" href="user_style.css">
</head>
<body>
  <div class="header">
  	<h2>Login</h2>
  </div>
	 
  <form method="post" action="login.php">
  	<?php include('errors.php'); ?>
  	<div class="input-group">
  		<label>Username</label>
  		<input type="text" name="user_name" >
  	</div>
  	<div class="input-group">
  		<label>Password</label>
  		<input type="password" name="user_pass">
  	</div>
  	<div class="input-group">
  		<button type="submit" class="btn" name="login">Login</button>
  	</div>
  	<p>
  		Not yet a member? <a href="reg_user.php">Sign up</a>
  	</p>
  </form>
</body>
</html>

 

server.php

<?php
session_start();

// initializing variables
$user_name = "";
$user_email = "";
$errors = array(); 

// connect to the database
$db_sys = mysqli_connect('localhost', 'root', '', 'sys');

// REGISTER USER
if (isset($_POST['user_reg'])) {
  // receive all input values from the form
  $user_name = mysqli_real_escape_string($db_sys, $_POST['user_name']);
  $user_email = mysqli_real_escape_string($db_sys, $_POST['user_email']);
  $user_pass1 = mysqli_real_escape_string($db_sys, $_POST['user_pass1']);
  $user_pass2 = mysqli_real_escape_string($db_sys, $_POST['user_pass2']);

  // form validation: ensure that the form is correctly filled ...
  // by adding (array_push()) corresponding error unto $errors array
  if (empty($user_name)) { array_push($errors, "Username is required"); }
  if (empty($user_email)) { array_push($errors, "Email is required"); }
  if (empty($user_pass1)) { array_push($errors, "Password is required"); }
  if ($user_pass1 != $user_pass2) {
	array_push($errors, "The two passwords do not match");
  }

  // check the database a user does not already exist with the same username and/or email
  $user_check_query = "SELECT * FROM users WHERE user_name='$user_name' OR user_email='$user_email' LIMIT 1";
  $result = mysqli_query($db_sysgo, $user_check_query);
  $user = mysqli_fetch_assoc($result);
  
  if ($user) { 
	// if user exists
    if ($user['user_name'] === $user_name) {
      array_push($errors, "Username already exists");
    }

    if ($user['user_email'] === $user_email) {
      array_push($errors, "email already exists");
    }
  }

  // Register user if there are no errors
  if (count($errors) == 0) {
	//encrypt the password
  	$user_pass = md5($user_pass1);
	
  	$query = "INSERT INTO users (user_name, user_email, user_pass) 
  			  VALUES('$user_name', '$user_email', '$user_pass')";
  	mysqli_query($db_sys, $query);
  	$_SESSION['user_name'] = $user_name;
  	$_SESSION['success'] = "You are now logged in";
  	header('location: index.php');
  }
}

// LOGIN USER
if (isset($_POST['login'])) {
  $user_name = mysqli_real_escape_string($db_sys, $_POST['user_name']);
  $user_pass = mysqli_real_escape_string($db_sys, $_POST['user_pass']);

  if (empty($user_name)) {
    array_push($errors, "Username is required");
  }
  if (empty($user_pass)) {
    array_push($errors, "Password is required");
  }

  if (count($errors) == 0) {
    $user_pass = md5($user_pass);
    $query = "SELECT * FROM users WHERE user_name='$user_name' AND user_pass='$user_pass'";
    $results = mysqli_query($db_sys, $query);
    if (mysqli_num_rows($results) == 1) {
      $_SESSION['user_name'] = $user_name;
      $_SESSION['success'] = "You are now logged in";
      header('location: index.php');
    }else {
 AQUI ESTÁ O ERRO QUE MOSTRA ---->>>> array_push($errors, "Wrong username/password");
    }
  }
}

?>

<?php  if (count($errors) > 0) : ?>
  <div class="error">
    <?php foreach ($errors as $error) : ?>
      <p><?php echo $error ?></p>
    <?php endforeach ?>
  </div>
<?php endif ?>



 

Editado por INous
Linhas em local errado
Link para o comentário
Compartilhar em outros sites

2 respostass a esta questão

Posts Recomendados

  • 0

Eu fiz a conexão via OO e ficou assim:

<?php
session_start();

// initializing variables
$user_name = "";
$user_email = "";
$errors = array(); 

// connect to the database
$db_sys = new mysqli('localhost', 'root', '', 'test');

// REGISTER USER
if (isset($_POST['user_reg'])) {
  // receive all input values from the form
  $user_name = mysqli_real_escape_string($db_sys, $_POST['user_name']);
  $user_email = mysqli_real_escape_string($db_sys, $_POST['user_email']);
  $user_pass1 = mysqli_real_escape_string($db_sys, $_POST['user_pass1']);
  $user_pass2 = mysqli_real_escape_string($db_sys, $_POST['user_pass2']);

  // form validation: ensure that the form is correctly filled ...
  // by adding (array_push()) corresponding error unto $errors array
  if (empty($user_name)) { array_push($errors, "Username is required"); }
  if (empty($user_email)) { array_push($errors, "Email is required"); }
  if (empty($user_pass1)) { array_push($errors, "Password is required"); }
  if ($user_pass1 != $user_pass2) {
	array_push($errors, "The two passwords do not match");
  }

  // check the database a user does not already exist with the same username and/or email
  $user_check_query = "SELECT * FROM users WHERE user_name='$user_name' OR user_email='$user_email' LIMIT 1";
  $result = mysqli_query($db_sysgo, $user_check_query);
  $user = mysqli_fetch_assoc($result);
  
  if ($user) { 
	// if user exists
    if ($user['user_name'] === $user_name) {
      array_push($errors, "Username already exists");
    }

    if ($user['user_email'] === $user_email) {
      array_push($errors, "email already exists");
    }
  }

  // Register user if there are no errors
  if (count($errors) == 0) {
	//encrypt the password
  	$user_pass = md5($user_pass1);
	
  	$query = "INSERT INTO users (user_name, user_email, user_pass) 
  			  VALUES('$user_name', '$user_email', '$user_pass')";
  	mysqli_query($db_sys, $query);
  	$_SESSION['user_name'] = $user_name;
  	$_SESSION['success'] = "You are now logged in";
  	header('location: index.php');
  }
}

// LOGIN USER
if (isset($_POST['login'])) {
  $user_name = mysqli_real_escape_string($db_sys, $_POST['user_name']);
  $user_pass = mysqli_real_escape_string($db_sys, md5($_POST['user_pass']));

  if (empty($user_name)) {
    array_push($errors, "Username is required");
  }
  if (empty($user_pass)) {
    array_push($errors, "Password is required");
  }

  if (count($errors) == 0) {
    $query = "SELECT * FROM users WHERE user_name='$user_name' AND user_pass='$user_pass'";
    echo $query;
    // echo mysqli_num_rows($db_sys, $results);
    $result = $db_sys->query($query);
    // $linhas = $result->num_rows;
    // echo $linhas;

    if (($linhas = $result->num_rows) == 1) {
      $_SESSION['user_name'] = $user_name;
      $_SESSION['success'] = "You are now logged in";
      // header('location: index.php');
    }else {
    //  AQUI ESTÁ O ERRO QUE MOSTRA ---->>>> 
    array_push($errors, "Wrong username/password");
    }
  }
}

?>

<?php  if (count($errors) > 0) : ?>
  <div class="error">
    <?php foreach ($errors as $error) : ?>
      <p><?php echo $error ?></p>
    <?php endforeach ?>
  </div>
<?php endif ?>

 

Claro que mudei o nome do BD pois o nome que estava usando era sys e creio que não pode usar esse nome da tabela. Deve ser um nome reservado.

Ponto de pesquisa:

https://www.php.net/manual/en/mysqli-result.num-rows.php

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152k
    • Posts
      651,7k
×
×
  • Criar Novo...