Rename image before upload and insert name in database with PHP - php

I want image rename before upload and after renamed image name should be inserted into database with PHP. I am using following code to upload image and insert some other data into database. Please help me out to rename image because I'm beginner with PHP.
<?php
if(isset($_POST['submit'])) {
$post_image = $_FILES['post_image']['name'];
$post_image_tmp = $_FILES['post_image']['tmp_name'];
$post_content = $_POST['post_content'];
if ($post_image=='' OR $post_content=='') {
echo "<script>alert('Fiil In All Fields')</script>";
} else {
move_uploaded_file($post_image_tmp, "../post_imgs/$post_image");
$insert_post ="INSERT INTO posts(post_image,post_content)values('$post_image','$post_content')";
$run_post= mysql_query($insert_post);
echo "<script>alert('Post has been Published Now...')</script>";
echo "<script>window.open('index.php?insert_post=insert','_self')</script>";
}
}
?>

$tmp_file = $_FILES['uploadedfile']['tmp_name'];
$ext = pathinfo($_FILES["uploadedfile"]["name"], PATHINFO_EXTENSION);
$rand = md5(uniqid().rand());
$post_image = $rand.".".$ext;
move_uploaded_file($tmp_file,"../post_imgs/".$post_image);

Try this..
<?php
if(isset($_POST['submit'])) {
$post_image = $_FILES['post_image']['name'];
$post_image_tmp = $_FILES['post_image']['tmp_name'];
$post_content = $_POST['post_content'];
if ($post_image=='' OR $post_content=='') {
echo "<script>alert('Fiil In All Fields')</script>";
} else {
$newname="image".$post_image;
$path='../post_imgs/';
$pathAndName = $path.$newname;
$moveResult = move_uploaded_file($post_image_tmp, $pathAndName);//move to folder
$insert_post ="INSERT INTO posts(post_image,post_content)values('$newname','$post_content')";
$run_post= mysql_query($insert_post);
echo "<script>alert('Post has been Published Now...')</script>";
echo "<script>window.open('index.php?insert_post=insert','_self')</script>";
}
}
?>

Related

How to hard code a file's name in the database while saving an image to the server in php?

I'm working on getting images from the database, which I've been saving as an url from the server it's been getting saved on.
There's this upload image section on the form, which is saving the images on a server and its url is getting saved in the database.
Here's the code:
$fileName = "";
$target_dir="/home/web/newsletter/uploads/";
$target_file_cv = $target_dir . basename($_FILES['fileToUpload']['name']);
if(!empty($_FILES['fileToUpload']['name']))
{
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file_cv)) {
$fileName= $target_file_cv;
} else {
echo $twig->render("App/error.twig");
}
}
$conn = DB::databaseConnection();
$conn->beginTransaction();
$sqlInsert = "INSERT INTO dbo.form (photo) VALUES (:fileToUpload)";
$stmt = $conn->prepare($sqlInsert);
$stmt->bindParam(':fileToUpload', $fileName);
if ($stmt->execute()) {
$conn->commit();
return true;
} else {
return false;
}
?>
Here, I want to edit the file Name before it goes to the database. Like now it is saving as "/home/web/newsletter/uploads/pic.jpg" but I want it to be saved as "newsletter/uploads/pic.jpg".
I referred to a few questions here and got everything else working but just got stuck at hard coding the file's name here. Any help would be appreciated. TIA
$fileName = implode(array_slice(explode("/",$target_file_cv),3),"/");
Okay I got it:
Changed the code to:
$fileName = "";
$target_dir="/home/web/newsletter/uploads/";
$target_file_cv = $target_dir . basename($_FILES['fileToUpload']['name']);
if(!empty($_FILES['fileToUpload']['name']))
{
if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $target_file_cv)) {
$fileName= "newsletter/uploads/" . $_FILES['fileToUpload']['name'];
} else {
echo $twig->render("App/error.twig");
}
}
$conn = DB::databaseConnection();
$conn->beginTransaction();
$sqlInsert = "INSERT INTO dbo.form (photo) VALUES (:fileToUpload)";
$stmt = $conn->prepare($sqlInsert);
$stmt->bindParam(':fileToUpload', $fileName);
if ($stmt->execute()) {
$conn->commit();
return true;
} else {
return false;
}
?>

Retrieving image from the database and updating the image or uploading another file

I have an upload function where the image is uploaded into the database then I want to echo the image but the problem is if I update the image, it won't show but if it is the first upload the image is showing here's how I upload the image
include('phpqrcode/qrlib.php');
//start of register function
if (isset($_POST['student-registration'])) {
// get image - student picture
$check = getimagesize($_FILES["image"]["tmp_name"]);
if($check !== false){
$image = $_FILES['image']['tmp_name'];
$imgContent = addslashes(file_get_contents($image));
}
else{
array_push($errors, "Please select an image to upload");
}
here's how I echo the image please note that I echo the image in a different file i'm including the file where the upload function is located
<?php echo '<img src="data:image/jpeg;base64,'.base64_encode($image).'" style ="width:200px; height:200px;"/>'; ?>
<?php
i only have one data field for the image and it is called image from userinfo table
here's how I fetch the arrays from my database table
$UserID = $_POST['UserID'];
// mysql search query
$query = "SELECT * FROM userinfo WHERE UserID = '$UserID' LIMIT 1";
$result = mysqli_query($db, $query);
// if code exist
// show data in inputs
if(mysqli_num_rows( $result) > 0)
{
while ($row = mysqli_fetch_array($result))
{
$UserType= $row['UserType'];
if ($UserType != "Student")
{
echo '<span style="color:#FF0000;text-align:center;">Oppss... Student ID not FOUND!</span>';
$UserID = "";
}
else //get data from database to retrieve and display in students registration form
{
$StudName = $row['LName'].","." " .$row['FName']." ".$row['MName'];
$UserType= $row['UserType'];
$UserID = $row['UserID'];
$FName = $row['FName'];
$MName = $row['MName'];
$LName = $row['LName'];
$EName = $row['EName'];
$Gender = $row['Gender'];
$Address = $row['Address'];
$ContactNo = $row['ContactNo'];
$EmailAddress = $row['EmailAddress'];
$College = '<option value="' . $row['College'] . '">' ;
$Department = $row['Department'];
$Course = $row['Course'];
$YearLevel = $row['YearLevel'];
$ParentName = $row['ParentName'];
$ParentEmail = $row['ParentEmail'];
$ParentContact = $row['ParentContact'];
$image = $row['image']; // image from the database
}
}
}
thanks in advance
When querying your DB you are putting in $image the image's content.
When updating image, you are putting in $image the image's name.
This is why your image is not displaying after update.
You need to:
OR put image content in $image while updating
- $image = $_FILES['image']['tmp_name'];
- $imgContent = addslashes(file_get_contents($image));
+ $img_name = $_FILES['image']['tmp_name'];
+ $image = file_get_contents($img_name);
+ $imgContent = addslashes($image);
OR execute your query part after update.

Extecuting Query With The Condition in PHP

I have a page in which user can update their posts.
I need to update the database with different query(for different Conditions).
But every time I run update using this code, image filename changes automatically (even if I have a condition). Am I doing something wrong?
if(empty($up_image)){
$up_image = $image;
$update_query = "UPDATE posts SET title = '$up_title', image = '$up_image', categories = '$up_categories', tags = '$up_tags', post_data = '$up_post_data', status = '$up_status' WHERE id = $edit_id";
if(mysqli_query($con, $update_query)){
$msg = "Post has been Updated";
$path1 = "img/$up_image";
header("refresh:1;edit-post.php?edit=$edit_id");
if(move_uploaded_file($up_tmp_name, $path1)){
copy($path1, "../$path1");
}
}
else{
$error = "Unable to Update Post";
}
}
if(!empty($up_image)){
$up_image = preg_replace('/\s+/','',$up_image);
$image_size = $_FILES['image']['size'];
$allowed_img_ext = array("jpg", "jpeg", "png", "bmp");
$ext = pathinfo($up_image, PATHINFO_EXTENSION);
$trimed_img_name = pathinfo($up_image, PATHINFO_FILENAME);
if(in_array($ext, $allowed_img_ext))//check valid file extension
{
if($image_size < 2097152) {
$ren_image = substr($trimed_img_name,0,3)."".substr($title,0,11)."_".date("mj")."_".date("Y")."_".date("His").".".$ext;
$path = "img/".$ren_image;
$update_query = "UPDATE posts SET title = '$up_title', image = '$ren_image', categories = '$up_categories', tags = '$up_tags', post_data = '$up_post_data', status = '$up_status' WHERE id = $edit_id";
}
else{
$img_error = "Please Upload the Image File Size Less than 2 MB";
}
}
else{
$img_error = "Invalid Image File";
}
if(mysqli_query($con, $update_query)){
$msg = "Post has been Updated";
header("refresh:1;edit-post.php?edit=$edit_id");
if(move_uploaded_file($up_tmp_name, $path)){
copy($path, "../$path");
}
}
else{
$error = "Unable to Update Post";
}
} //End
So I removed $up_image = $image; and image = $up_image section from first query now it is working. Thanks for your comment

How to upload and insert multiple images in PHP and mysql database

I am a beginner in PHP. I encoded some images in a base64String. All images are successfully decoding in the specified folder. My problem is am only able to record one image/path in the database. Somebody help me to come up with the PHP to insert all images paths in one row in the database.
here is the php code
<?PHP
if(isset($_POST['image']))
{
$image = $_POST['image'];
$identity = $_POST['id'];
$username = $_POST['username'];
//create unique image file name based on micro time and date
$now = DateTime::createFromFormat('U.u', microtime(true));
$id = rand(1000000, 10000000000);
$id2=rand(1000000, 10000000000);
$upload_folder = "upload";
$id="$id$id2";
$path = "$upload_folder/$id.jpeg";
if(file_put_contents($path, base64_decode($image)) != false){
echo "uploaded_success";
$sql = "UPDATE apartment SET Image_path = '$path' WHERE apart_username
='$username' AND id = '$identity'";
mysqli_query($conn, $sql);
}
else{
echo "uploaded_failed";
}
exit;
}
else{
echo "images_not_in";
exit;
}
?>
You need some sort of loop...all I did in the example below was instead of making a single variable called image I made a array called $imagesArr. And I added a foreach loop on the imagesArr so it will run the code you wrote for each image you input into that array. I also killed the exit at the end as that would stop the loop. That should work
<?PHP
if(isset($_POST['image']))
{
//$image = $_POST['image']; - I commented this out
$imagesArr = array('image1.jpeg','image2.jpeg','image3.jpeg'); //etc. put all of your images here into this array
$identity = $_POST['id'];
$username = $_POST['username'];
foreach ($imagesArr as $key => $image) {
//create unique image file name based on micro time and date
$now = DateTime::createFromFormat('U.u', microtime(true));
$id = rand(1000000, 10000000000);
$id2=rand(1000000, 10000000000);
$upload_folder = "upload";
$id="$id$id2";
$path = "$upload_folder/$id.jpeg";
if(file_put_contents($path, base64_decode($image)) != false){
echo "uploaded_success";
$sql = "UPDATE apartment SET Image_path = '$path' WHERE apart_username
='$username' AND id = '$identity'";
mysqli_query($conn, $sql);
}
else{
echo "uploaded_failed";
}
}
else{
echo "images_not_in";
}
}

UPDATE SQL query won't update database in my php script

I am trying to have an Edit page that fetch the data selected by user and display them in a form. I manage to display the data from database and allow user to edit the data in the form. But my UPDATE query won't work in php. I tried echo the query and run it manual in xampp, it turns out to be ok and it was able to update manual in xampp but not in php. Can anyone help me with the codes? many thanks
this is my php coding
<?php
session_start();
include_once 'dbconnect.php';
if(isset($_POST['btn-update']))
{
$ProdCode = mysql_real_escape_string($_POST['productCode']);
$ProdType = mysql_real_escape_string($_POST['productType']);
$ProdDes = mysql_real_escape_string($_POST['product_description']);
$ProdCol = mysql_real_escape_string($_POST['productColour']);
$ProdPrice = floatval($_POST['productPrice']);
$XSsize = mysql_real_escape_string($_POST['XSquantity']);
$Ssize = mysql_real_escape_string($_POST['Squantity']);
$Msize = mysql_real_escape_string($_POST['Mquantity']);
$Lsize = mysql_real_escape_string($_POST['Lquantity']);
$XLsize = mysql_real_escape_string($_POST['XLquantity']);
$XXLsize = mysql_real_escape_string($_POST['XXLquantity']);
if(isset($_FILES['productImg'])){
$file_name = $_FILES['productImg']['name'];
$file_size = $_FILES['productImg']['size'];
$file_tmp = $_FILES['productImg']['tmp_name'];
$file_type = $_FILES['productImg']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['productImg']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors="Please choose JPEG/PNG file.";
$errorTrigger =true;
}
if($file_size > 2097152) {
$errors='File size must be excately 2 MB';
$errorTrigger =true;
}
if(empty($errors)==true) {
move_uploaded_file($file_tmp,"images/".$file_name);
} }
$query = "UPDATE product SET product_code='$ProdCode', product_type='$ProdType' ,description='$ProdDes' ,colour='$ProdCol',price= '$ProdPrice',size_xs='$XSsize',size_s='$Ssize',size_m='$Msize',size_l='$Lsize',size_xl='$XLsize',size_xxl='$XXLsize' WHERE product_code='%". $ProdCode ."%'";
echo $query;
if(mysql_query($query))
{
echo "<script>
alert('Product Updated');
</script>";
}
else
{
echo mysql_error();
?>
<script>alert('Error while updating');</script>
<?php
}
}
?>

Categories