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;
}
Related
I'm having a problem and I can't find a solution. I'm getting this error "Notice: Undefined variable: id_horaire". But I defined it and I don't know how to fix that.
Here's my code :
<?php
require_once '../database.php';
if (!$_SESSION['admin']) {
header('location:login.php');
exit();
}
if(isset($_GET['id']) AND !empty($_GET['id'])) {
$id_horaireSecure = htmlspecialchars($_GET['id']);
$id_horaire = $db->prepare('SELECT * FROM runaway.horaire WHERE id = ?');
$id_horaire->execute(array($id_horaireSecure));
}
if(!empty($_POST['heure_ouverture']) AND !empty($_POST['heure_fermeture'])) {
$heure_ouverture = ($_POST['heure_ouverture']);
$heure_fermeture = ($_POST['heure_fermeture']);
$update = $db->prepare('UPDATE runaway.horaire SET heureOuverture=?, heureFermeture=?');
$update->execute(array($heure_ouverture, $heure_fermeture));
$message = "L'horaire a bien été mise à jour";
header('location:login.php');
exit();
} else {
$message = 'Les champs ne sont pas tous remplis';
}
?>
<div class="phpContainer">
<h2>Changer les horaires d'ouverture du Lundi</h2>
<div class="form col-12">
<div class="contact-form container">
<form method="post" enctype="multipart/form-data">
<div class="input-container">
<input type="text" name="heure_ouverture" class="input" value="<?=$id_horaire['heureOuverture'] ?>" />
<label for="">Heure d'ouverture</label>
<span>Heure d'ouverture</span>
</div>
<div class="input-container">
<input type="text" name="heure_fermeture" class="input" value="<?=$id_horaire['heureFermeture'] ?>" />
<label for="">Heure de fermeture</label>
<span>Heure de fermeture</span>
</div>
<input type="submit" value="Modifier l'horaire" class="boutonForm">
</form>
</div>
</div>
<br>
<?php if(isset($message)) {
echo $message;
}
?>
</div>
Thank you !
ps: I'm french, which is why some variables and text may seem strange to you
The problem is you declare $id_horaire only if this condition isset($_GET['id']) AND !empty($_GET['id']) met.
You can either give it a default value before the if, or you need to change your logic.
I'm currently working on a school project and i'm trying to upload a "post" of a recipe. this includes image, title, instructions,ingredients and also 1 or multiple categories.
all of them insert fine and well. the only issue is with the categories. It only inserts 1 category even if I select multiple checkboxes.
It's supossed to insert every checkbox into a new row in the database.
My DAO
public function insertCategory($data, $title) {
if (empty($errors)) {
$sql = "INSERT INTO `recipes_categories` (`category_id`, `recipe_id`) VALUES(:category_id,:recipe_id);";
$stmt = $this->pdo->prepare($sql);
$stmt->bindValue(':category_id', $data['category_id']);
$stmt->bindValue(':recipe_id', $title['id']);
if ($stmt->execute()) {
return $this->selectcategoryById($this->pdo->lastInsertId());
}
}
return false;
}
My Controller (relevant parts)
public function upload() {
// variabele om foutmelding bij te houden
$error = '';
// controleer of er iets in de $_POST zit
if(!empty($_POST['action'])){
// controleer of het wel om het juiste formulier gaat
if($_POST['action'] == 'add-image') {
// controleren of er een bestand werd geselecteerd
if (empty($_FILES['image']) || !empty($_FILES['image']['error'])) {
$error = 'Gelieve een bestand te selecteren';
}
if(empty($error)){
// controleer of het een afbeelding is van het type jpg, png of gif
$whitelist_type = array('image/jpeg', 'image/png','image/gif');
if(!in_array($_FILES['image']['type'], $whitelist_type)){
$error = 'Gelieve een jpeg, png of gif te selecteren';
}
}
if(empty($error)){
// controleer de afmetingen van het bestand: pas deze gerust aan voor je eigen project
// width: 270
// height: 480
$size = getimagesize($_FILES['image']['tmp_name']);
if ($size[0] < 100 || $size[1] < 100) {
$error = 'De afbeelding moet minimum 100x100 pixels groot zijn';
}
}
if(empty($error)){
// map met een random naam aanmaken voor de upload: redelijk zeker dat er geen conflict is met andere uploads
$projectFolder = realpath(__DIR__);
$targetFolder = $projectFolder . '/../assets/ads';
$targetFolder = tempnam($targetFolder, '');
unlink($targetFolder);
mkdir($targetFolder, 0777, true);
$targetFileName = $targetFolder . '/' . $_FILES['image']['name'];
// via de functie _resizeAndCrop() de afbeelding croppen en resizen tot de gevraagde afmeting
// pas gerust aan in je eigen project
$this->_resizeAndCrop($_FILES['image']['tmp_name'], $targetFileName, 100, 100);
$relativeFileName = substr($targetFileName, 1 + strlen($projectFolder));
$data = array(
'image' => $relativeFileName,
'title' => $_POST['title'],
'instructions' => $_POST['stappenplan'],
'description' => $_POST['ingredienten'],
'category_id' => $_POST['category'],
);
// TODO: schrijf de afbeelding weg naar de database op basis van de array $data
if (!empty($_POST['action'])) {
if ($_POST['action'] == 'add-image') {
// array met data invullen
$data = array(
'path' => '/' . $relativeFileName,
'title' => $_POST['title'],
'instructions' => $_POST['stappenplan'],
'description' => $_POST['ingredienten'],
'category_id' => $_POST['category'],
);
// aanspreken van de DAO
$insertImage = $this->uploadDAO->insertImage($data);
$title = $this->uploadDAO->ImageInsterId($data);
$this->set('title', $title);
$ingredientsArray = explode( ',', $data['description'] );
foreach($ingredientsArray as $ingredient){
$insertIngredient = $this->uploadDAO->insertIngredients($ingredient , $title);
}
$insertCategory = $this->uploadDAO->insertCategory($data, $title);
// TODO 2: zorg dat de variabele $error getoond wordt indien er iets fout gegaan is
if (!$insertImage) {
$errors = $this->uploadDAO->validate($data);
$this->set('errors', $errors);
} else {
$_SESSION['info'] = 'Thank you for adding a Post!';
header('Location: index.php?page=detail&id='. $title['id']);
exit();
}
}
}
}
}
}
There is some code here for the image upload too, but it isn't relevant since that is working.
My HTML
<span class="error"><?php if(!empty($error)){ echo $error;} ?></span>
<section class="upload_box">
<h1 class="hidden">upload-form</h1>
<form method="post" action="index.php?page=upload" enctype="multipart/form-data" class="form__box">
<input type="hidden" name="action" value="add-image" />
<div class="form-field">
<label class="upload__title form_container">Kies een afbeelding
<span class="error"><?php if(!empty($errors['title'])){ echo $errors['title'];}?></span>
<input type="file" name="image" accept="image/png, image/jpeg, image/gif" required class="upload__button filter__submit input">
</label>
</div>
<div class="form-field">
<label class="upload__title form_container">Titel
<span class="error"><?php
if(!empty($errors['title'])){
echo $errors['title'];} ?></span>
<input type="text" name="title" required class="upload__title form_field input">
</label>
</div>
<div class="form-field">
<label class="upload__title form_container">Stappenplan
<span class="error"><?php if(!empty($errors['instructions'])){ echo $errors['instructions'];} ?></span>
<textarea name="stappenplan" id="stappenplan" cols="50" rows="5" required class="form_field upload__title input"></textarea>
</label>
</div>
<div class="form-field">
<label class="upload__title form_container">Ingredienten
<span class="error"><?php if(!empty($errors['description'])){ echo $errors['description '];} ?></span>
<input type="text" TextMode="MultiLine" name="ingredienten" maxlength="255" required class="form_field upload__title input" id="ingredienten">
</label>
</div>
<div class="category_container">
<label class="category_label filter__button">
<input class="category_input" type="checkbox" id="pasta" name="category" value="1">
Pasta</label>
<label class="category_label filter__button">
<input class="category_input" type="checkbox" id="veggie" name="category" value="2">
Veggie</label>
<label class="category_label filter__button">
<input class="category_input" type="checkbox" id="vlees" name="category" value="3">
Vlees</label>
</div>
<div class="form-field">
<input type="submit" value="uploaden" class="filter__button filter__submit">
<input type="reset" value="wissen" class="filter__button filter__submit">
</div>
</form>
</section>
<script src="js/validate.js"></script>
What I do know:
I know the recipe_id isn't an issue. I use the same for other SQL inserts.
I don't want an explode() or implode() as they don't work in this case.
Tried several foreaches but haven't gotten it to work, just yet.
it's also nothing to do with brackets or comma's or whatever.
It's just the insert only doing it once while I have 2 checkbox values. and I don't know how to make it loop over both or all 3 when all 3 are selected
<div class="category_container">
<label class="category_label filter__button">
<input class="category_input" type="checkbox" id="pasta" name="category[]" value="1">
Pasta</label>
<label class="category_label filter__button">
<input class="category_input" type="checkbox" id="veggie" name="category[]" value="2">
Veggie</label>
<label class="category_label filter__button">
<input class="category_input" type="checkbox" id="vlees" name="category[]" value="3">
Vlees</label>
</div>
You need to use category[], rather than just category to send multiple values in form submit.
Now, you can fetch the values of categories
$categories = (is_array($_POST['category'])) ? $_POST['category'] : [];
I have assigned categories a default value if there is no checkbox selected.
Then use implode function of php:
$categories_string = implode(',', $categories);
or use a foreach loop based on how you want to save in your database table:
foreach ($category as $category)
{
//use each category
}
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 created a login script where I am simply trying to match the email and password that is passed through my login form, create a session and pass through session variables and redirect the user to his account's page. This is returning bool(false)...
When registering a user I encrypt the password using the PHP password_hash method. However when I try to login my statement is returned as false and to be fair I don't know what I am doing wrong, perhaps I'm decrypting the password incorrectly, I'm not sure.
When I tried to debug it. Can't find out why it's happening.
Any help or ideas greatly welcomed and appreciated, thank you in advance.
Here is my script :
class Auth.php
public function login($db, $email, $mdp, $remember = false)
{
$user = $db->query('SELECT * FROM client WHERE (email = :email) AND confirmed_at IS NOT NULL ', ['email' => $email])->fetch(PDO::FETCH_OBJ);
/*var_dump( password_verify($mdp,($user->mdp)));*/
print_r($db->errorInfo());
if ($user && password_verify($mdp,($user->mdp)))
{ $this->connect($user);
if ($remember) {
$this->remember($db, $user->id_clt);
} //for cookie key
return $user;
} else {
return false;
}
}
login.php
<?php
require 'inc/bootstrap.php';
$auth = App::getAuth();
$db = App::getDatabase();
$auth->connectFromCookie($db);
if($auth->userLogged()){
App::redirect('account.php');
}
if(!empty($_POST) && !empty($_POST['email']) && !empty($_POST['mdp'])){
$user = $auth->login($db, $_POST['email'], $_POST['mdp'], isset($_POST['remember']));
$session = Session::getInstance();
var_dump($user);
if($user){
$session->setFlash('success' , 'Vous êtes maintenant connecté');
App::redirect('account.php');
}else{
$session->setFlash('danger', 'Identifiant ou mot de passe incorrecte');
}
}
?>
<?php require 'inc/header2.php'; ?>
<h1 align="center"> Se connecter </h1>
<form method="POST" action="" autocomplete="on">
<div class="form-group" align="center">
<label for="email">Email</label>
<input id="email" name="email" type="email" class="form-control"/>
</div>
<div class="form-group" align="center">
<label for="mdp" >Mot de passe (J'ai oublié mon mot de passe)</label>
<input id="mdp" name="mdp" type="password" class="form-control"/>
</div>
<div class="form-group" align="center">
<label>
<input type="checkbox" name="remember" value="1"> Se souvenir de moi
</label>
<button type="submit" name="forminscription" class="btn btn-primary">Se connecter</button>
</div>
<?php require 'inc/footer.php'; ?>
I'm using a form on my website using wordpress to allow users to create posts.
It works perfectly fine, I'm abble to assign the posts to a custom post type, add Advanced Custom Fields, content, tags...
What I'm trying to do is to allow the user to also upload images, using the same coding architecture, as it works fine this way since.
User don't have to be registred, so when uploading an image, He'll be abble to browse is computer and then upload the image.
the image should then be saved in my media library and database, and assign to the post.
I want to be abble to assign images to post_tumbnails for example, or to custom fields.
8 new inputs for 8 images in my form.
image_1
image_2, and so on...
like this : , and then being abble to use the image object inside my insert array.
here is my php code :
<?php
if(isset($_POST['submit'])){
$err = array();
$err['status'] = true;
$output = "";
if(empty($_POST['nom'])){
$err['status'] = false;
$err['msg'][] = 'Le champ "Nom" ne peut être vide.';
}
if(empty($_POST['prenom'])){
$err['status'] = false;
$err['msg'][] = 'Le champ "Nom" ne peut être vide.';
}
if(empty($_POST['telephone'])){
$err['status'] = false;
$err['msg'][] = 'Le champ "Nom" ne peut être vide.';
}
if(empty($_POST['#mail']) || !preg_match('/[a-zA-Z0-9._-]+#[a-zA-Z0-9._-]+\.[a-zA-Z]{2,4}/',$_POST['#mail'])){
$err['status'] = false;
$err['msg'][] = 'Le champs "Mail" est mal renseigné';
}
if($err['status']){
$insert = array(
'post_status' => 'publish',
'post_title' => $_POST ['nom'] . ' ' . $_POST ['prenom'],
'post_category' => array(11),
'post_author' => 999,
'tags_input' => htmlentities($_POST['tags']),
'post_type' => 'vendre',
);
$post_id = wp_insert_post($insert);
if($post_id != 0){
/* CUSTOM FIELDS */
update_field('field_546f2983c57ae',htmlentities($_POST['civilite']),$post_id);
update_field('field_546f22db11f3e',htmlentities($_POST['nom']),$post_id);
update_field('field_546f22e011f3f',htmlentities($_POST['prenom']),$post_id);
update_field('field_546f22e611f40',htmlentities($_POST['adresse']),$post_id);
update_field('field_546f22f311f41',htmlentities($_POST['code_postal']),$post_id);
update_field('field_546f230211f42',htmlentities($_POST['ville']),$post_id);
update_field('field_546f230811f43',htmlentities($_POST['pays']),$post_id);
update_field('field_546f230d11f44',htmlentities($_POST['telephone']),$post_id);
update_field('field_546f231611f45',htmlentities($_POST['#mail']),$post_id);
update_field('field_546f232011f46',htmlentities($_POST['localisation']),$post_id);
update_field('field_546f232611f47',htmlentities($_POST['prix_souhaite']),$post_id);
update_field('field_546f233211f48',htmlentities($_POST['description_']),$post_id);
$output = add_post_meta($post_id, "user_meta", json_encode($user_meta_values)) ? 'Article inséré avec succès.' : 'Une erreur est survenue lors de l\enregistrement.' ;
}
}
else{
foreach($err['msg'] as $k=>$v)
$output .= $v . '<br />';
}
}
?>
and my Html :
<form method="post" action="<?php echo site_url().'/vendre'; ?>">
<label class="civilite">M.</label><input type="radio" name="civilite" id="civilite" value="monsieur">
<label class="civilite">Mme</label><input type="radio" name="civilite" id="civilite" value="madame"> <br>
<label for="nom">Nom</label><input type="text" name="nom" id="nom" value="" /><br>
<label for="prenom">Prénom</label><input type="text" name="prenom" id="prenom" value="" /><br>
<label for="adresse">Adresse</label><input type="text" name="adresse" id="adresse" value="" /><br>
<label for="code_postal">Code Postal</label><input type="text" name="code_postal" id="code_postal" value="" /><br>
<label for="ville">Ville</label><input type="text" name="ville" id="ville" value="" /><br>
<label for="pays">Pays</label><input type="text" name="pays" id="pays" value="" /><br>
<label for="telephone">Téléphone</label><input type="text" name="telephone" id="telephone" value="" /><br>
<label for="#mail">#mail</label><input type="text" name="#mail" id="#mail" value="" /><br>
<label for="localisation">Localisation</label><input type="text" name="localisation" id="localisation" value="" /><br>
<label for="prix_souhaite">Prix souhaité</label><input type="text" name="prix_souhaite" id="prix_souhaite" value="" /><br>
<label for="description_">Description rapide de votre bien et commentaires</label><textarea name="description_" id="description_" rows="10" cols="15"></textarea><br>
<p><input type="submit" name="submit" value="envoyer" /></p>
</form>
<div class="ok"><?php echo isset($output) ? $output : '' ; ?></div>
hope someone can help me with this,
thanks a lot