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.
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>
This question already has answers here:
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
Closed 6 years ago.
I have a problem for a connection page i'm trying to set up, after the connection form, the conditionnal block of code that should verify the info just appear instead of executing. Everything appear after , even the semi-colon and parenthesis that should end the if. What did I do wrong?
<?php
// if ($id!=0) {erreur(ERR_IS_CO)};
if (!isset($_POST['mail']))
{
echo "<form method="post" action="connexion.php">
<fieldset>
<legend>Connexion</legend>
<p>
<label for="mail">Mail :</label><input name="mail" type="text" id="mail" /><br />
<label for="password">Mot de Passe :</label><input type="password" name="password" id="password" />
</p>
</fieldset>
<p><input type="submit" value="Connexion" /></p></form>" ;
}
else
{
$message;
if (empty($_POST['mail']) || empty($_POST['password']) ) //empty space
{
$message = "<p>une erreur s\'est produite pendant votre identification. Vous devez remplir tous les champs</p>
<p>Cliquez ici pour revenir</p>";
}
else //password checker
{
if ( md5($_POST['password']) == 'student') // Student
{
$_SESSION['mail'] = $_POST['mail'];
$_SESSION['id'] = "student";
$message = "<p>Bienvenue student
vous êtes maintenant connecté!</p>" //.$data['Nom']., need to fetch name
<p>Cliquez ici pour revenir à la page d accueil</p>;
}
else // Access denied
{
$message = "<p>Une erreur s\est produite pendant votre identification.<br /> Le mot de passe ou le pseudo
entré n\est pas correct.</p><p>Cliquez ici
pour revenir à la page précédente <br />";
}
$query->CloseCursor();
}
echo $message;
}
?>
Syntax error is reason of showing blank page, use Netbeans or Sublime software helps you and you need concatination or use single quotes inside double quotes
Example
echo "<form method='post' action='connexion.php'>
and also enable your errors to see reason of blank page
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!
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);
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 */