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
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>
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm seeking your help for two problems I'm unable to solve.
The first one is not truly problematic but rather annoying :
?php
session_start();
$_SESSION['pseudo'];
$CAT="";
//tentative de connexion à la base de donnée
try
{
$bdd = new PDO('mysql:host=localhost;dbname=espace_membre;charset=utf8', 'root', '');
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage()); //message d'erreur au cas où la connexion échoue
}
if(isset($_SESSION['id']))
{ //echo "ok";
}
else
{
//echo "lol";
header('location:connexion.php');
}
if(isset($_GET['id']) AND $_GET['id'] > 0)
{
$getid=intval($_GET['id']);
$requser= $bdd -> prepare('SELECT * FROM membres WHERE id= ?');
$requser->execute(array($getid));
$userinfo=$requser->fetch();
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$CAT = test_input($_POST["categorie"]);
$TYPE= test_input($_POST["typeannonce"]);
$WILA= test_input($_POST["wilaya"]);
$fk_membres_id=$_SESSION['id'];
if(isset($_POST['revenirprofil']))
{
header("Location: profil.php?id=".$_SESSION['id']);
}
if(isset($_POST['article_titre']) AND isset($_POST['article_description']) AND isset($_POST['categorie']) AND isset($_POST['wilaya']) AND isset($_POST['typeannonce']) )
{
$article_titre=htmlspecialchars($_POST['article_titre']);
$article_description=htmlspecialchars($_POST['article_description']);
///insertion dans la BDD /////
$ins=$bdd->prepare('INSERT into articles (titre_article, description,date_publication,catégorie,type_article,wilaya,fk_membres_id) VALUES(?,?, NOW(),?,?,?,?)' );
$ins->execute(array($article_titre,$article_description,$CAT,$TYPE,$WILA,$fk_membres_id));
//header("Location: profil.php?id=".$_SESSION['id']);
}
else
{
$erreurAE = "veuillez remplir tous les champs du formulaire d'ajout";
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Ajouter une annonce</title>
<meta charset="utf-8">
</head>
<body>
<h3>Bonjour <?php echo $_SESSION['pseudo'] ?> ajoutez une annonce TROKI par ici : </h3>
<h3>Bonjour <?php echo $_SESSION['id'] ?> ajoutez une annonce TROKI par ici : </h3>
<h3>Ajoutez une annonce <?php echo $_SESSION['email']?></h3>
éditer mon profil
modifier mon mot de passe
mon profil
se déconnecter
<div align="center">
<form method="POST">
<label>titre de votre annonce</label>
<input type="text" placeholder="titre de votre annonce" name="article_titre" /> <br/>
<label>description de votre annonce</label>
<textarea name = "article_description" rows = "5" cols = "40" placeholder="décrivez votre annonce en insistant sur les mots clés pour attirer le plus de visiteurs possible"> </textarea> <br/>
<label>veuillez seletionner la catégorie de votre article</label>
<input type="radio" name="categorie" value="Livres">Livres
<input type="radio" name="categorie" value="Sport">Sports en tout genre
<br/> <br/>
<label>veuillez seletionner la catégorie de votre article</label>
<input type="radio" name="wilaya" value="25">Constantine
<input type="radio" name="wilaya" value="31">Oran
<br/> <br/>
<td>Que souhaitez-vous faire de votre objet ?:</td> <br/>
<td>
<input type = "radio" name = "typeannonce" value = "vente">vendre seulement
<input type = "radio" name = "typeannonce" value = "échange">troquer seulement
<input type = "radio" name = "typeannonce" value = "indécis">Je suis indécis
</td>
<br/>
<input type="submit" value="envoyer l'article" >
<?php
if (isset($erreur))
{
echo $erreur;
}
?> <br/>
<?php
if (isset($erreur))
{
echo $erreur;
}
?>
<button name="revenirprofil">revenir au profil</button>
</form>
</body>
</html>
Well, the page shows three errors :
Notice: Undefined index: categorie in C:\wamp\www\projet3\formulaireajout.php on line 44
Notice: Undefined index: typeannonce in C:\wamp\www\projet3\formulaireajout.php on line 45
Notice: Undefined index: wilaya in C:\wamp\www\projet3\formulaireajout.php on line 46
but surprisingly, the code still works and the the 3 notices disappear after completing and sending the form to the database. Everything works just fine apart from the mysterious 3 errors which are not truly errors
My second problem may look like a typing error in the SQL query but still not able to find the problem.
I am trying to update the informations sent to the database with the previous form.
Here is the SQL :
$update=$bdd->prepare('UPDATE articles SET titre_article= ?, description=?,catégorie=?,type_article=?,wilaya=?,fk_membres_id=? WHERE id = ?' );
$update->execute(array($article_titre,$article_description,$CAT,$TYPE,$WILA,$fk_membres_id,$fk_membres_id));
die('Edit successful');
I'm getting 'edit successful' but still no changes are being made in my DB. You would normally expect changes to be applied to the desired line but nothing seems to change
Thank you for reading. (hoping it's not something I'm missing in the query)
Its because your php code is getting executed as soon as the page loads irrespective of whether you have submitted the form or not. And until you haven't submitted the form, the $_POST global variable doesn't have access to categorie, typeannoance and wilaya.
And when you submit it, well, those values are accessible by the $_POST global variable and that's why those notices disappear.
Try to check their existence first with isset() function and that should solve your problem
i'm creating a member area ! i included a condition in order to insert a profile picture for the member
it dosen't show any errors ! The problem is that the picture cannot be inserted into the base what should i do ?
HTML:
<form method="POST" action="" enctype="multipart/form-data">
<label >Pseudo : </label>
<input name="newpseudo" type="text" placeholder="pseudo" value="<?php echo $user['pseudo']; ?>" /><br/><br/>
<label>email : </label>
<input name="newmail" type="email" placeholder="mail" value="<?php echo $user['mail'];?>" /><br/><br/>
<label>mot de passe : </label>
<input name="newmdp1" type="password" placeholder="mot de passe"/><br/><br/>
<label>confirmation du mot de passe : </label>
<input name="newmdp2" type="password" placeholder="confirmation du mot de passe"/><br/><br/>
<label>avatar :</label>
<input type="file" name="avatar"></input><br/><br/>
<input type="submit" name="formedition" value="Mettre a jour mon profil !">
</form>
PHP:
<?php
if(isset($_FILES['avatar']) and !empty($_FILES['avatar']['name']))
{
$tailleMax = 2097152;
$extensionsValides = array('jpg','jpeg','gif','png');
if($_FILES['avatar']['size'] <= $tailleMax)
{
$extensionUpload = strtolower(substr(strrchr($_FILES['avatar']['name'], '.'), 1));
if(in_array($extensionUpload, $extensionsValides))
{
$chemin = "membres/avatars/".$_SESSION['id'].".".$extensionUpload;
$resultat = move_uploaded_file($_FILES['avatar']['tmp_name'], $chemin);
if($resultat)
{
$updateAvatar = $bdd -> prepare('UPDATE membres SET avatar = ? WHERE id=?');
$updateAvatar -> execute(array(
'avatar' => $_SESSION['id'].".".$extensionUpload ,
'id ' => $_SESSION['id']
));
header("location:profil.php?id=" . $_SESSION['id']);
}
else
{
$msg = " erreur lors de l'importation de votre photo de profil ";
}
}
else
{
$msg =" votre photo de profil doit etre au forme de jpeg png gif ou jpg";
}
}
else
{
$msg = "votre photo de profil ne doit pas depasse 2 MO ! ";
}
}
?>
This is not a solution, but rather a series of steps you can take to QUICKLY solve this problem yourself.
"Divide and conquer". Instead of troubleshooting the entire app, all at once, break it up into smaller pieces (temporarily, for testing) and troubleshoot each piece.
First, copy your PHP code into a separate file - test.php or some such. Hard code some information to replace the data received in the $_POSTs, and run the file. Does the data go into the database? Probably not. Fix that and copy the fix into your original PHP file. Is everything fixed now?
If not, then copy your original PHP file and call it test2.php. Now, instead of putting the data into the database, just echo it out to the screen. What do you see?
Create a log file and write messages into it at various points in the code. Because PHP does not usually abort with an error message -- it just silently stops -- you need to give yourself some "eyes" to see what's going on:
$handle = fopen('__logfile.txt','a');
$line = 'Got to here 01' . "\n";
fwrite($handle, $line);
fclose($handle);
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!
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!