I am trying to upload images using php and html form.
<form class="form-horizontal" method="POST" action="products_photo.php" enctype="multipart/form-data">
<input type="hidden" class="prodid" name="id">
<div class="form-group">
<label for="photo" class="col-sm-3 control-label">Photo</label>
<div class="col-sm-9">
<input type="file" id="photo" name="photo" required>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default btn-flat pull-left" data-dismiss="modal"><i class="fa fa-close"></i> Close</button>
<button type="submit" class="btn btn-success btn-flat" name="upload"><i class="fa fa-check-square-o"></i> Update</button>
</form>
But the issue is png extensions are not being saved to database. jpg and jpeg are stored.
Anyone has an idea how to solve this?
I am using a function to make slug for images, but the extensions for jpg and jpeg are stored in database but not for png files.
the php file:
<?php
if(isset($_POST['upload'])){
$id = $_POST['id'];
$filename = $_FILES['photo']['name'];
$conn = $pdo->open();
$stmt = $conn->prepare("SELECT * FROM products WHERE id=:id");
$stmt->execute(['id'=>$id]);
$row = $stmt->fetch();
if(!empty($filename)){
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$new_filename = $row['slug'].'_'.time().'.'.$ext;
move_uploaded_file($_FILES['photo']['tmp_name'], '../images/'.$new_filename);
}
try{
$stmt = $conn->prepare("UPDATE products SET photo=:photo WHERE id=:id");
$stmt->execute(['photo'=>$new_filename, 'id'=>$id]);
$_SESSION['success'] = 'Product photo updated successfully';
}
catch(PDOException $e){
$_SESSION['error'] = $e->getMessage();
}
$pdo->close();
}
else{
$_SESSION['error'] = 'Select product to update photo first';
}
?>
Related
I want to update my profile image but I don't know how to update it. I successfully insert it into my database and folder but when user wants to update it So I don't know how to update this image. Can you tell me how this is possible? Thanks.
Code of my HTML form
<form class="form" action="accountsetting.php" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-12 col-sm-auto mb-3">
<div class="mx-auto" style="width: 140px;">
<div class="rounded-circle avatar avatar-xl mb-3">
<img class="rounded-circle" id="preview_avatar" name="avatar" src="<?php echo
$_SESSION['user']['avatar']; ?>" width="100" height="100">
</div>
</div>
</div>
<div class="col d-flex flex-column flex-sm-row justify-content-between mb-3">
<div class="text-center text-sm-left mb-2 mb-sm-0">
<h4 class="pt-sm-2 pb-1 mb-0 text-nowrap"><?php echo $_SESSION['user']['fullname']; ?></h4>
<p class="mb-0"><?php echo $_SESSION['user']['username']; ?></p>
<div class="form-group mb-2 pt-2">
<input class='input' type='hidden' name='id' value="<?php echo $_SESSION['user']['id']; ?>" />
<input id="avatar" type="file" name="avatar" hidden="" accept="image/png, image/jpeg,
image/jpg">
<button id="uploadBtn" type="submit" name="profile" class="btn btn-primary btn-file " ><i
class="fa fa-camera" aria-hidden="true"></i>   Upload Avatar</button>
</div>
<div class="row">
<div class="col d-flex justify-content-end pr-5">
<button class="btn btn-primary " type="submit" name="profileupdate">Save Changes</button>
</div>
</div>
</div>
</div>
</div>
</form>
Code of my PHP side
// sava image into directoray
$id="";
$filename = $avatar['name'];
$fileerror = $avatar['error'];
$filetmp = $avatar['tmp_name'];
$fileext = explode('.',$filename);
$filecheck = strtolower(end($fileext));
$fileextstored =array('png', 'jpg', 'jpeg');
$destinationfile = 'upload/';
$destinationfile = $destinationfile .$filename;
$destinationfile1 = 'userside/upload/';
$destinationfile1 = $destinationfile1 .$filename;
try {
//throw exception if can't move the file
if (!move_uploaded_file($filetmp, $destinationfile)) {
throw new Exception('Could not move file');
}
if(!copy ( $destinationfile , $destinationfile1 ))
{
throw new Exception('Could not move 2nd file');
}
}
catch(Exception $e) {
echo 'Message: ' .$e->getMessage();
}
// image insert
if(in_array($filecheck, $fileextstored))
{
$query = "INSERT INTO users (avatar) VALUES('$destinationfile')";
$displayquery = "select * from users where id= $id";
$displayquery = mysqli_query($db,$displayquery);
}
What's type of code i will use. When the user click on the save button the image will successfully update.
It looks like you need a condition in your INSERT INTO statement. Shouldn't you insert the avatar in the users table where id = $id?
Here:
"INSERT INTO users (avatar) VALUES('$destinationfile')";
Change to:
"INSERT INTO users (avatar) VALUES('$destinationfile') WHERE id = $id";
Update: if you're inserting the path to the image, then maybe you need to put the URL in with the image tag:
<!-- insert code for http or https:// -->
<img class="rounded-circle" id="preview_avatar" name="avatar" src="<?php echo "http://" . $_SERVER['SERVER_NAME'] . "/" . $_SESSION['user']['avatar']; ?>" width="100" height="100">
This relies on that path being valid and accessible from the server name, like http://localhost/uploads/image_name.jpg if the path is .../uploads/image_name.jpg. You can put the path in the session variable, then just add the image name on the end, e.g. $_SESSION['image_path'] = 'http://localhost/uploads/'.
I have an upload image to database code like this:
<form method="post" action="quanly.php" class="form-group justify-content-center" enctype="multipart/form-data">
<div class="custom-file mb-3">
<input type="file" class="custom-file-input" id="image" name="image">
<label class="custom-file-label" for="customFile">Choose file</label>
</div>
<div class="col text-center">
<button type="submit" name="submit" id="add_btn" class="btn btn-primary mb-2"> <i class="fas fa-plus"></i>Submit</button>
</div>
</form>
And the PHP code:
$image = addslashes($_FILES['image']['name']);
$query = "INSERT INTO tasks (image) VALUES ('$image')";
mysqli_query($db, $query); //db is the mysql connection
Everything upload works just fine, but I have some code to display image using Bootstrap 4 modal
<?php $i = 1; while ($row = mysqli_fetch_array($tasks)) { ?>
<button type="button" class="btn btn-primary btn-sm " data-toggle="modal" data-target="#imagemodal<?php echo $row['id'];?>" <?php if (empty($row['image'])) { echo "disabled"; } ?> ><i class="fas fa-image"></i></button>
<!-- IMAGE MODAL BEGIN -->
<div class="modal fade" id="imagemodal<?php echo $row['id'];?>">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Xem ảnh/ đính kèm</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<?php echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>'; ?>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- IMAGE MODAL END -->
<?php $i++; } ?>
Which image of rows showing a small image square (error), when I view the image url, it's something like this: data:image/jpeg;base64,ei5wbmc=
Store and upload image in folder code
<?php
if(isset($_POST['but_upload'])){
$name = $_FILES['file']['name'];
$target_dir = "upload/";
$target_file = $target_dir . basename($_FILES["file"]["name"]);
// Select file type
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Valid file extensions
$extensions_arr = array("jpg","jpeg","png","gif");
// Check extension
if( in_array($imageFileType,$extensions_arr) ){
// Insert record
$query = "insert into images(name) values('".$name."')";
mysqli_query($con,$query);
// Upload file
move_uploaded_file($_FILES['file']['tmp_name'],$target_dir.$name);
}
}
?>
<form method="post" action="" enctype='multipart/form-data'>
<input type='file' name='file' />
<input type='submit' value='Save name' name='but_upload'>
</form>
Show in display view.
<?php
$sql = "select name from images where id=1";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
$image = $row['name'];
$image_src = "upload/".$image;
?>
<img src='<?php echo $image_src; ?>' >
I cannot figure out why my form does not want to submit its data into my recipes table after clicking submit. When I click the submit button the form just refreshes,
I have an echo for successful set but it does not appear along with no error messages and no data in my database.
Here is the HTML
<div class="row">
<div class="main-login main-center">
<h1>Add Recipe</h1>
<form enctype="multipart/form-data" action="#" method="post">
<div class="form-group">
<label for="recipe_name" class="cols-sm-2 control-label">Recipe Name</label>
<div class="cols-sm-10">
<div class="input-group">
<input type="text" class="form-control" name="recipe_name" id="recipe_name" placeholder="Recipe Name"/>
</div>
</div>
</div>
<div class="form-group">
<label for="recipe_duration" class="cols-sm-2 control-label"> Recipe Duration </label>
<div class="cols-sm-10">
<div class="input-group">
<input type="text" class="form-control" name="recipe_duration" id="recipe_duration" placeholder="Recipe Duration"/>
</div>
</div>
</div>
<div class="form-group">
<label for="recipe_ingredient" class="cols-sm-2 control-label"> Ingredients </label>
<div class="cols-sm-10">
<div class="input-group">
<input type="text" class="form-control" name="recipe_ingredient" id="recipe_ingredient" placeholder="Ingredients"/>
</div>
</div>
</div>
<div class="form-group">
<label for="recipe_nutrition" class="cols-sm-2 control-label"> Recipe Nutrition </label>
<div class="cols-sm-10">
<div class="input-group">
<input type="text" class="form-control" name="recipe_nutrition" id="recipe_nutrition" placeholder="Recipe Nutrition"/>
</div>
</div>
</div>
<div class="form-group">
<label for="recipe_method" class="cols-sm-2 control-label"> Recipe Directions </label>
<div class="cols-sm-10">
<div class="input-group">
<input type="text" class="form-control" name="recipe_method" id="recipe_method" placeholder="Recipe Directions"/>
</div>
</div>
</div>
<div class="form-group">
<label for="profile_image">Recipe Image</label>
<input type="file" name="recipe_image" id="recipe_image">
<p class="help-block">Upload an image of the recipe</p>
<img class="recipeImage" src="./recipe_images/"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success btn-lg btn-block login-button">Submit</button>
</div>
</form>
</div>
and PHP
<?php
if(isset($_POST['submit'])){
//Insert DB
$query = "INSERT INTO recipes (recipe_name, recipe_duration, recipe_ingredient, recipe_nutrition, recipe_method) VALUES (:recipe_name, :recipe_duration, :recipe_in
gredient, :recipe_nutrition, :recipe_method)";
$result = $DBH->prepare($query);
$result->bindParam(':recipe_name', $_POST['recipe_name']);
$result->bindParam(':recipe_duration', $_POST['recipe_duration']);
$result->bindParam(':recipe_ingredient', $_POST['recipe_ingredient']);
$result->bindParam(':recipe_nutrition', $_POST['recipe_nutrition']);
$result->bindParam(':recipe_method', $_POST['recipe_method']);
if($target_file){
$result->bindParam(':recipeImage', $newFilename);
}
if($result->execute()){
echo '<div class="alert alert-success" role="alert">Recipe Added!</div>';
}
if($_FILES['recipeImage']["name"]){
//Let's add a random string of numbers to the start of the filename to make it unique!
$newFilename = md5(uniqid(rand(), true)).$_FILES["profile_image"]["name"];
$target_file = "./recipe_images/" . basename($newFilename);
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
$check = getimagesize($_FILES["recipeImage"]["tmp_name"]);
if($check === false) {
echo "File is not an image!";
$uploadError = true;
}
//Check file already exists - It really, really shouldn't!
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadError = true;
}
// Check file size
if ($_FILES["recipeImage"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadError = true;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadError = true;
}
// Did we hit an error?
if ($uploadError) {
echo "Sorry, your file was not uploaded.";
} else {
//Save file
if (move_uploaded_file($_FILES["recipeImage"]["tmp_name"], $target_file)) {
//Success!
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
}
?>
Because you have no element with name="submit" and you're testing for it here if(isset($_POST['submit'])){
Your submit should be an input, not a button:
<input type="submit" class="btn btn-success btn-lg btn-block login-button" value="Submit" />
<input type="submit" name="submit" value="Submit"class="btn btn-success btn-lg btn-block login-button">
change the submit button like this
<button type="submit" class="btn btn-success btn-lg btn-block login-button">Submit</button>
instead of
<input type="submit" class="btn btn-success btn-lg btn-block login-button" value="Submit" name="submit">
Change
<button type="submit" class="btn btn-success btn-lg btn-block login-button">Submit</button>
To
<button type="submit" name="submit" class="btn btn-success btn-lg btn-block login-button">Submit</button>
Actually you needed to add a name attribute to the button element, so that you can identify the element in the following php line
if(isset($_POST['submit'])){
The line above checks for a "POST"ed element identified by the name 'submit'.
I've uploaded different types of files and I save them in a folder and save into DB the path, all files load them well (.doc, xls ...) except (docx, xlsx ...) . The Docx Files It copies it to the directory but it is not possible to get its name, type size etc.
This is my code:
<?php
require_once 'connect.php';
if($_POST) {
$nombre = $_FILES['archivo']['name'];
$tipo = $_FILES['archivo']['type'];
$tamanio = $_FILES['archivo']['size'];
$ruta = $_FILES['archivo']['tmp_name'];
$destino = "../archivos/" . $nombre;
copy($ruta, $destino);
$sql = "INSERT INTO documentos (tipo,tamano,destino,fecha) VALUES ('$tipo', '$tamanio', '$nombre',NOW())";
$query = $connect->query($sql);
$connect->close();
}
My form:
<form class="form-horizontal" action="../../phpcrud/create_documentos.php" method="POST" id="create_documentos_form" enctype="multipart/form-data">
<div class="modal-body">
<div class="message_create_documentos"></div>
<div class="form-group">
<label for="apemat" class="col-sm-2 control-label">Archivo</label>
<div class="col-sm-10">
<input type="file" class="form-control" id="archivo" name="archivo" placeholder="Archivo">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" class="btn btn-primary">Guardar</button>
</div>
</form>
Table name = image_2017.My image is not updating by this UPDATE query in a particular $_GET['id'] instead image is inserting as a new image. I don't know what is wrong in this code.I am new to php. Kindly help me someone.
<?php
include_once "config.php";
session_start();
if(!isset($_SESSION)){
header("index.php");
}
$id = $_GET['id'];
//echo $id;
if(!empty($_FILES)){
$t = time();
$filename = $category."_".$t."_".$_FILES['image']['name'];
$upload = "uploads/";
$fileupload = move_uploaded_file($_FILES['image']['tmp_name'],$upload.$filename);
if($fileupload){
$msg1 = "File uploaded Successfully";
}else{
$msg2 = "File uploaded Failed";
}
}
if(!empty($_POST)){
$category = $_POST['category'];
$image = $_FILES['image'];
$query = "UPDATE image_2017 SET category ='$category', image ='$filename' WHERE id ='$id' ";
$result = $db->query($query);
if($result){
$msg3 = "Image Updated Successfully";
}else{
$msg4 = "Image not Updated";
}
}else{
//echo "Please enter all the details";
}
?>
<html>
<body>
<form class="form news" style="padding:10px;" method="post" action="image-2017.php" enctype="multipart/form-data">
<div class="row">
<div class="form-group">
<label class="control-label col-md-2">category</label>
<div class="col-md-4">
<select class="form-control" name="category">
<option>--> Select <--</option>
<option>Birthday</option>
<option>Christmas</option>
<option>Fruits</option>
<option>Ganesh Chathurthi</option>
<option>Green Day</option>
<option>Guitar Play</option>
<option>Independence Day</option>
<option>Krishna Jayanthi</option>
<option>Onam</option>
<option>Splash Pool</option>
<option>Teddy Bear</option>
<option>Veg Market</option>
<option>Vijayadhasami</option>
</select>
</div>
</div>
</div>
<br>
<div class="row">
<div class="form-group">
<label class="control-label col-md-2">Upload Image</label>
<div class="col-md-10">
<input type="file" name="image">
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2"></label>
<div class="col-md-10">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="button" class="btn btn-primary">Back</button>
</div>
</div>
</form>
</body>
</html>
I updated html to add a post for id
<?php
include_once "config.php";
session_start();
if(!isset($_SESSION)){
header("index.php");
}
$id = $_POST['id'];
//echo $id;
if(!empty($_FILES)){
$t = time();
$filename = $category."_".$t."_".$_FILES['image']['name'];
$upload = "uploads/";
$fileupload = move_uploaded_file($_FILES['image']['tmp_name'],$upload.$filename);
if($fileupload){
$msg1 = "File uploaded Successfully";
}else{
$msg2 = "File uploaded Failed";
}
}
if(!empty($_POST)){
$category = $_POST['category'];
$image = $_FILES['image'];
$query = "UPDATE image_2017 SET category ='$category', image ='$filename' WHERE id ='$id' ";
$result = $db->query($query);
if($result){
$msg3 = "Image Updated Successfully";
}else{
$msg4 = "Image not Updated";
}
}else{
//echo "Please enter all the details";
}
?>
<html>
<body>
<form class="form news" style="padding:10px;" method="post" action="image-2017.php" enctype="multipart/form-data">
<div class="row">
<div class="form-group">
<label class="control-label col-md-2">category</label>
<div class="col-md-4">
<select class="form-control" name="category">
<option>--> Select <--</option>
<option>Birthday</option>
<option>Christmas</option>
<option>Fruits</option>
<option>Ganesh Chathurthi</option>
<option>Green Day</option>
<option>Guitar Play</option>
<option>Independence Day</option>
<option>Krishna Jayanthi</option>
<option>Onam</option>
<option>Splash Pool</option>
<option>Teddy Bear</option>
<option>Veg Market</option>
<option>Vijayadhasami</option>
</select>
</div>
</div>
</div>
<br>
<div class="row">
<div class="form-group">
<label class="control-label col-md-2">Upload Image</label>
<div class="col-md-10">
<input type="file" name="image">
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2"></label>
<div class="col-md-10">
<input type="hidden" name="id" value="<?php echo $_GET['id'];?>">
<button type="submit" class="btn btn-primary">Submit</button>
<button type="button" class="btn btn-primary">Back</button>
</div>
</div>
</form>
</body>
</html>
Make sure you reach the page as: mypage.php?id=12