How to destroy the current image in image upload - php

I want to do is when a user decided to change his profile picture the link in the database will be update and move the image to upload folder and destroy the current link and image on the upload folder on that specific user.
My problem in my code is when a user change his profile picture it will add another picture on the upload folder. I want to do is to delete the current image first on that specific user before the new image he selected is move on the upload folder.
php code
<?php
include_once('../dbc/database.php');
$db = new Connection();
$db = $db->dbConnect();
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$email = isset($_POST['email']) ? $_POST['email'] : "";
$image = addslashes(file_get_contents($_FILES['imageInput']['tmp_name']));
$image_name = addslashes($_FILES['imageInput']['name']);
$image_size = getimagesize($_FILES['imageInput']['tmp_name']);
move_uploaded_file($_FILES["imageInput"]["tmp_name"], "../upload/" . $_FILES["imageInput"]["name"]);
$location = "elogFiles/upload/" . $_FILES["imageInput"]["name"];
$qOldpic = "SELECT user_image FROM tbl_user WHERE user_email = : email";
$queryOldpic = $db->prepare($qOldpic);
$queryOldpic->bindParam(':email', $email);
$queryOldpic->execute();
$num_rows = $queryOldpic->rowCount();
if ($num_rows == 1) {
unlink($queryOldpic);
$q = "UPDATE tbl_user SET user_image = '$location' WHERE user_email= :email ";
$query = $db->prepare($q);
$query->bindParam(':email', $email);
$results = $query->execute();
echo "1";
}
?>

http://php.net/manual/en/function.unlink.php
above url will help you understand proper approach to delete the previous image file.
If you want to make the error message invisible when that file is not exist on given location, use '#' so you could simply ignore the error display as the following:
<?php
unlink($filename);
?>

Before you do your update, run a select and get the user_image by email, store it into a variable, like $oldPicture.
After that, you should remove the picture like this:
if ((!!$oldPicture) && (file_exists($oldPicture))) {
unlink($oldPicture);
}
You only delete an image if you have a value for its path and the file exists. Make sure the path of $oldPicture is correct. Finally, after the if above you can run your update command. I will not delve into security problems, as it is out of scope in this question, but make sure you prevent SQL injection.

Related

Upload Image won't upload unless I add a specific line of code that I don't want

My code wont work unless I add this specific line of code, the one that has the comment next to it (Line 3). Does anyone have any open suggestions on what I should do? Because I don't wont $_SESSION['username'] = "nameofuser";
:
Here is the link to the code: sweettune.info/code.txt
Using "$_SESSION['username'] = "nameofuser";" and deleting it, but if I delete it my image won't upload.
<?php
session_start();
$_SESSION['username'] = "nameofuser"; // Won't work unless this line of code is added
if(isset($_POST['submit'])){
move_uploaded_file($_FILES['file']['tmp_name'],"uploads/".$_FILES['file']['name']);
$conn = mysqli_connect("localhost","newkit","frtysk489","configurenow");
$q = mysqli_query($conn,"UPDATE users SET image = '".$_FILES['file']['name']."' WHERE username = '".$_SESSION['username']."'");
}
?>
If you don't want to use $_SESSION['username'] = 'nameofuser'; then you will need to choose another unique column from your table (such as the record id) to identify the row to be updated.
The reason the database is not updated is because your query specifically asks WHERE username = '".$_SESSION['username']."'"
"UPDATE users SET image = '".$_FILES['file']['name']."' WHERE username = '".$_SESSION['username']."'"
Without a unique identifier, the table row cannot be updated, your update will fail.

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)

Profile photo upload in php and database

I have problem that the photo uploaded to the site but the name of it don't be saved on database .
The code upload the photo to the site but the name of the file didn't be uploaded to the database
help me, I need to know what the problem in the code?
please someone answer!
the code:
<?php session_start();
$con = mysqli_connect("my host","my account","my passwod","my table name");
$_SESSION['id'] = "$con_id";
?>
<?php
if(isset($_POST['submit'])){
move_uploaded_file($_FILES['file']['tmp_name'],"../userstorage/p_photos/".$_FILES['file']['name']);
$con = mysqli_connect("my host","my account","my password","my table name");
$q = mysqli_query($con,"UPDATE users SET image = '".$_FILES['file']['name']."' WHERE id = '".$_SESSION['id']."'");
}
?>
Your error is here
$q = mysqli_query($con,"UPDATE users SET image = '".$_FILES['file']['tmp_name']."' WHERE id = '$id'");
$_FILES['file']['tmp_name'] is the image data, while $_FILES['file']['name'] is the name of the file. So in the end of the day you need to change this piece of code
for reference check this article on W3Schools on how to upload and display images from a database.

Unable to copy() image from one folder to another

I am trying to copy an image from one folder to another. I feel that my paths are wrong, but I have tried so many path combinations that I am now unsure whether it is the problem.
I am trying to copy an image (if it exists) from the user_photos folder, into the profile_pics folder. Here are where they are located, as well as the script, known as, change_dp.php, which once called, will execute the copy().
www > user_data > user_photos > photos_are_here
www > user_data > profile_pics > photos_are_here
www > inc > change_dp.php
Here is change_dp.php:
$all_pics = mysqli_query ($connect, "SELECT * FROM user_photos WHERE username = '$username'");
$row_query = mysqli_fetch_assoc($all_pics);
$get_photo_owner = $row_query['username'];
$get_photo_id = $_GET['id'];
$get_pic_with_id = mysqli_query ($connect, "SELECT * FROM user_photos WHERE id = '$get_photo_id'");
$row_query2 = mysqli_fetch_assoc($get_pic_with_id);
$img_url = $row_query2['img_url'];
$file = $img_url;
$arrPathInfo = pathinfo($file);
$shortened_url = $arrPathInfo['basename'];
if (file_exists($file)) {
copy("../../" . $file, "../../profile_pics/" . $shortened_url);
}
$pro_pic_change = mysqli_query($connect, "UPDATE users SET profile_pic='$shortened_url' WHERE username = '$username'") or die ($connect);
header("Location: /photos/$get_photo_owner");
Just to illustrate the issue more:
User uploaded photos (which are stored in user_photos) are stored in there full path in my database, for example, if Alice uploads a file called alice.jpg, it will be stored as user_data/user_photos/alice.jpg. This is why I have varible $shortened_url which will only get the base name of the file i.e. get the alice.jpg from user_data/user_photos/alice.jpg. I need the $shortened_url because column profile_pics in the database holds just the base name of the image, not the full path.
With the if statement, I am trying to get the basename of the image, see if an image with the same name in my user_photos file exists, and if it does, copy it into the profile_pics folder and set the basename to profile_pics column via an UPDATE statement. The UPDATE statement works fine, the image name does change in the database, but the image just doesn't copy over, which corrupts the image since it cant find it in the profile_pics folder.
What I have tried:
copy($file, "../profile_pics/" . $shortened_url);
copy("../../" . $file, "../../profile_pics/" . $shortened_url);
copy($file, "user_data/profile_pics/" . $shortened_url);
None which work.
Edit:
Here's what I want the code to do:
Lets assign values to $file for an example:
$file = user_data/user_photos/alice.jpg
See if an image with the name of $file exists in the user_photos folder.
If there is a file with the name of alice.jpg in the folder, then copy that image into the profile_pics folder.
That's it.
You could use __DIR__ magic constant and then based on that you can go to upper levels in the directory hierarchy, by using realpath() function or even dirname() function. This way it will be less confusing and less error prone.
E.g.:
$upOneLevel = realpath(__DIR__."../");
$upTwoLevels = realpath(__DIR__."../../");
So to access your file you shoud use:
$fileRealPath = $upOneLevel."/".$file;
$fileRealDestination = $upOneLevel."user_data/profile_pics/".$shortened_url;
I also recommend to update the data in the DB only if the file exists and the copy command executes successfully:
if (file_exists($fileRealPath)) {
if(copy($fileRealPath, $fileRealDestination)) {
//TODO db logic here
} else {
//TODO error handling here
}
} else {
//TODO error handling here
}

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

Categories