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);
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 days ago.
Improve this question
here is my issue.
I made a login page with a variable that counts the number of attempts. This variable increments itself each time the user credentials are wrong.
I use this variable to disable the account if the user tries more than 5 times. Everything works but, if the user goes back to the previous page, he goes back to the last submit and the variable is decremented. With this issue, he can have unlimited attempts if he goes back everytime to the last page.
Can you help me please?
Here is my code.
<?php
// Le nombre de tentatives est placé dans le formulaire en renvoyé en post
if(isset($_POST['failurecount'])) {
$failcount = $_POST['failurecount'];
} else {
$failcount = 1;
}
if(isset($_POST['login_email']) && isset($_POST['mdp'])) {
$login_email = $_POST['login_email'];
$mdp = $_POST['mdp'];
$result = $wpdb->get_results("SELECT login, email, mdp FROM `wp_clients_user` WHERE (`login` = '$login_email' OR `email` = '$login_email') AND actif = 1", ARRAY_A);
if($wpdb->last_error) {
echo 'wpdb error: ' . $wpdb->last_error;
}
if($failcount < 5) {
if(empty($result)) {
$failure = "Erreur, le nom d'utilisateur ou le mot de passe est incorrect, vérifiez les données saisies! Nombre de tentatives : ". $failcount;
$failcount++;
} else {
foreach($result as $row) {
if(password_verify($mdp, $row['mdp'])) {
$_SESSION['login'] = $row['login'];
} else {
$failure = "Erreur, le mot de passe est incorrect, veuillez vérifier le mot de passe saisi! Nombre de tentatives : " . $failcount;
$failcount++;
}
}
}
} else {
// On ne bloque que si le nombre de tentatives est = 5 car sinon, il bloquera tous les comptes qe l'utilisateur entrera après avoir été bloqué
if ($failcount == 5) {
// Si l'utilisateur s'est trompé trop de fois
$failure = "Erreur! Votre compte a été bloqué suite à un trop grand nombre d'échecs!";
$wpdb->query("UPDATE wp_clients_user SET actif = 0 WHERE `login` = '$login_email' OR `email` = '$login_email'", ARRAY_A);
blocked_account($login_email);
$failcount++;
} else { // Si l'utilisateur continue d'essayer de se connecter, on ne fait plus rien (pas de connexion ou de bloquge)
$failure = "Toutes vos prochaines tentatives de connexion ne seront pas prises en compte! Nombre de tentatives : " . $failcount;
$failcount++;
}
?>
<form id="login_form" method="post" onsubmit="return false">
<input type="hidden" name="failurecount" value="<?php if(isset($failcount)){echo $failcount;}else{echo 1;} ?>">
<input id="login_email" name="login_email" type="text" value="<?php echo $login_email; ?>" placeholder="Nom d'utilisateur ou adresse e-mail *">
<input id="mdp" name="mdp" type="password" value="<?php echo $mdp; ?>" placeholder="Mot de passe *">
<p>Mot de passe oublié?</p>
<div>
<input id="showpwd" type="checkbox" onclick="show_password()"><label for="showpwd">Afficher le mot de passe</label>
</div>
<?php
if($failure !== false) {
echo('<p style="color: red;">'.htmlentities($failure)."</p>\n");
}
?>
<div>
<input id="souvenir" type="checkbox"><label for="souvenir">Se souvenir de moi</label>
</div>
<button class="bouton_submit" id="user_send_login" style="background-color:#3498db; color:white; width:100px; height:35px;" onclick="verif_login_form()">Se connecter</button>
</form>
I've got two websites with the same content. One is with ".com" and the other one is ".nc".
I've got this php page:
<?php
// si le mot de passe est posté
if(isset($_POST["motpasse"])){
// si la valeur du mot de passe est bien celle qu'il faut
if($_POST["motpasse"] == "pass") {
header ("Location: dernier.php");
exit();
}else {echo "Mauvais mot de passe";}
}
echo ('<p align="center"><font size=6pt>Veuillez saisir
votre mot de passe: <br></p></font>');
echo '<form name="motdepasse" method="post"
action="' . htmlspecialchars($_SERVER['REQUEST_URI']) . '">';
echo ('<p align="center"><input type=password name="motpasse"
size="5" style="height:60px; width:160px" value="" /></p>');
echo ('<p align="center"><input type="submit"
name="action onClick=(this.form)"
style="height:60px; width:160px"value="OK"></p>');
echo '</form>';
?>
Weirdly, the header function is working on the website ".com" but not on the website ".nc"
When I type the password, the header doesn't redirect me on the php page that I've put ("dernier"). Any idea why?
Is correct what JackBauer told you about the headers sent. another solution some nasty is this:
<?php
// si le mot de passe est posté
if(isset($_POST["motpasse"])){
// si la valeur du mot de passe est bien celle qu'il faut
if($_POST["motpasse"] == "pass") {
echo "<meta http-equiv="refresh" content="0;url=dernier.php">";
/*header ("Location: dernier.php"); */
exit();
}else {echo "Mauvais mot de passe";}
}
echo ('<p align="center"><font size=6pt>Veuillez saisir votre mot de passe: <br></p></font>');
echo '<form name="motdepasse" method="post" action="' . htmlspecialchars($_SERVER['REQUEST_URI']) . '">';
echo ('<p align="center"><input type=password name="motpasse" size="5" style="height:60px; width:160px" value="" /></p>');
echo ('<p align="center"><input type="submit" name="action onClick=(this.form)" style="height:60px; width:160px"value="OK"></p>');
echo '</form>';
?>
But maybe the principal thing that is failing in your script is the action in your form.
with firebug review your scaped html code in your client side. (what u r seeing in your browser {font code})
see ya!
session_start(); is the first thing I call. There is no whitespace. Why am I still get this warning?
Screenshots:
Error:
[20-Feb-2014 16:52:32 America/New_York] PHP Warning: session_start(): Cannot send session cookie - headers already sent by (output started at /home/feyzprod/public_html/expertlookup.ca/index.php:1) in /home/feyzprod/public_html/expertlookup.ca/index.php on line 4
[20-Feb-2014 16:52:32 America/New_York] PHP Warning: session_start(): Cannot send session cache limiter - headers already sent (output started at /home/feyzprod/public_html/expertlookup.ca/index.php:1) in /home/feyzprod/public_html/expertlookup.ca/index.php on line 4
<?php session_start();
require_once('bdservice.php');
$bd = new BDService();
require_once('script.php');
if(!isset($_SESSION['specialiteBD']))
{
$sql = "SELECT * FROM Specialites";
try
{ $resultat = $bd->Select($sql); }
catch(Exception $e)
{ echo $e->getMessage(); }
if(count($resultat) != 0)
{
$newSpec= array();
foreach($resultat as $a)
{
$newSpec[] = utf8_encode($a[1]);
}
$_SESSION['specialiteBD'] = $newSpec;
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Annuaire</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<link rel="stylesheet" href="css/style.css" />
<link rel="stylesheet" href="css/ico.css" />
<script src='js/validation.js'></script>
<script>
function initialize()
{
var input = document.getElementById('where');
var componentRestrictions = {country: 'ca'};
var autocomplete = new google.maps.places.Autocomplete(input);
autocomplete.setComponentRestrictions(componentRestrictions);
}
google.maps.event.addDomListener(window, 'load', initialize);
$(function() {
var availableTags = [];
var ville = [];
var availableTags = <?php echo urldecode(json_encode($_SESSION['specialiteBD'])) ?>;
for(var i = 0; i < availableTags.length; i++)
{
ville.push(decode(availableTags[i]));
}
$( "#what" ).autocomplete({
minLength: 2,
source: function(req, responseFn) {
var re = $.ui.autocomplete.escapeRegex(req.term);
var matcher = new RegExp( "^" + re, "i" );
var a = $.grep( ville, function(item,index){
return matcher.test(item);
});
responseFn( a.slice(0,10));
}
});
});
</script>
</head>
<body>
<?php include_once("analyticstracking.php") ?>
<div class='headerBar'>
<div class='headerContent'>
<div id='logo'><a href='index.php'><img src='images/logo4.png' height='75' width='321' alt="Expert LookUp"/ title="Expert LookUp"/></a></div>
<div id='navLien'>
<table>
<tr>
<td>
<span>
<?php
if(isset($_SESSION['authentification']))
{
echo "<a href='logout.php'>déconnexion</a>
<a href='profil.php' class='blue_Button'>Profil</a>";
}
else
{
echo "<a href='enregistrement.php'>Ajouter votre entreprise</a>
<a href='connexion.php' class='blue_Button'>Connexion</a>";
}
?>
</span>
</td>
</tr>
</table>
</div>
</div>
</div>
<div class='blur'>
<div class='blurContent'>
<div id='left'>
<p>Multiplier votre visibilité sur le web en vous inscrivant gratuitement sur notre moteur de recherche d'entreprise.</p>
<a href='enregistrement.php' class='blue_Button'>S'enregistrer</a>
</div>
<div id='right'>
<form action='search/index.php' method='get'>
<p>Trouvez un entrepreneur pour vos prochains travaux</p>
<div class='iconMan'><input type='text' name='what' id='what' size='40' placeholder="Que recherchez vous ? Ex : Plombier" required title="Veuillez indiquer votre critère de recherche." x-moz-errormessage="Veuillez indiquer votre critère de recherche." /></div><br/>
<?php
if(isset($_SESSION['invalideAdr']))
{
unset($_SESSION['invalideAdr']);
echo "<div class='iconWhere'><input type='text' style=\"border:1px solid red;\" name='where' id='where' size='40' placeholder=\"Impossible de trouver votre adresse !\" required title=\"Veuillez indiquer l\'emplacement de vos travaux.\" x-moz-errormessage=\"Veuillez indiquer l\'emplacement de vos travaux.\" /></div><br/>";
}
else
{
echo "<div class='iconWhere'><input type='text' name='where' id='where' size='40' required title=\"Veuillez indiquer l\'emplacement de vos travaux.\" x-moz-errormessage=\"Veuillez indiquer l\'emplacement de vos travaux.\" /></div><br/>";
}
?>
<div class='radio'>
<input type="radio" id="r1" name="secteur" value='1' />
<label for="r1"><span></span>Résidentiel</label>
<input type="radio" id="r2" name="secteur" value='2' />
<label for="r2"><span></span>Industriel</label>
<input type="radio" id="r3" name="secteur" value='3' checked="checked" />
<label for="r3"><span></span>Les deux</label><br/><br/>
<input type='hidden' name='page' value='1' />
<input type='submit' name='Rechercher' value='Rechercher' class='blue_Button' />
</div>
</form>
</div>
</div>
</div>
<div class='infoContent'>
<div id='info'>
<p>À propos d'Expert Lookup</p>
<span style='font-weight:bold;'>Information</span><br/>
<span>Expert LookUp est un annuaire se concentra principalement sur les entreprises dans le domaine de la construction.</span><br/><br/>
<span style='font-weight:bold;'>La simplicité même !</span><br/>
<span>Vous avez uniquement à choisir quel type d'entreprises/personnes vous recherchez, l'emplacement de votre travaux et le secteur d'activité pour faire votre recherche.
Les résultats de recherches vous seront affichées par ordre de distance et si une entreprise ne se déplace pas jusqu`à chez vous, elle ne sera pas affichée.</span><br/><br/>
<span style='font-weight:bold;'>Validation de la licence RBQ</span><br/>
<span>Nous vérifions directement à partir de la base de données de Gouvernement du Québec pour vérifier la licence RBQ des entreprises enregistrées sur notre annuaires.
Si une entreprise ne dispose pas de licence RBQ valide, cette information vous sera affichée.</span><br/><br/>
</div>
<div id='why'>
<p>Pourquoi s'enregistrer ?</p>
<table>
<tr>
<td><span>Soyez visible partout au Canada, auprès des millions d'internautes !</span></td>
<td><img src='images/blueEarth.png' width='97' height='97' alt='terre' title='terre' /></td>
</tr>
<tr>
<td><span>Expert LookUp est un annuaire entièrement gratuit, aucun frais caché !</span></td>
<td><img src='images/greenMoney.png' width='97' height='97' alt='terre' title='terre' /></td>
</tr>
<tr>
<td><span>Votre inscription prendra moins de 5 minutes, alors qu'attendez-vous ? Vous n'avez rien à perdre !</span></td>
<td><img src='images/clock.png' width='97' height='97' alt='terre' title='terre' /></td>
</tr>
</table>
</div>
</div>
<div class='footerBar'>
<div class='footerContent'>
<a href='contact.php'>Contactez-nous</a><span> | </span>
<a href='enregistrement.php'>Ajouter votre entreprise</a><span> | </span>
<a href='connexion.php'>Connexion</a><span> | </span>
<a href='aide.php'>Aide</a><br/>
<span>© Copyright at ExpertLookUp.ca</span>
</div>
</div>
</body>
</html>
No need to check if your session_start() has already started or not. session_start() will just use the current session if there is one.
PHP Doc:
session_start() creates a session or resumes the current one based on
a session identifier passed via a GET or POST request, or passed via a
cookie.
Link
About the error you're receiving, I'm guessing this is due to the IF-Statement lines above it.
Well, that is probably because you already started session somewhere. I usually made solution by putting # before session_start and error was silent and session also worked.
So, #session_start(); may be solution.
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 */
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.