php and html insert picture in the data base - php

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);

Related

Undefined array key "image" and Trying to access array offset on value of type null and Uncaught ValueError: Path cannot be empty error

I want to insert an image in the database. The field in the database is of type longblob but I constantly get an error.
I changed form method from POST to GET but I still have the same problem. I tried to verify each input name with if(isset()) but I have the same problem.
HTML code
<form method="post" action="contact.php" enctype="multipart/form-data">
<?php
if(isset($error)){
foreach($error as $error){
echo '<span class="error-msg">'.$error.'</span>';
};
};
?>
<div class="control-group">
<input type="text" class="form-control border-0 p-4" name ="matricule" required placeholder="Matricule" />
<p class="help-block text-danger"></p>
</div>
<div class="control-group">
<input type="text" class="form-control border-0 p-4" name ="residence" required placeholder="Quartier de residence" />
<p class="help-block text-danger"></p>
</div>
<div class="drag-area">
<div class="icon"><i class="fas fa-cloud-upload-alt"></i></div>
<header>Glisser & Deposser le photo de votre CNI</header>
<span>OR</span>
<button type="button">Importer Fichier </button>
<input type="file" name="image" hidden required >
</div>
<div class="drag-area1">
<div class="icon"><i class="fas fa-cloud-upload-alt"></i></div>
<header class="header">Glisser & Deposser la photo de votre recu </header>
<span>OR</span>
<button class="button" type="button">Importer Fichier </button>
<input type="file" name="img" hidden class="input" required >
</div>
PHP code
<?php
#include 'connect.php';
if($_SERVER['REQUEST_METHOD']=="POST")
{
if(isset($_POST['submit'])){
if(isset($_POST['matricule']) || isset($_POST['residence']) || isset($_POST['image']) || isset($_POST['img'])){
$matricule = $_POST['matricule'];
$residence = $_POST['residence'];
$image1 = $_FILES['image']['tmp_name'];
$image1 = base64_encode(file_get_contents(addslashes($image1)));
$image2 = $_FILES['img']['tmp_name'];
$image2 = base64_encode(file_get_contents(addslashes($image2)));
}
$age = "SELECT *, DATEDIFF(CURDATE(),DATENAISSANCE) AS nbjour FROM etudiant WHERE MATRICULE = '$matricule'";
$rb = mysqli_query($conn,$age);
while($list = mysqli_fetch_array($rb)){
extract($list);
$age = floor($nbjour/365);
}
$sql ="SELECT * FROM etudiant WHERE MATRICULE = '$matricule'";
$sqp = "SELECT * FROM candidat WHERE MATRICULE = '$matricule'";
$result = mysqli_query($conn,$sql);
$result1 = mysqli_query($conn,$sqp);
if(mysqli_num_rows($result1) > 0)
{
$error[] = "vous avez deja une candidature";
}
if(mysqli_num_rows($result) > 0 && $age < 23){
$insert = "INSERT INTO candidat(MATRICULE,RESIDENCE,CNI,RECUEPAIEMENT) VALUES('$matricule','$residence','$image1','$image2')";
mysqli_query($conn,$insert);
$error[] = "Votre candidature a ete envoyer avec success";
}else
if($age >= 23){
$error[] = "Desoler vous ne pouvez plus postuler pour une chambre car vous avez plus de 22 ans".$age;
// }else
// if(isset($image1) == false){
// $error[] = "Selectionner l'image de votre CNI";
// }else
// if(isset($image2) == false){
// $error[] = "Selectionner l'image de vos recus ";
}else{
$error[] = "Vous n'etes pas inscrite";
}
}
}
?>
I tried using if(isset($_POST[''])) on all my input name files but it still gives me the same errors.
I tested your code on my server and the data from the form is just posting.
If the image is not posting on your server then maybe you need to change some settings in your php.ini and check your phpinfo to make sure the limits are correct on your server.
If you type in php phpinfo();, reload the page and then search for upload_max_filesize and post_max_size the value of that is then probably 2M and 8M. The values can be adjusted with the ini_set() function or adjust the value in your php.ini file.
<?php
// Adjust the values to your needs
ini_set('post_max_size', '6M');
ini_set('upload_max_filesize', '10M');
Or in php.ini find and change:
post_max_size=6M
upload_max_filesize=10M
Always make sure that the post limit is a bit higher then your file limit. Also check the allowed number of files your server can handle in 1 post by checking the max_file_uploads value, most times the value is by default 20.
Also to prevent undefined errors always first check if the posted data exist before using it. And also make sure the file that is uploaded is for sure an image.
Storing the images in the database as a base64 string is not the best solution, you can better safe the image after validation in a directory and save the image name in a database column. This will keep your database size allot smaller and will make your application over time allot faster

PHP SQL UPDATE problem and undefined variables [closed]

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

PHP Boolean not set

I'm trying to upload an image to my local server but a boolean value is not set in my code .
I include a php file to upload the file and do my checks there .
There is no error during the process but my variable is still not set.
Verification.php
// Verification si une image a été sélectionné :
if(isset($_POST['photo']) && !empty($_POST['photo']))
{
// Upload l'image dans le dossier upload si tout est valide
include_once "upload.php";
$uploaded = true;
}
//$bdd->query('INSERT INTO users(pseudo,email,password,birthday) VALUES(');
$req = $bdd->prepare('INSERT INTO users(pseudo,email,password,DateInscription,Photo) VALUES(:identifiant,:email,:password,NOW(),:photo)');
$req->execute(array(
'identifiant' => $_POST["pseudo"],
'email' => $_POST["email"],
'password' => cryptPassword($_POST["password"]),
'photo' => isset($uploaded) == true ? $directory : "test",
));
Upload.php
$form_name = "photo";
$max_size = 5000000; // = 5 MO
$validExtension = array('png','gif','jpg','jpeg');
$directory = "uploads/" .$_POST["pseudo"];
// Vérification si l'image s'est bien uploadé
if(!isset($_FILES[$form_name]) OR $_FILES[$form_name]['error'] > 0 )
{
$error = "codeerreur : " .$_FILES[$form_name]['error'];
header("Location: http://localhost/serveur_web/inscription.php?error-photo=invalid_upload" .$error);exit;
}
// Vérification si l'image est trop lourde : > 5 MO
if($_FILES[$form_name]['size'] > $max_size) header("Location: http://localhost/serveur_web/inscription.php?error-photo=invalid_size");exit;
// Verification de l'extension de l'image
$imageExtension = substr(strrchr($_FILES[$form_name]['name'],'.'),1);
if(!in_array($imageExtension,$validExtension)) header("Location: http://localhost/serveur_web/inscription.php?error-photo=invalid_extension");exit;
// tout est ok déplacement de l'image dans le dossier
if(!move_uploaded_file($_FILES[$form_name]['tmp_name'],$directory))
{
header("Location: http://localhost/serveur_web/inscription.php?error-photo=move");
exit;
}
This part of the code : isset($uploaded) == true ? $directory : "test" always return : test .
Thank you for help.
EDIT : I already have enctype definition in my html code
<form accept-charset="UTF-8" method="post" action="verif.php?protocol=inscription" enctype="multipart/form-data">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Pseudo" name="pseudo" type="text">
</div>
<div class="form-group">
<input class="form-control" placeholder="E-mail" name="email" type="text">
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="password" type="password" value="">
</div>
<div class="form-group">
<input class="form-control" placeholder="Confirm Password" name="password_confirm" type="password" value="">
</div>
<div class="form-group">
<input class="form-control" placeholder="Photo de profil" name="photo" type="file" value="">
</div>
<input class="btn btn-lg btn-success btn-block" type="submit" value="Inscription">
</fieldset>
</form>
You have problem in this line
'photo' =>isset($uploaded) == true ? $directory : "test"
change this line to
'photo' =>($uploaded === true) ? $directory : "test";
if $uploaded is set true then it takes $directory value and if it is set to false then it takes "test"
set $upload to false in Verification.php
$uploaded = false;
if(isset($_FILES['photo']) && !empty($_FILES['photo']))
{
include_once "upload.php";
$uploaded = true;
}

Block of code php appear after a form [duplicate]

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

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