ISSET function to prevent image file overwrites? - php

Im setting up a website like gumtree (uni project). I'm implementing the ability for users to be able to edit their listed items. I'm having trouble with the image part. If the user does not want to change the image when updating other rows, the ran function is overwriting the image with random numbers. I have attached a picture of the code.
I want the user to be able to update things like the product name and price without the image being overwritten by random numbers each time they press the update button.
if(isset($_FILES['uploadimg']['name'])){
$ran = rand(0,1000000);
$filename = $_FILES['uploadimg']['name'];
$filename = $ran.$filename;
$filetmp = $_FILES['uploadimg']['tmp_name'];
$filetype = $_FILES['uploadimg']['type'];
move_uploaded_file($filetmp, "../dbimages/".$filename);
$updateimg = "UPDATE elmtree SET path='$filename' WHERE itemid='$id'";
$imageupdate = $conn -> query($updateimg);
}

Related

create unique folder of each user from input and save images inside that folder using php

I'm working on project for creating Online Exam for college Entrance. I am looking for solution to upload image and create folder using user serial id as which is as per mysql database primary increment idsave the images inside the folder.
Here is my solution where images are uploaded in already created folder called uploads. How to modify this for what I required.
<?php
session_start();
include('../connect.php');
$a = $_POST['name'];
// query
$file_name = strtolower($_FILES['file']['name']);
$file_ext = substr($file_name, strrpos($file_name, '.'));
$prefix = 'your_site_name_'.md5(time()*rand(1, 9999));
$file_name_new = $prefix.$file_ext;
$path = '../uploads/'.$file_name_new;
/* check if the file uploaded successfully */
if(#move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
//do your write to the database filename and other details
$sql = "INSERT INTO student (name,file) VALUES (:a,:h)";
$q = $db->prepare($sql);
$q->execute(array(':a'=>$a,':h'=>$file_name_new));
header("location: students.php");
}
?>
First: Be careful uploading files without correctly checking it's types;
Second: As Sean mentioned, this approach may get out of control.
--
The following example changed the steps that you tried.
First insert the user to get it's ID and then create the folder under '../uploads' with it.
This way you do not need to move the file two times (move the file to ../uploads, insert the user and then move the file again to ../uploads/userID)
<?php
...
$sql = "INSERT INTO student (name,file) VALUES (:a,:h)";
$q = $db->prepare($sql);
$q->execute(array(':a'=>$a,':h'=>$file_name_new));
// Get user id
$studentId = $db->lastInsertId();
// Create path with new userId just inserted
$path = "../uploads/$studentId/";
if(!file_exists($path)) { // maybe "&& !is_dir($path)" ?
// IMPORTANT NOTE: the second argument is the permission of the folder. 0777 is the default and may cause security flaws
mkdir($path, 0777, true);
}
// Move the uploaded file to new path with the userId
#move_uploaded_file($_FILES['file']['tmp_name'], $path.$file_name_new);
I think you need to check if the user already exists before inserting (but I don't know the details of your project)

how to get uploaded file name in different upload form without clicking choose file?

I am working on a CRM, on uploading a file in one upload form. Is it possible to get that file name inside choose file in another form without clicking the choose file option?
This is the code for selecting file in one form.
if ($_FILES['product_image']['name']!='') {
$target = "file_upload_source/";
$target1 =$target . #date(U)."_".( $_FILES['product_image']['name']);
$product_image=#date(U)."_".( $_FILES['product_image']['name']);
move_uploaded_file($_FILES['product_image']['tmp_name'], $target1);
$getlead_id1 = $_GET['leadid'];
// $appa = explode("_",$getlead_id1);
$data = explode("_",$getlead_id1);
$lead_id545=$data[0];
$type464 = $data[1];
$sl= "
INSERT INTO dizypro_file_order
SET lead_id = '$lead_id545',
description = '$description',
name = '$product_image',
type = '$type464',
upld_date = now(),
maker_date = now(),
maker_id = '".$_SESSION['ADMIN_GAME_ID']."',
divn_id = '".$_SESSION['SESS_Division']."',
comp_id = '".$_SESSION['SESS_COMPANY']."',
zone_id = '".$_SESSION['SESS_zone']."',
brnh_id = '".$_SESSION['SESS_Branch']."'
";
mysql_query($sl);
If I understand the question correctly, you want set the contents of a filefield to a predefined filename when you send a form. Every major browser will not let you do that, on security grounds. An unscrupulous site could display a filefield where the user can't see it, select the name of any file on your computer, put trick the user into uploading that file.
Short summary: Not possible!

PHP: define name for file upload

I have a peace of code that stores profile images in the map "images/profiles" and stores the URL in the database. I want to define the name of the uploaded profile picture to be the $ID of the user. How can I do this?
include("../../core/init.inc.php");
$target = "../images/profiles/";
$target = $target . basename($_FILES['photo']['name']);
$pic = $_FILES['photo']['name'];
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
echo "The file ". basename($_FILES['photo']['name']). " has been uploaded";
} else {
echo "ERROR";
}
mysql_query("UPDATE users SET image_url='includes/images/profiles/$pic' WHERE username = '".mysql_real_escape_string($_SESSION['username'])."'");
Now when someone uploads his profile picture (lets call it pf1.png) it saves it as "pf1.png". I want it to be saved like "$ID.png" (.png being a random extension). I want to accomplish this both for the move_upload_file function and updating the 'image_url' database column correctly.
According to the example in the documentation you can provide the filename in the destination of move_uploaded_file(). If that fails you can simply rename() the file after saving it.
try changing
$target = $target . basename($_FILES['photo']['name']);
to:
$filename=$_FILES["file"]["tmp_name"];
$extension=end(explode(".", $filename));
$target = target . $_SESSION["ID"].".".$extension;
side note: You are not escaping $pic this makes your site vulnerable to sql-injection
I don't know how you saved the ID of the user, but to make it easy let's assume you stored the ID in a session.
Then simply change the $target.
$target = $target . $_SESSION['ID'];
Also change your query as follows:
$url = "includes/images/profiles/" . $_SESSION['ID'];
SET image_url="$url"
Note: I don't know why you got an image folder inside an includes folder, but I guess you made that choice for yourself.
you can get the last inserted id and make it as a name of your image/uploaded file
$qry = mysqli_query($dbconnection,"INSERT INTO statements here");
$last_id = mysqli_insert_id($dbconnection);
//$ext= you get the extension of the file uploaded
move_uploaded_file($tmpname,$target.$last_id.$ext);
now if you want it to be accomplished in updating also.
you can always get the ID of the data you want to fetch and make it as a basis in updating.
ex.
$id = $_GET['id'] || $id = $row['id']; //anything depends on how you want it to retrieve
then you can do the query and move_uploaded_file function
$qry = mysqli_query($dbconnection,"UPDATE tblname SET field='$anything' WHERE id = '$id'");
move_uploaded_file($tmpname,$target.$id.$ext);
of course $tmpname will be the basis on what file you have uploaded, $tmpname will be the file you want to move into your desired directory

delete an image file using php

I am building a forum with php and MySQL and I want to append current time to each image that users upload for their profile. I used time() function on each image file uploaded and it worked for the image file but I have trouble inserting the new filename into the database. I wanted to give each image a unique name to prevent override.
OK here is what I did: I stored the current time as $time and the filename in a variable, $photo and I tried to insert that variable’s value using $photo .= $time into the database so it has the filename as I did with each uploaded image. However the original filename is inserted into the database in every attempt.
Any workarounds?
$image = $_FILES['photo']['name'];
$time = time();
$image .= $time;
delete the existing photo
delete(image_dir/$row['current_photo.jpg']);
//does not work, but i want something like that
if(move_uploaded_file($_FILES['photo']['tmp_name'], 'image_dir/$image') {
$query = "INSERT INTO profile (user_id, profile_photo) VALUES($id, $image)";
mysqli_query($dbc, $query);
if(mysqli_affected_rows($dbc) == 1) {
echo "added to the database!";
}else {
echo "failed to add photo to the database";
}
}else {
echo "failed to upload photo";
}
how can i give the uploaded image unique the name since the original image name gets inserted in the database in every try i make?
i know the code looks funny :). just want to show the logic.
If you need a unique id, you can use the uniqid function
$name=uniqid();
you may need to use
$filename=uniqid();

Inserting Thumbnail into Database

I have successfully added the original image into my imgs/ folder and also onto the server. But I'm wanting to add the thumbnail into the database. I've added it into the imgs/ folder but can't seem to find away to insert it into the database.
This is the final bit of code that is used to crop the img and insert it to the folder.
I need to insert it into the database also so I can call on it for the $_SESSION User and the Users friend as I have profiles.
if (isset($_POST["upload_thumbnail"]) && strlen($large_photo_exists)>0) {
//Get the new coordinates to crop the image.
$x1 = $_POST["x1"];
$y1 = $_POST["y1"];
$x2 = $_POST["x2"];
$y2 = $_POST["y2"];
$w = $_POST["w"];
$h = $_POST["h"];
//Scale the image to the thumb_width set above
$scale = $thumb_width/$w;
$cropped = resizeThumbnailImage($thumb_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
//Reload the page again to view the thumbnail
header("location:".$_SERVER["PHP_SELF"]);
exit();
}
if(isset($_GET['a'])){
if ($_GET['a']=="delete"){
if (file_exists($large_image_location)) {
unlink($large_image_location);
}
if (file_exists($thumb_image_location)) {
unlink($thumb_image_location);
$creator_id = $_SESSION['id'];
$sql = "UPDATE users SET user_pic_small='".$img."' WHERE id=$creator_id";
$sql2 = "INSERT INTO userphotos(photo_ownerid,photo_ispublic, photo_name, photo_caption, photo_imagedata) VALUES ($creator_id,1,'Profile Picture','Profile Picture','$img')";
// insert the image
if(!mysql_query($sql)) {
echo "Fail. It broke.";
}else{
$c=mysql_query($sql2);
echo "<script> parent.alert('Image Uploaded','',1000);</script>";
}
}
}
}
Hope someone can help. Thanks.
If you want to add in your database the path of thumbnail ($thumb_image_location), just add the code that inserts the path before unlink().
If you want to store the whole image into database, you need the column to be MEDIUMBLOB type, then, before unlink() read the code of the file that contains the image, for example with:
$img = file_get_contents($thumb_image_location);
Then, INSERT data stored in $img into your database.
Ideally, you don't want to be adding the thumbnail itself to the database, just a reference (filepath) to the file. So, while I don't know what your database looks like, you need to go through the following steps:
Create a field in your table called 'thumbnail' or similar. This will hold the name which the thumbnail file is saved as.
Add the filepath to the database immediately after you crop the large image (ie between the lines '$cropped = ...' and 'header("location....' in your code)
Whenever a user or user's friend is logged in, check this field and pull any thumbnail images referenced in the table.
And that is basically it.
If you want to store only the path of the Image into Database ,than it's fine to insert only the path and serve it with HTML.
Otherwise if you want to store the raw data of the image into Database than you have to encode the Image into base64 String .
Sending/Displaying a base64 encoded Image - Here is how you encode and image at base64.
And store this huge string into a Blob Field Type into databse.
You can use this:
// Read the file
$fp = fopen($file, 'r');
$data = fread($fp, filesize($file));
$data = addslashes($data);
fclose($fp);
// Create the query and insert into our database.
// image is an BLOB field type
$query = "INSERT INTO tbl_images ";
$query .= "(image) VALUES ('$data')";
$results = mysql_query($query, $link);

Categories