Jump to content

[PHP] Login / Registo


Recommended Posts

Posted

Visto que são 5:22 horas da manha, tentei criar um sistema de login bastante básico, em que consiste.

Tenho 4 páginas para este tutorial.

login.php - fazer login de um membro

criar_login.php -  fazer a criação de um novo login

login_validade.php - se o login for efectuado com sucesso acede a esta página

login_error.php - se o login for mal efectuado ou caso já exista um membro com aquele nome de login, acede a esta página

Restrinções:

Um membro não pode ter o mesmo login, Pois o script não deixa.

A página de login_error.php tem um script de refresh de 3 segundos e volta à página de login.php

Deixo em baixo os codigos das páginas assim como da base de dados.

Base de dados:

Já vem com um registo de teste

login: teste

password: 12345


CREATE TABLE `login` (
  `id_membro` int(11) NOT NULL auto_increment,
  `login` varchar(30) NOT NULL default '',
  `password` varchar(20) NOT NULL default '',
  PRIMARY KEY  (`id_membro`)
) TYPE=MyISAM AUTO_INCREMENT=2 ;
INSERT INTO `login` VALUES (1, 'teste', '12345');

Codigo de php:

login.php

<h1 align="center">Fazer login </h1>
<p align="center"> </p>
<p align="center"> </p>
<form ACTION="<?php echo $loginFormAction; ?>" id="form1" name="form1" method="POST"><table width="450" border="0" cellspacing="0" cellpadding="0">
  <tr>
    <th width="168" scope="col">Login:</th>
    <th width="282" scope="col"><label>
      <div align="left">
        <input name="login" type="text" id="login" />
      </div>
      </label></th>
  </tr>
  <tr>
    <th scope="row">Password:</th>
    <td><label>
      <input name="password" type="password" id="password" />
    </label></td>
  </tr>
  <tr>
    <th scope="row"> </th>
    <td><label>
      <input name="Submit" type="submit" id="Submit" value="Entrar" />
    </label></td>
  </tr>
</table>
</form>
<p> </p>

criar_login.php

<?php require_once('Connections/Rs_login.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

// *** Redirect if username exists
$MM_flag="MM_insert";
if (isset($_POST[$MM_flag])) {
  $MM_dupKeyRedirect="login_error.php";
  $loginUsername = $_POST['login'];
  $LoginRS__query = sprintf("SELECT login FROM login WHERE login=%s", GetSQLValueString($loginUsername, "text"));
  mysql_select_db($database_Rs_login, $Rs_login);
  $LoginRS=mysql_query($LoginRS__query, $Rs_login) or die(mysql_error());
  $loginFoundUser = mysql_num_rows($LoginRS);

  //if there is a row in the database, the username was found - can not add the requested username
  if($loginFoundUser){
    $MM_qsChar = "?";
    //append the username to the redirect page
    if (substr_count($MM_dupKeyRedirect,"?") >=1) $MM_qsChar = "&";
    $MM_dupKeyRedirect = $MM_dupKeyRedirect . $MM_qsChar ."requsername=".$loginUsername;
    header ("Location: $MM_dupKeyRedirect");
    exit;
  }
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
  $insertSQL = sprintf("INSERT INTO login (login, password) VALUES (%s, %s)",
                       GetSQLValueString($_POST['login'], "text"),
                       GetSQLValueString($_POST['password'], "text"));

  mysql_select_db($database_Rs_login, $Rs_login);
  $Result1 = mysql_query($insertSQL, $Rs_login) or die(mysql_error());

  $insertGoTo = "login_validade.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}

mysql_select_db($database_Rs_login, $Rs_login);
$query_Rs_criar_login = "SELECT * FROM login";
$Rs_criar_login = mysql_query($query_Rs_criar_login, $Rs_login) or die(mysql_error());
$row_Rs_criar_login = mysql_fetch_assoc($Rs_criar_login);
$totalRows_Rs_criar_login = mysql_num_rows($Rs_criar_login);
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>.: Criar Login :.</title>
<style type="text/css">
<!--
.style1 {font-size: 16px}
-->
</style>
</head>

<body>
<p> </p>
<h1 align="center">Crir um novo login</h1>
<p align="center"> </p>
<p align="center"> </p>
<form action="<?php echo $editFormAction; ?>" id="form1" name="form1" method="POST">
  <table width="450" border="0" cellspacing="0" cellpadding="0">
    <tr>
      <th width="154" scope="col">Login:</th>
      <th width="296" scope="col"><label>
        <div align="left">
          <input name="login" type="text" id="login" />
        </div>
      </label></th>
    </tr>
    <tr>
      <th scope="row">Password:</th>
      <td><label>
        <input name="password" type="password" id="password" />
      </label></td>
    </tr>
    <tr>
      <th scope="row"> </th>
      <td><label>
        <input type="submit" name="Submit" value="Criar login" />
      </label></td>
    </tr>
  </table>
    
  <input type="hidden" name="MM_insert" value="form1">
</form>
</body>
</html>
<?php
mysql_free_result($Rs_criar_login);
?>

login_validade.php

<?php require_once('Connections/Rs_login.php'); ?>
<?php
if (!isset($_SESSION)) {
  session_start();
}
$MM_authorizedUsers = "";
$MM_donotCheckaccess = "true";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) { 
  // For security, start by assuming the visitor is NOT authorized. 
  $isValid = False; 

  // When a visitor has logged into this site, the Session variable MM_Username set equal to their username. 
  // Therefore, we know that a user is NOT logged in if that Session variable is blank. 
  if (!empty($UserName)) { 
    // Besides being logged in, you may restrict access to only certain users based on an ID established when they login. 
    // Parse the strings into arrays. 
    $arrUsers = Explode(",", $strUsers); 
    $arrGroups = Explode(",", $strGroups); 
    if (in_array($UserName, $arrUsers)) { 
      $isValid = true; 
    } 
    // Or, you may restrict access to only certain users based on their username. 
    if (in_array($UserGroup, $arrGroups)) { 
      $isValid = true; 
    } 
    if (($strUsers == "") && true) { 
      $isValid = true; 
    } 
  } 
  return $isValid; 
}

$MM_restrictGoTo = "login_error.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {   
  $MM_qsChar = "?";
  $MM_referrer = $_SERVER['PHP_SELF'];
  if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0) 
  $MM_referrer .= "?" . $QUERY_STRING;
  $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  header("Location: ". $MM_restrictGoTo); 
  exit;
}
?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

mysql_select_db($database_Rs_login, $Rs_login);
$query_Rs_validate = "SELECT * FROM login";
$Rs_validate = mysql_query($query_Rs_validate, $Rs_login) or die(mysql_error());
$row_Rs_validate = mysql_fetch_assoc($Rs_validate);
$totalRows_Rs_validate = mysql_num_rows($Rs_validate);
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>.: Login sucesso :.</title>
</head>

<body>
Login efectuado com sucesso... 
</body>
</html>
<?php
mysql_free_result($Rs_validate);
?>

login_error.php

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>.: Login error :.</title>
<meta http-equiv="Refresh" content="3;URL=login.php" />
</head>

<body>
<p>Ocorreu um erro no login. volte atras... </p>
<p>Username invalido</p>
<p>username repetido..</p>
<p>Incapacitado de vizualizar pagina anterior   </p>
<p> </p>
<p> </p>
<p>(Redirecionamento em 3 segundos...) </p>
</body>
</html>


PS:

Script testado e a correr lindamente.

Tentei fazer um script básico e que nao fosse bastante puxado.

Deixo em anexo os ficheiros caso a voçes nao vos corra da melhor maneira.

Programas utilizados:

Dreamweaver 8

Mysql

.[ Once .SCP' , Allways .SCP']. o estádio a vibbrar a juve a cantar, ergue o teu poder, ergue a tua voz. SPORTING SOMOS NOS!

Posted

Não sei se alguem ja exprimentou o código ou deu uma vista de olhos, mas gostaria de saber se acham interessante para os membros em aprendizagem

.[ Once .SCP' , Allways .SCP']. o estádio a vibbrar a juve a cantar, ergue o teu poder, ergue a tua voz. SPORTING SOMOS NOS!

Posted

O código é td teu? z.z

Não peças ajuda por PM! A tua dúvida vai ter menos atenção do que se for postada na secção correcta do fórum!

Posted

EDIT: Acho que ja postei uma vez o código aqui no p@p  ?

Houve aí um post qq da tofas penso eu de que, em que tu falaste disto e o QuickFire postou o código de um dos files 😉

Não peças ajuda por PM! A tua dúvida vai ter menos atenção do que se for postada na secção correcta do fórum!

Posted

O código é td teu? z.z

Se lesses o inicio do post verias que era meu  😄

.[ Once .SCP' , Allways .SCP']. o estádio a vibbrar a juve a cantar, ergue o teu poder, ergue a tua voz. SPORTING SOMOS NOS!

Posted

orly? então pk é que vejo várias vezes require_once('Connections/Rs_login.php'); quando tu nem fazes referencia ao mesmo? 😉

Não peças ajuda por PM! A tua dúvida vai ter menos atenção do que se for postada na secção correcta do fórum!

Posted

LOL... tu também reparas em tudo 🙂

Por acaso acabei de fazer uma pesquisa no google e encontrei varios sites com scripts igualzinhos a esse nao tira e nem se põe nada.. até os nomes das variveis são iguais  😉  😐

Posted

Eu sou assim 🙂

Não peças ajuda por PM! A tua dúvida vai ter menos atenção do que se for postada na secção correcta do fórum!

Posted

Realmente... e comentários em ingles! ter variaveis em ingles ainda va lá que nao vá, agora postares num forum portugues com comentarios em ingles :S

btw.. "$MM_restrictGoTo =" esse MM_ xeirame a Dreamweaver... o dreamweaver é que costuma criar funcoes/variaveis com imico MM_... mas pronto 😉

Posted

Realmente... e comentários em ingles! ter variaveis em ingles ainda va lá que nao vá, agora postares num forum portugues com comentarios em ingles :S

btw.. "$MM_restrictGoTo =" esse MM_ xeirame a Dreamweaver... o dreamweaver é que costuma criar funcoes/variaveis com imico MM_... mas pronto 😉

Eu fui lá pelos comentários 😛

Não peças ajuda por PM! A tua dúvida vai ter menos atenção do que se for postada na secção correcta do fórum!

Posted

sim é visível que o código foi gerado pelo Dreamweaver 😉

O que está em causa não é o ser criado pelo Dreamweaver mas sim o ser um (possível) rip 😛

Não peças ajuda por PM! A tua dúvida vai ter menos atenção do que se for postada na secção correcta do fórum!

Posted

Rip não acredito ser, mas se é o Dreamweaver que gera... não é a mesma coisa que ser uma pessoa a programar de raiz 😉

Daniel Correia

Posted

Rip não acredito ser, mas se é o Dreamweaver que gera... não é a mesma coisa que ser uma pessoa a programar de raiz 😛

Eu não sei se é rip mas lê:

Por acaso acabei de fazer uma pesquisa no google e encontrei varios sites com scripts igualzinhos a esse nao tira e nem se põe nada.. até os nomes das variveis são iguais  😉  :|

🙂

Não peças ajuda por PM! A tua dúvida vai ter menos atenção do que se for postada na secção correcta do fórum!

Posted

deixem o rapaz defender-se, mas concordo, isso parece de dreamweaver

ele só responde se quiser. cm já disse, o q tá em causa aqui não é o ser do dreamweaver ou n, é o ser dele ou de outrém 😉

Não peças ajuda por PM! A tua dúvida vai ter menos atenção do que se for postada na secção correcta do fórum!

Posted

Ele diz no fim do post que utilizou o dreamweaver

PS:

Script testado e a correr lindamente.

Tentei fazer um script básico e que nao fosse bastante puxado.

Deixo em anexo os ficheiros caso a voçes nao vos corra da melhor maneira.

Programas utilizados:

Dreamweaver 8

Mysql

Só quero saber se foi ele que fez o script ou se foi RIP 😉

PS: bLd se fizesses o script de raiz (sem utilizar o dreamweaver) estavas de parabéns...

Posted

Só quero saber se foi ele que fez o script ou se foi RIP 😛

Not RIP but rip. 😉 Anyway, se fosse feito de raiz estava de parabéns.

Não peças ajuda por PM! A tua dúvida vai ter menos atenção do que se for postada na secção correcta do fórum!

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...

Important Information

By using this site you accept our Terms of Use and Privacy Policy. 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.