Foros del Web » Programando para Internet » PHP »

login redireccionado

Estas en el tema de login redireccionado en el foro de PHP en Foros del Web. Hola buenas noches/ días. Tengo el siguiente código que debería chequear al usuario que entra por su usuario y contraseña y posteriormente re-dirigirlo a otra ...
  #1 (permalink)  
Antiguo 28/11/2014, 21:14
 
Fecha de Ingreso: julio-2010
Ubicación: Cerca Sitges (Barcelona)
Mensajes: 98
Antigüedad: 13 años, 9 meses
Puntos: 4
login redireccionado

Hola buenas noches/ días.

Tengo el siguiente código que debería chequear al usuario que entra por su usuario y contraseña y posteriormente re-dirigirlo a otra página, donde debería mostrar todos los registros de este usuario (correspondientes a su email) que se encuentran en una BD.


Alguna sugerencia o código mejorado.

mi código de verificación es:

Código PHP:
Ver original
  1. <?php require_once('../../Connections/contactos.php'); ?>
  2. <?php
  3. if (!function_exists("GetSQLValueString")) {
  4. function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
  5. {
  6.   if (PHP_VERSION < 6) {
  7.     $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  8.   }
  9.  
  10.   $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
  11.  
  12.   switch ($theType) {
  13.     case "text":
  14.       $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
  15.       break;    
  16.     case "long":
  17.     case "int":
  18.       $theValue = ($theValue != "") ? intval($theValue) : "NULL";
  19.       break;
  20.     case "double":
  21.       $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
  22.       break;
  23.     case "date":
  24.       $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
  25.       break;
  26.     case "defined":
  27.       $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
  28.       break;
  29.   }
  30.   return $theValue;
  31. }
  32. }
  33.  
  34. mysql_select_db($database_contactos, $contactos);
  35. $query_Recordset1 = "SELECT * FROM contactos";
  36. $Recordset1 = mysql_query($query_Recordset1, $contactos) or die(mysql_error());
  37. $row_Recordset1 = mysql_fetch_assoc($Recordset1);
  38. $totalRows_Recordset1 = mysql_num_rows($Recordset1);
  39. ?>
  40. <?php
  41. // *** Validate request to login to this site.
  42. if (!isset($_SESSION)) {
  43. }
  44.  
  45. $loginFormAction = $_SERVER['PHP_SELF'];
  46. if (isset($_GET['accesscheck'])) {
  47.   $_SESSION['PrevUrl'] = $_GET['accesscheck'];
  48. }
  49.  
  50. if (isset($_POST['textfield'])) {
  51.   $loginUsername=$_POST['textfield'];
  52.   $password=$_POST['textfield2'];
  53.   $loginUsername2=$_POST['textfield3'];
  54.   $MM_fldUserAuthorization = "";
  55.   $MM_redirectLoginSuccess = "modificar.php";
  56.   $MM_redirectLoginFailed = "acceso no permitido.php";
  57.   $MM_redirecttoReferrer = false;
  58.   mysql_select_db($database_contactos, $contactos);
  59.  
  60.   $LoginRS__query=sprintf("SELECT nombre_usuario, password, mailcontacto FROM contactos WHERE nombre_usuario=%s AND password=%s AND mailcontacto=%s",
  61.     GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text"), GetSQLValueString($loginUsername2, "hidden"));
  62.    
  63.   $LoginRS = mysql_query($LoginRS__query, $contactos) or die(mysql_error());
  64.   $loginFoundUser = mysql_num_rows($LoginRS);
  65.   if ($loginFoundUser) {
  66.      $loginStrGroup = "";
  67.    
  68.     //declare two session variables and assign them
  69.     $_SESSION['MM_Username'] = $loginUsername;
  70.     $_SESSION['MM_UserGroup'] = $loginStrGroup;
  71.     $_SESSION['MM_Username'] = $loginUsername;       
  72.  
  73.     if (isset($_SESSION['PrevUrl']) && false) {
  74.       $MM_redirectLoginSuccess = $_SESSION['PrevUrl']; 
  75.     }
  76.     header("Location: " . $MM_redirectLoginSuccess );
  77.   }
  78.   else {
  79.     header("Location: ". $MM_redirectLoginFailed );
  80.   }
  81. }
  82. ?><style type="text/css">
  83. <!--
  84. body {
  85.     background-color: WHITE;
  86. }
  87. a:link {
  88.     text-decoration: none;
  89. }
  90. a:visited {
  91.     text-decoration: none;
  92. }
  93. a:hover {
  94.     text-decoration: underline;
  95. }
  96. a:active {
  97.     text-decoration: none;
  98. }
  99. -->
  100. </style>
  101. <div align="center">
  102.   <table width="78%" border="0">
  103.     <tr>
  104.       <td height="120"><div align="center">
  105.         <table width="100%" border="0" cellspacing="0">
  106.           <tr>
  107.             <td height="0" bgcolor="WHITE"><div align="center">___ </div></td>
  108.             </tr>
  109.           <tr>
  110.             <td height="52" bgcolor="WHITE"><div align="center">
  111.               <table width="60%" border="0">
  112.                 <tr>
  113.                   <td bgcolor="WHITE"><div align="center"><strong style="font-size: xx-large; color: #000;">Talla variada</strong></div></td>
  114.                   </tr>
  115.                 </table>
  116.               </div></td>
  117.             </tr>
  118.           <tr>
  119.             <td height="17" bgcolor="WHITE">&nbsp;</td>
  120.             </tr>
  121.           <tr>
  122.             <td bgcolor="WHITE"><div align="center">
  123.               <table width="17%" border="0">
  124.                 <tr>
  125.                   <td width="47%"><div align="center"> <img src="http://.../datos internos/fotos/regresar.png" alt="Regresar " width="33" height="35" hspace="10" border="0" align="absmiddle" onclick="history.back(-1);" />Regresar</div></td>
  126.                   </tr>
  127.                 </table>
  128.               </div></td>
  129.             </tr>
  130.           </table>
  131.       </div></td>
  132.     </tr>
  133.     <tr>
  134.       <td><div align="center">
  135.         <table width="100%" border="0">
  136.           <tr>
  137.             <td height="4" bgcolor="WHITE">&nbsp;</td>
  138.             </tr>
  139.           </table>
  140.       </div></td>
  141.     </tr>
  142.   </table>
  143. </div>
  144. <div align="center"></div>
  145. <form name="form1" method="POST" action="<?php echo $loginFormAction; ?>">
  146.   <label><br>
  147.   </label>
  148.  
  149.   <div align="center">
  150.     <table width="43%" border="0">
  151.       <tr>
  152.         <td height="30" colspan="2" bgcolor="white"><div align="center" style="color: black; font-weight: bold; font-size: large;">Autentificaci&oacute;n usuario:</div></td>
  153.       </tr>
  154.       <tr>
  155.         <td width="40%" bgcolor="WHITE"><div align="right" style="color: black">Usuario:</div></td>
  156.         <td width="60%" bgcolor="WHITE"><div align="left">
  157.           <input type="loginUsername" name="textfield" id="textfield">
  158.         </div></td>
  159.       </tr>
  160.       <tr>
  161.         <td bgcolor="WHITE"><div align="right" style="color: black">Contrase&ntilde;a:</div></td>
  162.         <td bgcolor="WHITE"><div align="left">
  163.           <input type="password" name="textfield2" id="textfield2">
  164.         </div></td>
  165.       </tr>
  166.       <tr>
  167.         <td bgcolor="WHITE">&nbsp;</td>
  168.         <td bgcolor="WHITE"><div align="left">
  169.           <input name="loginUsername2" type="hidden" id="textfield3" value="modificar.php?idempleado=<?php echo $row_Recordset1['mailcontacto']; ?>" />  
  170.         </div></td>
  171.       </tr>
  172.     </table>
  173. <table width="88%" border="0">
  174.       <tbody>
  175.         <tr>
  176.           <td height="55" bgcolor="WHITE"><div align="center"><span style="font-size:small; color:black;">Recuerde la referencia de su pedido.</span></div></td>
  177.         </tr>
  178.       </tbody>
  179.     </table>
  180. <p>
  181.       <label>
  182.         <input type="submit" name="button" id="button" value="Enviar">
  183.       </label>
  184.     </p>
  185.   </div>
  186. </form>
  187. <div align="center"></div>
  188. <p align="center"><a href="http://..."></a></p>
  189. <div align="center">_ </div>
  190. <p>
  191.   <?php
  192. mysql_free_result($Recordset1);
  193. ?>
  194. </p>
  195. <p>&nbsp;</p>
  196. <p>&nbsp;</p>
  197. <p>&nbsp;</p>
  198. <p>&nbsp;</p>
  199. <p>&nbsp;</p>


el código para validar me da error al enviarlo.

Código HTML:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

Pretendo que al validar el usuario, se redirija a otra página, donde el usuario pueda visualizar sus artículos contenidos en una BD, para poder modificarlos o eliminarlos.


Muchas gracias

Última edición por rafaxusirati; 28/11/2014 a las 21:19
  #2 (permalink)  
Antiguo 29/11/2014, 13:27
Avatar de manuparquegiralda  
Fecha de Ingreso: junio-2012
Ubicación: Barcelona
Mensajes: 241
Antigüedad: 11 años, 10 meses
Puntos: 39
Respuesta: login redireccionado

Obviamente el fallo lo tienes en las sintaxis del query a mysql, sinceramente, sugerencias para mejorar el código, desde mi punto de vista, muchas, no entiendo muy bien porque haces tantas cosas para un script tan sencillo, si lo único que pretendes es validar un usuario.

- No es para nada necesario que habras y cierres etiquetas <?php ?> si no hay código en otro lenguaje entre una y otra.

- Deberías haber puesto el código del archivo que incluyes al principio del script, ya que hay variables como la de $contactos que no se de donde y porque salen.

- No sé porque preguntas si la función GetSQLValueString() no existe para declararla en lugar de declararla directamente.

- Si ya conoces tu versión PHP, porque andar haciendo comprobaciones de la versión.

- ¿Por qué compruebas si hay variable de sesión para declarar el session_start()?, decláralo y punto.

- Intenta no crear arcivos php con espacios en el nombre, en alguna ocasión me he visto afectado por tonterías así, por ejemplo en lugar de "acceso no permitido.php" llámalo "acceso_no_permitido.php".

- Evita las tablas en HTML, a Google no le hacen mucha gracia según tengo entendido.

No sé, me voy a molestar un poco para darte una guía de como trabajo yo, también fui novato y en este foro hubo gente muy buena que me ayudó bastante.

Código PHP:
Ver original
  1. <?php session_start();
  2.  
  3. if((isset($_POST['user']))&&(isset($_POST['pass']))){
  4.     // CONECTAS CON LA BASE DE DATOS //
  5.     $mysqli = new mysqli("tu dominio", "tu usuario", "tu password", "tu base de datos");
  6.     $mysqli->set_charset("utf8");
  7.     // PREGUNTAS SI EXISTE EL USUARIO CON EL PASSWORD //
  8.     $p = $mysqli->query("SELECT * FROM contactos WHERE nombre_usuario = '".$_POST['user']."' AND password = '".$_POST['pass']."'");
  9.     $aUser = $p->fetch_assoc();
  10.     if(!$aUser['nombre_usuario']){
  11.         // SI NO SE EXTRAEN DATOS DE LA CONSULTA MOSTRAMOS EL ERROR //
  12.         $error = "El usuario o el password no son correctos.";
  13.     }else{
  14.         ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  15.         // CREAMOS VARIABLES DE SESSION CON EL USUARIO ESTE DEBERÍA SER ÚNICO PARA QUE EN LA PÁGINA DE DESTINO /////
  16.         // PUEDAS VOLVER A HACER LA CONSULTA A LA BASE DE DATOS PARA EXTRAER LOS DATOS DEL USUARIO O TAMBIÉN ////////
  17.         // PUEDES CREAR UNA VARIABLE DE SESSION PARA CADA DATO DE LA BASE DE DATOS, PERO SI TIENES MUCHOS CAMPOS //
  18.         // PUEDE ACABAR SIENDO UN POCO LIOSO LA VERDAD, ESO LO ELIGES TÚ. YO TRABAJO CON CLASES POR LO QUE LO /////////
  19.         // GUARDARÍA TODOS LOS DATOS NECESARIOS EN UN OBJETO QUE SERIALIZARÍA EN UNA VARIABLE DE SESSION QUE  //////
  20.                 // PUEDA LEER EN CADA PÁGINA SIN NECESIDAD DE DE VOLVER A CONSULTAR A LA BASE DE DATOS NI DE TENER UN ///////
  21.         //  NÚMERO INMENSO DE VARIABLES DE SESSION /////////////////////////////////////////////////////////
  22.         //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  23.         $_SESSION['user'] = $aUser['nombre_usuario'];
  24.         header("location:modificar.php");
  25.         exit();
  26.     }
  27. }else{
  28.     $error = "Tienes que rellenar todos los campos.";
  29. }
  30.  
  31. ?>
  32.  
  33.  
  34. <!doctype html>
  35. <html>
  36. <head>
  37. <meta charset="utf-8">
  38. <title>Loguin</title>
  39. <style type="text/css">
  40. body {
  41.     margin:0px;
  42.     padding:0px;
  43.     padding-top:20px;
  44. }
  45. .table{
  46.     position:relative;
  47.     display:table;
  48.     width:500px;
  49.     margin:0 auto;
  50. }
  51. .table > div{
  52.     position:relative;
  53.     display:table-row;
  54. }
  55. .cell_izq{
  56.     position:relative;
  57.     display:table-cell;
  58.     width:50%;
  59.     text-align:right;
  60.     vertical-align:middle;
  61.     padding:5px;
  62.     font-weight:bold;
  63. }
  64. .cell_der{
  65.     position:relative;
  66.     display:table-cell;
  67.     width:50%;
  68.     text-align:left;
  69.     vertical-align:middle;
  70.     padding:5px;
  71. }
  72. input[type=text],input[type=password]{
  73.     width:200px;
  74. }
  75. input[type=submit]{
  76.     font-weight:bold;
  77.     color:#FFF;
  78.     background:#42349F;
  79.     border:solid 1px #CCC;
  80. }
  81. .cont_button{
  82.     position:relative;
  83.     display:table;
  84.     width:500px;
  85.     margin:0 auto;
  86.     text-align:center;
  87. }
  88. input[type=submit]:hover{
  89.     color:#42349F;
  90.     background:#EDEDED;
  91. }
  92. p{
  93.     text-align:center;
  94.     margin-top:10px;
  95.     margin-bottom:10px;
  96.     font-weight:bold;
  97.     color:#F00;
  98. }
  99. </style>
  100. </head>
  101.  
  102. <body>
  103. <form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
  104. <div class="table">
  105.     <div>
  106.         <div class="cell_izq">
  107.             Usuario:
  108.         </div>
  109.         <div class="cell_der">
  110.             <input type="text" name="user" />
  111.         </div>
  112.     </div>
  113.     <div>
  114.         <div class="cell_izq">
  115.             Contraseña:
  116.         </div>
  117.         <div class="cell_der">
  118.             <input type="password" name="pass" />
  119.         </div>
  120.     </div>
  121. </div>
  122. <div class="cont_button">
  123.     <input type="submit" value="Enviar">
  124. </div>
  125. <p><?php echo $error; ?></p>
  126. </body>
  127. </form>
  128. </html>


Prueba con esta página que te he hecho, debería valerte, tan solo tienes que cambiar la conexión a la base de datos y modificar los campos en las consultas si yo los he puesto mal.
__________________
Diseño Web - Arisman Web

Última edición por manuparquegiralda; 29/11/2014 a las 13:51
  #3 (permalink)  
Antiguo 29/11/2014, 20:14
 
Fecha de Ingreso: julio-2010
Ubicación: Cerca Sitges (Barcelona)
Mensajes: 98
Antigüedad: 13 años, 9 meses
Puntos: 4
Respuesta: login redireccionado

muchas gracias

Etiquetas: login, mysql, registro, select, sql, variable
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 22:45.