upload images on front by user - 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

Related

inserting multiple checkboxes into MySQL (PDO)

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
}

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

php and html insert picture in the data base

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

How to change div content in PHP?

I want to change the div's id intFrom. Content after inserting data to the database, I want the code not just echo ¡Enhorabuena!...
But replace the form with ¡Enhorabuena! I maybe, I could replace the form using AJAX.
Here is the code:
HTML
<form method="post" action="">
<div>
<select value="genero" name="genderselect" id="genero" required="required" autofocus="autofocus">
<option value="none" selected>- Selecciona Género - </option>
<option value="Mujer">Mujer</option>
<option value="Hombre">Hombre</option>
</select>
<input type="text" id="name" name="name" value="" placeholder="Nombre completo" required="required" autofocus="autofocus" />
<input type="email" id="email" name="email" value="" placeholder="Correo electrónico" required="required" />
</div>
<div>
<div class="infForm img">
<img src="http://www.miraqueguapa.com/Landings/General/img/biotherm.png" alt="Imagen Crema Aquasource Biotherm" class="biotherm">
</div>
<div class="infForm text">
<div class="legal">
<input type="checkbox" id="cblegales" value="1" name="cblegales" required="required" autofocus="autofocus">
<p>He leído y acepto la <a class="enlace_pp" href="http://www.miraqueguapa.com/content/5-privacidad-proteccion-datos" target="_blank">política de privacidad</a></p>
</div>
<input type="submit" value="ENVIAR DATOS" name="submit_form" style=" background-color: #DF2848;border: none;border-radius: 0px;color: white;width: 200px;float: right;padding-left: 50px;cursor: pointer;margin-top: -5px;" />
</div>
</div>
</form>
</div>
PHP
<?php
if (isset($_POST['submit_form'])) {
include 'connection.php';
$name=$_POST["name"];
$email=$_POST["email"];
$gender=$_POST["genderselect"];
if($gender=="none"){
echo"</br>";
echo"por favor selecciona nuestro género";
$link = null;
}
else{
$i=0;
$statement = $link->prepare("select email from webform where email = :email");
$statement->execute(array(':email' => "$email"));
$row = $statement->fetchAll();
foreach($row as $key) {
$i=$i+1;
}
if ($i !=0) {
echo" Este correo electrónico ya está registrado";
$link = null;
}
else{
$statement = $link->prepare("INSERT INTO webform(name, email, gender)
VALUES(:name, :email, :gender)");
$statement->execute(array(
"name" => "$name",
"email" => "$email",
"gender" => "$gender"
));
$link = null;
echo"¡Enhorabuena!"."<br/>";
echo"Tus datos se han enviado correctamente. A partir de ahora recibirás cada semana las últimas novedades y las mejores ofertas en Cosmética de las marcas más prestigiosas del mercado.";
}}}
?>
You need to add simple if else statement.
if (isset($_POST['submit_form'])) {
// Your code after form get submitted.
}
else {
// Show default form.
}
Just load your HMTL Code in to your PHP as a kind of "Template" with file_get_contents(__DIR__ . "Path/To/Your.html"); in to a variable and do a simple str_replace('id="your_element_id"', 'id="replace_id"', $template_variable); and echo your Template after if you just want to replace an ID.
If you want to change something within the Form, do it as i said above with str_replace('tag_you_are_looking_for', 'should_be_replaced_with', $template_variable);

php wp_insert data on front using a form

I'm using a form on my website to allow user to create posts on my wordpress admin.
It works fine, but I have an issue, I don't get the tags meta inside my admin.
here is my php code :
<?php
if(isset($_POST['submit'])){
$err = array();
$err['status'] = true;
$output = "";
if(empty($_POST['pseudo'])){
$err['status'] = false;
$err['msg'][] = 'Le champ "Pseudo" 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(empty($_POST['title'])){
$err['status'] = false;
$err['msg'][] = 'Le champ "Titre" ne peut être vide.';
}
if(empty($_POST['content'])){
$err['status'] = false;
$err['msg'][] = 'Le champ "Article" ne peut être vide.';
}
if($err['status']){
$insert = array(
'post_status' => 'publish',
'post_title' => htmlentities($_POST['title']),
'post_content' => htmlentities($_POST['content']),
'post_category' => array(11),
'post_author' => 999,
);
$post_id = wp_insert_post($insert);
if($post_id != 0){
/*
TAGS
*/
if(!empty($_POST['keywords'])){
$keywords = explode(',',$_POST['keywords']);
foreach($keywords as $k=>$v){
$tag = trim(strip_tags($v));
wp_insert_term(
$tag,
'post_tag',
array(
'slug' => sanitize_title($tag)
)
);
}
}
$user_meta_values = array(
'pseudo' => htmlentities($_POST['pseudo']),
'mail' => $_POST['mail']
);
$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 />';
}
}
?>
my html form :
<form method="post" action="<?php echo site_url().'/ajouter'; ?>">
<p><label for="pseudo">Pseudo</label><input type="text" name="pseudo" id="pseudo" value="" /></p>
<p><label for="mail">Mail</label><input type="text" name="mail" id="mail" value="" /></p>
<p><label for="title">Titre</label><input type="text" name="title" id="title" value="" /></p>
<p><label for="content">Article</label><textarea name="content" id="content" rows="10" cols="15"></textarea></p>
<p><label for="keywords">Mots clés</label><input type="text" name="keywords" id="keywords" value="" /> ( séparez les mots clés par des virgules )</p>
<p><input type="submit" name="submit" value="enregistrer" /></p>
</form>
Anyone know what I'm doing wrong ? can't find out why it's not working,
thanks for your help

Categories