How to post a form to same page loaded dynamically - php

thanks in advance for your time.
I have a PHP web which dynamically fills a html section depending on the url in this way:
<section id="sect_info">
<?php
$existingPages = array('main', 'createacc');
if (isset($_GET['p'])) {
$requestedPage = $_GET['p'];
if (in_array($requestedPage, $existingPages)) {
if (file_exists($requestedPage.'.php')) include_once($requestedPage.'.php');
else echo "La pagina solicitada no existe.";
}
else include_once('main.php');
}
else include_once('main.php');
?>
</section>
The php that has the content for that section is the following:
<?php
if (isset($_POST['user']) && isset($_POST['pwd'])) {
createAcc();
}
else {
echo "
<table cellpadding='0' cellspacing='0' class='table_info'>
<tr>
<td class='topWnd' align='center'> Nueva cuenta
</td>
</tr>
<tr>
<td class='contenidoInfo'>
<form action='createacc.php' method='post'>
<table>
<tr>
<td>Usuario:</td>
<td><input type='text' maxlength='10' name='user'></td>
</tr>
<tr>
<td>Contraseña:</td>
<td><input type='password' maxlength='10' name='pwd'></td>
</tr>
<tr>
<td>Repetir contraseña:</td>
<td><input type='password' maxlength='10' name='repeatPwd'></td>
</tr>
<tr>
<td>E-mail:</td>
<td><input type='text' maxlength='60' name='email'></td>
</tr>
<tr>
<td>Pregunta secreta:</td>
<td><input type='text' maxlength='60' name='question'></td>
</tr>
<tr>
<td>Respuesta secreta:</td>
<td><input type='text' maxlength='60' name='answer'></td>
</tr>
</table>
<p><input type='checkbox' name='rules'> Estoy de acuerdo con las reglas de Helbreath OS.</p>
<p><input type='submit' value='Crear cuenta'></p>
</form>
</td>
</tr>
</table>";
}
function createAcc() {
include_once("include/account.php");
include_once("include/main.php");
// -- Variables globales
$usuario = $_POST["user"];
$contraseña = $_POST["pwd"];
// --
// Verificamos que los datos ingresados sean validos
if (!empty($usuario) and !empty($contraseña))
{
// se verifica la longitud de los campos para no generar conflictos con la base de datos
if ((strlen($usuario) <= 10) && ((strlen($contraseña) >= 4) && (strlen($contraseña) <= 10))) {
// Luego de verificar la información establecemos la comunicacion con la base de datos.
$mainObj = new Main; // Instancia de Main
// Intentamos conectar a la base de datos y almacenamos el resultado
// de la conexion en una variable.
$conexResult = $mainObj->ConnectToDatabase();
if ($conexResult != "") // La conexión no ha sido exitosa. Mostramos el resultado
{
echo $conexResult;
$mainObj->CloseCon();
return;
}
$accObj = new Account; // Instancia de Account
// verificamos si la cuenta que se quiere crear ya existe
if ($accObj->CheckExistingAccount($mainObj->getConexObj(), $usuario))
{
echo "La cuenta: ".$usuario." ya existe!.";
$mainObj->CloseCon();
return;
}
else
{
if ($accObj->CreateNewAccount($mainObj->getConexObj(), $usuario, $contraseña))
echo "<p style='color:green;'>La cuenta: ".$usuario." fue creada exitosamente.!</p>";
else
echo "<p style='color:red;'>La cuenta: ".$usuario." no ha podido crearse.!</p>";
}
}
// Cerramos la conexion a la base de datos
$mainObj->CloseCon();
}
}
?>
The problem is that when the user submit the form, it result is shown on a blank page. What I need is to display the result of the php action in the same section where the php is loaded.
I've tried using jQuery and ajax, replacing the "input type submit" for "input type button" and handling the submit event from jQuery but it seems that jQuery can't find the form element.
so: how can I post a form and display its result to that section that I mentioned before?
Sorry guys for my poor english. If you need more details or more code or whatever just tell me.
Thanks again!

To do an ajax post and replace the contents of the forms container you should do this.
$('#sect_info form').on('submit', function(e){
e.preventDefault();
// do client side check of values
if ($(this).find("input[name=user]").val() == '' ||
$(this).find("input[name=pwd]").val() == '' ||
$(this).find("input[name=pwd]").val() != $(this).find("input[name=repeatPwd"]).val()){
alert ('All fields are required. Please Correct and resubmit');
return;
}
// do the post and replace the context of the section with the returned markup.
$.ajax({
url:window.location.toString,
type:"POST",
data:$(this).serialize(),
success:function(htmlStr){
$('#sect_info').html(htmlStr);
}
)};
});
edit: One of the square bracket of [name=pwd] was outside the quotation marks

you just need the form to post to itself. For this just use form without "action" or point the action to itself.
For instance, if the file where the form is, it's named "myform.php", then you could use:
<form action="http://www.mywebsite.com/myform.php" method="post">
Then, at the begining of myform.php you check the $_POST (or $_REQUEST if you want)
if (!empty($_POST['user'])) {
/* do stuff */
}
<form action="http://www.mywebsite.com/myform.php" method="post">
/* the form's inputs goes here */

Related

Database not receiving data send from PHP/HTML form

Okay so i have this form that is supposed to fill multiple tables but when i click on the send button, the page just refreshes, and when i check phpmyadmin the tables are empty.
i have a code that is supposed to tell me if the data got succesfully registered in the database, but i cant get it to work either, it doesn't show up at all, not even to tell me the registration was not succesful.
I've been struggling with this code for 3 days, im pretty new to coding but i tried every change i could an i still can't get it to work.
Here's the code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Registro empleado</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css">
</head>
<body>
<form>
<h1>Ingresar Datos</h1>
<h3>Cliente</h3>
<input type="number" name="id_cliente" placeholder="id_local"><!--ingreso del id-->
<input type="text" name="nombre" placeholder="nombre"><!--ingreso del nombre del cliente-->
<input type="text" name="domicilio" placeholder="domicilio"><!--ingreso del domicilio-->
<input type="text" name="telefono" placeholder="telefono"><!--ingreso del numero de telefono-->
<input type="text" name="edad" placeholder="edad"><!--ingreso de la edad del cliente-->
<h3>Ganancias</h3>
<input type="number" name="id_ganancias" placeholder="id_ganancias"><!--ingreso del id-->
<input type="number" name="diarios1" placeholder="diarios"><!--ingreso de ganancias diarias-->
<input type="number" name="mensuales1" placeholder="mensuales"><!--ingreso de ganancias mensuales-->
<input type="number" name="anuales1" placeholder="anuales"><!--ingreso de ganancias anuales-->
<h3>Gastos</h3>
<input type="number" name="id_gastos" placeholder="id_gastos"><!--ingreso del id-->
<input type="number" name="diarios2" placeholder="diarios"><!--ingreso de gastos diarios-->
<input type="number" name="mensuales2" placeholder="mensuales"><!--ingreso de gastos mensuales-->
<input type="number" name="anuales2" placeholder="anuales"><!--ingreso de gastos anuales-->
<input type="submit" name="enviar"><!--botton de enviar-->
</form>
<form action="http://localhost/consulta_cliente.php"><!--link para phpadmin-->
<input type="submit" value="consulta_cliente"><!--boton que te lleva phpadmin-->
<form action="http://localhost/consulta_ganancias.php"><!--link para phpadmin-->
<input type="submit" value="consulta_ganancias"><!--boton que te lleva phpadmin-->
<form action="http://localhost/consulta_gastos.php"><!--link para phpadmin-->
<input type="submit" value="consulta_gastos"><!--boton que te lleva phpadmin-->
</form>
<?php
include("registrar_empleado.php");/*Llamado a el archivo php de registro*/
?>
</body>
</html>
PHP:
<?php
//Llamada a código de conexión
include("conexion_empleado.php");
//validación de variables que recibirán cada campo de la tabla
//cliente
if (isset($_POST['enviar'])) {
if (strlen($_POST['id_cliente']) >=1 && strlen($_POST['nombre']) >= 1 && strlen($_POST['domicilio']) >= 1 && strlen($_POST['edad']) >= 1 && strlen($_POST['telefono']) >= 1) {
$id_cliente = trim($_POST['id_cliente']);
$nombre = trim($_POST['nombre']);
$domicilio = trim($_POST['domicilio']);
$telefono = trim($_POST['telefono']);
$edad = trim($_POST['edad']);
//inserción de registros en la tabla datos
$consulta1 = "INSERT INTO cliente(id_cliente, nombre, domicilio, telefono, edad) VALUES ('$id_cliente', '$nombre', '$domicilio', '$edad', '$telefono')";
$resultado1 = mysqli_query($conecta,$consulta1);
//ganancias
if (strlen($_POST['id_ganancias']) >=1 && strlen($_POST['diarios1']) >= 1 && strlen($_POST['mensuales1']) >= 1 && strlen($_POST['anuales1']) >= 1) {
$id_ganancias = trim($_POST['id_ganancias']);
$diarios1 = trim($_POST['diarios1']);
$mensuales1 = trim($_POST['mensuales1']);
$anuales1 = trim($_POST['anuales1']);
$consulta2 = "INSERT INTO ganancias(id_ganancias, diarios, mensuales, anuales) VALUES ('$id_ganancias', '$diarios1', '$mensuales1', '$anuales1')";
$resultado2 = mysqli_query($conecta,$consulta2);
//gastos
if (strlen($_POST['id_gastos']) >=1 && strlen($_POST['diarios2']) >= 1 && strlen($_POST['mensuales2']) >= 1 && strlen($_POST['anuales2']) >= 1) {
$id_gastos = trim($_POST['id_gastos']);
$diarios2 = trim($_POST['diarios2']);
$mensuales2 = trim($_POST['mensuales2']);
$anuales2 = trim($_POST['anuales2']);
$consulta3 = "INSERT INTO gastos(id_gastos, diarios, mensuales, anuales) VALUES ('$id_gastos', '$diarios2', '$mensuales2', '$anuales2')";
$resultado3 = mysqli_query($conecta,$consulta3);
if ($resultado1 && $resultado2 && $resultado3) {
?>
<h3 class="completo">Registro exitoso</h3>
<?php
} else {
?>
<h3 class="incompleto">Error de registro</h3>
<?php
}
} else {
?>
<h3 class="incompleto">Por favor completa el registro</h3>
<?php
}
}
}
}
?>
PHP code to connect to the database:
<?php
//código para asignar las variables para la conexión: localhost = nombre servido, usuario = root, nombre_BD = registro
$conecta = mysqli_connect("localhost","root","","locales");
?>
I have some code to show the last rows that were filled by the form, i can't test if it works yet since i can't get data to even get send to the database, anyways here it is just it case:
Query1:
<?php
include("conexion_cliente.php");//Llamado a el documento php
$consulta1_1 = "select * from pago";//se muestra la tabla pago
$resultado1_1 = mysqli_query($conecta,$consulta1_1);
$cuenta = mysqli_num_rows ($resultado);
$cuenta = $cuenta - 1;
$resultado1 = mysqli_query($conecta, "SELECT * FROM cliente LIMIT $cuenta, 1"); //consulta de tabla empleando
//limit para obtener solo una fila
echo "<h1>ULTIMO CAMPO</h1>"; //titulo
echo "<pre>"; //atributo pre para poder realizar el salto de línea
while($row1 = mysqli_fetch_array($resultado1)) { //se obtienen los arrays de la consulta
echo print_r($row1); //se imprimen los resultados de la consulta
echo "\n"; //salto de linea
}
echo "</pre>";
?>
Query2:
<?php
include("conexion_cliente.php");//Llamado a el documento php
$consulta2_1 = "select * from pago";//se muestra la tabla pago
$resultado2_1 = mysqli_query($conecta,$consulta2_1);
$cuenta = mysqli_num_rows ($resultado);
$cuenta = $cuenta - 1;
$resultado2 = mysqli_query($conecta, "SELECT * FROM ganancias LIMIT $cuenta, 1"); //consulta de tabla empleando
//limit para obtener solo una fila
echo "<h1>ULTIMO CAMPO</h1>"; //titulo
echo "<pre>"; //atributo pre para poder realizar el salto de línea
while($row2 = mysqli_fetch_array($resultado2)) { //se obtienen los arrays de la consulta
echo print_r($row2); //se imprimen los resultados de la consulta
echo "\n"; //salto de linea
}
echo "</pre>";
?>
Query3:
<?php
include("conexion_cliente.php");//Llamado a el documento php
$consulta3_1 = "select * from gastos";//se muestra la tabla gastos
$resultado3_1 = mysqli_query($conecta,$consulta3_1);
$cuenta = mysqli_num_rows ($resultado);
$cuenta = $cuenta - 1;
$resultado3 = mysqli_query($conecta, "SELECT * FROM gastos LIMIT $cuenta, 1"); //consulta de tabla empleando
//limit para obtener solo una fila
echo "<h1>ULTIMO CAMPO</h1>"; //titulo
echo "<pre>"; //atributo pre para poder realizar el salto de línea
while($row3 = mysqli_fetch_array($resultado3)) { //se obtienen los arrays de la consulta
echo print_r($row3); //se imprimen los resultados de la consulta
echo "\n"; //salto de linea
}
echo "</pre>";
?>
Sorry it's written in spanish, im from mexico but i noticed that this "us" page was more active than the "es" one. Any help it's greatly appreciated and if you have any language related question i'll be glad to answer.

PHP issue with login screen

I have his index.php code:
<?php
session_start();
session_destroy();
?>
<!DOCTYPE html>
<html lang="es">
<meta charset="utf-8">
<head>
<title>Login</title>
<link rel="stylesheet" type="text/css" href="css/estilos.css">
</head>
<body>
<center>
<div class="caja_login">
<form method="POST" action="validar.php">
<label>Nombre de usuario:</label><input type="text" name="nombre" placeholder="Usuario" required/><br><br>
<label>Contraseña:</label><input type="password" name="contraseña" placeholder="Contraseña" required /><br><br>
<input type="submit" value="Entrar" class="enviar" placeholder="Entrar"/><br>
</form>
</div>
<div class ="caja_registro">
<form method="POST">
<label>¿Aún no estás registrado?</label><br>
<label>Nombre de usuario:</label><input type="text" name="nombrerg" placeholder="Nombre de usuario" required><br>
<label>Contraseña:</label><input type="password" name="contrarg" placeholder="Contraseña" required>
<input type="submit" name="registro" value="Crear Cuenta"><br>
</form>
</div>
<h1><?php include("conexion.php");?></h1>
</center>
<?php//para el registro
include("conexion.php");
if(isset($_POST['registro'])){
$sql = 'SELECT FROM cuenta';
$rec = mysqli_query($conexion, $sql);
$verificar =0;
while ($resultado = mysql_fetch_array($rec)) {
if ($resultado->nombre == _POST['nombrerg']) {//verificamos que el nombre de usuario no existe
$verificar = 1;//si verificar es 1 es que el usuario esta repetido
}
}
if ($verificar == 0) {//si varificar es 0 entonces el nombre no esta repetido
$nom = _POST['nombrerg'];
$pw = _POST['contrarg'];
$conexion->query("INSERT INTO cuenta (usuario, contraseña) VALUES ('$nom','$pw')";
mysqli_query($conexion, $sql);
echo 'Te has registrado con exito';
}else{
echo "El nombre de usuario ya existe!";
}
}
?>
</body>
</html>
When I go to the page, it shows everything right, but below everything it shows the PHP code, and when I click the button "registro" it doesn't insert the data into the DB.
The page's is a simple login and register, but as I said the register button (registro) isn't working.
EDIT:
This is what is showing in the bottom of the page:
nombre == _POST['nombrerg']) {//verificamos que el nombre de usuario no existe $verificar = 1;//si verificar es 1 es que el usuario esta repetido } } if ($verificar == 0) {//si varificar es 0 entonces el nombre no esta repetido $nom = _POST['nombrerg']; $pw = _POST['contrarg']; $conexion->query("INSERT INTO cuenta (usuario, contraseña) VALUES ('$nom','$pw')"; mysqli_query($conexion, $sql); echo 'Te has registrado con exito'; }else{ echo "El nombre de usuario ya existe!"; } } ?>
It's due to your code-formatting.
Change this:
<?php//para el registro
To:
<?php //para el registro
And this:
$conexion->query("INSERT INTO cuenta (usuario, contraseña) VALUES ('$nom','$pw')";
To:
$conexion->query("INSERT INTO cuenta (usuario, contraseña) VALUES ('$nom','$pw')");
The last one you're missing and ending ) after the last "
For the other ones, having the //-comment without space from the start-tag <?php prevents it from being interpreted correctly.
As a side-note, you have two includes right after eachother, for the same file, one of them inside a <h1> for no reason.
Also, your code is horribly prone to SQL injection attacks.
On the code below, I put a line break to separate where the PHP started from your comment, after that, I notied you were using both mysqli and mysql functions and changed to mysqli only and insert $ where it was missing in $_POST. Your last query had a column named contraseña, do not use especial characters in column names, I've changed it to contrasena.
<?php
//para el registro
include("conexion.php");
if(isset($_POST['registro'])){
$sql = 'SELECT FROM cuenta';
$rec = mysqli_query($conexion, $sql);
$verificar =0;
while ($resultado = mysqli_fetch_array($rec)) {
if ($resultado->nombre == $_POST['nombrerg']) {//verificamos que el nombre de usuario no existe
$verificar = 1;//si verificar es 1 es que el usuario esta repetido
}
}
if ($verificar == 0) {//si varificar es 0 entonces el nombre no esta repetido
$nom = $_POST['nombrerg'];
$pw = $_POST['contrarg'];
$conexion->query("INSERT INTO cuenta (usuario, contrasena) VALUES ('$nom','$pw') )";
mysqli_query($conexion, $sql);
echo 'Te has registrado con exito';
}else{
echo "El nombre de usuario ya existe!";
}
}
?>
</body>
</html>
<?php//para el registro is probably causing problems. Change it to <?php //para el registro (notice the space)
If the rest of the php renders, then it's unlikely a server issue.
Also, the variable for post is $_POST not _POST
Just to reiterate. Please don't store passwords in clear text. Here's a good article explaining why. For more questions related to that, feel free to checkout other StackExchange sites like security

Validate input-fields (texbox) BEFORE execute script

I would like to ask you, how to handle this:
Validate input-fields
if everything is OK, execute the following script which writes the fields in database
What I have till now is:
if($_SERVER['REQUEST_METHOD'] == "POST")
{
...
$checkField = "";
if (empty($_POST["tb_checkField"]))
{
$checkFieldErr = "<br> Field is required!";
}
else
{
$checkField = $_POST["tb_checkField"];
if (!preg_match("/[-a-z0-9+&##\/%?=_!:,.;]+/",$checkField))
{
$checkFieldErr = "<br> Invalid value detected!";
}
}
...
}
...
<form method="post" action="writeTodatabase.php">
<table border="0" align="center">
<tr>
<td colspan="2"><input name="tb_checkField" type="text" value="<?php echo $checkField;?>" tabindex="1" size="50" maxlength="20"/>
<span class="error"><?php echo $checkFieldErr;?></span></td>
</tr>
</table>
</form>
...
<td><p>
<input type="submit" name="submit" value="Save" tabindex="2"/>
</p></td>
So when I press the button, is directly going to execute writeTodatabase.php without checking the textbox.
So how can I tell him to go first check this values from textbox and if its ok, go and execute writeTodatabase.php?
Either you can choose to validate the input on the same page as the form, or you can do the validation on the writeTodatabase.php page.
The "action" parameter in the form tag decides where you want the _POST data to be sent. You can't have your validation code on the same page as the form when you're sending the _POST data to another page. You'll either have to send the data to the current page (either removing the action parameter, or changing it's value to the current page) or move the validation script to writeTodatabase.php.
If you want the validation code to remain on the current page, and remove the action parameter, you can use the header() function to redirect to writeTodatabase.php if the validation is successful. If you're gonna use the header() function remember to put the validation code at the top of the file, before any output.
I'm making a WEB project, and I used a form imput validations in PHP:
if($_SERVER['REQUEST_METHOD']=='POST'){
require('inc/mysqli_connect.php');
$errors=array();
/*Verifica el nombre*/
if(empty($_POST['first_name'])){
$errors[]='Verifique el campo de Nombre del participante';
}else{
$fina=mysqli_real_escape_string($dbc, trim($_POST['first_name']));
}
/*Verifica el apellido paterno*/
if(empty($_POST['ape_pat'])){
$errors[]='Verifique el campo de Apellido Paterno del participante';
}else{
$appa=mysqli_real_escape_string($dbc, trim($_POST['ape_pat']));
}
/*Verifica el apellido materno*/
if(empty($_POST['ape_mat'])){
$errors[]='Verifique el campo de Apellido Materno del participante';
}else{
$apma=mysqli_real_escape_string($dbc, trim($_POST['ape_mat']));
}
/*Verifica el genero*/
if(empty($_POST['gender'])){
$errors[]='Seleccione el Género del participante';
}else{
$gend=mysqli_real_escape_string($dbc, trim($_POST['gender']));
}
/*Verifica el correo electronico*/
if(empty($_POST['email'])){
$errors[]='Verifique el campo de Correo Electrónico del participante';
}else{
$coel=mysqli_real_escape_string($dbc, trim($_POST['email']));
}
/*and repeat the code above for all the input that you have in your form */
if(empty($errors)){
$q="INSERT INTO participante(nombre, paterno, materno, genero, correo, fechadenac, procedencia, ocupacion, asistencia, fechareg) VALUES ('$fina','$appa','$apma','$gend','$coel','$dabi','$prov','$ocup','$assi',NOW())";
$r=mysqli_query($dbc,$q);
if($r){
echo '
<p>
Nombre: <b>'.$_POST['first_name'].'</b><br />
Apellido Paterno: <b>'.$_POST['ape_pat'].'</b><br />
Apellido Materno: <b>'.$_POST['ape_mat'].'</b><br />
Genero: <b>'.$_POST['gender'].'</b><br />
Correo Electrónico: <b>'.$_POST['email'].'</b><br />
Fecha de nacimiento: <b>'.$_POST['date'].'</b><br />
Procedencia: <b>'.$_POST['provenance'].'</b><br />
Ocupación: <b>'.$_POST['ocuppation'].'</b><br />
¿Asistió? <b>'.$_POST['assistance'].'</b><br />
</p>
';
}else{
echo '
<h2><a>¡Error del Sistema!</a></h2>
<p>
El registro no pudo realizarse debido a un error del sistema. Disculpe los incovenientes.<br />
</p>
<p>
Error: '.mysqli_error($dbc).'<br />
Query: '.$q.'<br />
</p>
';
}
mysqli_close($dbc);
include ('inc/footer.html');
exit();
}else{
echo '
<p>
Revise que todo los campos hayan sido llenados correctamente.<br />
Se encontraron los siguientes errores: <br />
';
foreach ($errors as $msg) {
echo " - $msg<br />\n";
}
echo '
</p>
<p>
Ingrese los datos faltantes e intente de nuevo.
</p>
';
}
mysqli_close($dbc);
}
mysqli_connect.php has this structure:
<?php
DEFINE('DB_USER','root');
DEFINE('DB_PASSWORD','armando');
DEFINE('DB_HOST','localhost');
DEFINE('DB_NAME','flisol');
$dbc=mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME) OR die ('No es posible conectarse a la Base de datos: '.mysqli_connect_error());
mysqli_set_charset($dbc,'utf8');
By the way, I'm using a sticky form. Enjoy it!

Query failed only on IE browser

My goal is to move an PHP application from a Windows Server 2000 - SQL Server 2005 - Apache 2.2 to a new a server with Windows Server 2012 - SQL Server 2012 - Apache 2.2.
On the new server I've installed and configured SQL Server 2012 - Apache 2.2 and PHP 5.2.9.
I copied the application and the database on the new server.
Unfortunately the application didn't work with Internet Explorer. I cannot access to my application account because it failed on the login form. It works with Firefox and Chrome.
I can read on the Apache log : PHP Warning: mssql_query() [function.mssql-query]: message: Incorrect syntax near '='. (severity 15)
I tried the application under PHP 5.4 and Apache 2.4 using the ODBC library for handling requests. I meet again the same error with Internet Explorer.
On the old server the application work fine with IE7-8-9-10.
Somebody can help me ?
Regards
I'm not using JQuery, data from login form are passed to $_POST to another page.
The log just failed it didn't recognize me.
Here is the form
<fieldset class="fld_type" style="width:80%;">
<legend class="lgd_style">Connexion - Inscription</legend>
<table align="center">
<?php if(!empty($erreur)){ ?>
<tr>
<td align="right" colspan="3" style="color:red; font-size:14px;" ><?php echo $erreur; ?></td>
</tr>
<?php } ?>
<tr><td> </td></tr>
<tr>
<td rowspan="4"><img style="height:90px;" src="images/connect.png" alt="Authentification" /></td>
<td class="right"><b>Nº Panéliste (identifiant):</b></td>
<td><input style="border:1px solid #0075bc;" onFocus="modif_champs(this);" onBlur="default_champs(this);" type="text" id="txt_login" name="txt_login" /></td>
</tr>
<tr>
<td class="right"><b>Mot de passe :</b></td>
<td><input style="border:1px solid #0075bc;" onFocus="modif_champs(this);" onBlur="default_champs(this);" type="password" id="txt_mdp" name="txt_mdp" /></td>
</tr>
<tr>
<td></td>
<td><a class="strong" href="#MDPOublie" onClick="$('formMDPOublie').appear();Effect.ScrollTo('MDPOublie'); return false;" >Mot de passe oublié ?</a></td>
</tr>
<tr>
<td></td>
<td>
<!--<input onClick="verifLoginMDP(this.form);" type="button" value="Se connecter" id="btn_valider" name="btn_valider" class="btn_style" />-->
<input type="submit" value="Se connecter" id="btn_valider" name="btn_valider" class="btn_style" />
</td>
</tr>
<tr><td colspan="3"><hr style="color:white;" /></td></tr>
</table>
<table align="center">
<tr>
<td align="right"><img style="height:40px; width:40px; " src="images/addP2.png" alt="Nouveau ?" /></td>
<td><a class="strong" href="questionnaire_consommation/form_inscriptionPaneliste.php">Vous n'êtes pas encore inscrit ?</a></td>
</tr>
</table>
</fieldset>
Here is the php code that handle the login
if(isset($_POST['txt_login']) AND isset($_POST['txt_mdp'])){
$login = Securite::bdd($_POST['txt_login']);
$mdp = md5($_POST['txt_mdp']); // cryptage du mot de passe
$erreur = "";
/* Verification de l'utilisateur
*********************************/
$requeteVerif = "SELECT COUNT(*) FROM paneliste WHERE PANELISTE_LOGIN = '" . $login . "' AND PANELISTE_MDP = '" . $mdp . "'";
$stmtVerif = ExecRequete($requeteVerif, Connexion());
$donneesVerif = ObjetSuivant($stmtVerif);
if($donneesVerif[0] == 0){
//Le paneliste n'est pas referencé dans la base de données
$erreur = "Les identifiants de connexion sont incorrects !";
}else{
$requeteIDPaneliste = "SELECT PANELISTE_ID, PANELISTE_TYPE, PANELISTE_DATENAISS, SITE_ID FROM paneliste WHERE PANELISTE_LOGIN = '" . $login . "' AND PANELISTE_MDP = '" . $mdp . "'";
$stmtIDPaneliste = ExecRequete($requeteIDPaneliste, Connexion());
$IDPaneliste = ObjetSuivant($stmtIDPaneliste);
$_SESSION['id_paneliste'] = $IDPaneliste[0];
$_SESSION['site_id'] = $IDPaneliste[3];
$_SESSION['type_user'] = $IDPaneliste[1];
$_SESSION['type_questionnaire'] = getTypeQuestionnaire($IDPaneliste[2]);
// Correction de l'erreur #90 : Des références au site de Vandoeuvre (e-mail et téléphone) apparaissent quelque soit le site de rattachement du panéliste.
// A la connexion, on enregistre donc ces valeurs en session.
$siteInfo = recupererSiteInfo($_SESSION['id_paneliste']);
$_SESSION['site_admin_nom'] = $siteInfo['SITE_ADMIN_NOM'];
$_SESSION['site_admin_prenom'] = $siteInfo['SITE_ADMIN_PRENOM'];
$_SESSION['site_tel'] = $siteInfo['SITE_TEL'];
$_SESSION['site_email'] = $siteInfo['SITE_EMAIL'];
$_SESSION['site_horaires'] = $siteInfo['SITE_HORAIRES'];
// Correction de l'erreur #132 : Certains panélistes ne peuvent accéder au site, car la variable de session est effacée après une redirection par header().
session_write_close();
header("Location: /partie_paneliste/accueil_paneliste.php");
}
}
afficheEnTete("Espace de Connexion", "");
Here is the php code that execute query
// Execution d'une requête SQL
function ExecRequete($requete, $connexion){
$resultat = mssql_query($requete, $connexion);
if($resultat){
return $resultat;
}
else{
echo "<b>Erreur dans l'execution de la requete '$requete' .</b>";
exit;
}
} // Fin de la fonction ExecRequete
//Recherche de l'objet suivant
function ObjetSuivant($resultat){
return mssql_fetch_array($resultat);
}
//Recherche de la ligne suivante (retourne un tableau)
function LigneSuivante($resultat){
return mssql_fetch_assoc($resultat);
}
// Correction de l'erreur #187 : Erreur SQL lors de la mise à jour des fréquences de consommation.
// Nombre d'enregistrements trouvés
function Nombre($resultat){
return mssql_num_rows($resultat);
}
?>
It fails on line $resultat = mssql_query($requete, $connexion);

Protect a page with php sessions

I have some pages in website that i want to protect with php sessions so only an administrator with a valid password and login that match password and login in a mysql database can have access to this pages .
here's the code for index.html ( the form of authentification )
<form id="form2" name="form2" method="post" action="authagent.php">
<p class="kkm">Authentification </p>
<table align="center" width="300" border="0">
<tr>
<td width="146">Login</td>
<td width="144"><label for="textfield12"></label>
<input type="text" name="login" id="text" /></td>
</tr>
<tr>
<td width="146">Mot de passe</td>
<td><label for="textfield13"></label>
<input type="password" name="mdp" id="mdp" /></td>
</tr>
<tr>
<td> </td><td><input type="submit" name="button" id="button" value="Se connecter" /></td>
</tr>
</table>
<p align="center">Créer un nouveau compte</p>
<p align="center"><a href = "javascript:history.back()">
and this is the code of authagent.php
<?php
session_start() ;
$_SESSION['connect']=0;
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("agence");
$login = $_POST['login'];
$mdp = $_POST['mdp'] ;
$query = "SELECT * FROM agent where login_agent = '$login' and mdp_agent = '$mdp'";
$result = mysql_query($query);
while ($line = mysql_fetch_array($result, MYSQL_ASSOC)) {
if ($login == $line['login_agent'] && ($mdp == $line['mdp_agent'])) // Si le nom d'utilisateur et le mot de passe sont correct
{
$_SESSION['connect']=1;
header('Location: agent.php');
}
else
{
echo 'incorrect' ;// Si le nom d'utilisateur ou le mot de passe est incorrect
}
}
?>
Here's the code of a secured page agent.php
<?php
session_start();
if (isset($_SESSION['connect']))//On vérifie que le variable existe.
{
$connect=$_SESSION['connect'];//On récupère la valeur de la variable de session.
}
else
{
$connect=0;//Si $_SESSION['connect'] n'existe pas, on donne la valeur "0".
}
if ($connect == "1") // Si le visiteur s'est identifié.
{
header('Location: agent.php');
// On affiche la page cachée.
}
else
{
header('Location: seconnecteragent.php');
} ?>
Usually this is done by testing for the existence of a session variable like loggedin, and if it is not =1 then you automatically redirect to the login page. You can put this simple bit of code at the top of every page, and if the loggedin variable is there, nothing happens and the page is served normally. A basic example:
<?php
if(!isset($_SESSION['loggedin']) || $_SESSION['loggedin']!=1){
header('Location: login.php');
exit();
}
?>
As I can see, your problem is that you have a recursion there. In agent.php page, if the user is authenticated, then you send him back to the same page agent.php.

Categories