Unable to copy() image from one folder to another - php

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
}

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)

Retrieve video file from mysql database using php and save it to local folder

I have been trying to upload video files to mysql database and retrieve those files and save it in a local folder. My table simply consists of id, a title of video, and size of video.
I thought both of retrieving from and uploading to database would be easy. I don't see any error except that undefined variable thing for $_GET["download"] once I run the code but the folder where all the videos should be saved is always empty.
PHP code saving a video file that I retrieve from database to a local folder:
if($_GET["download"] == 1)
{
$query = "select id, videoName, videoFile from video where ID = 5";
$result = $dab->sql_query($query);
$row = mysqli_fetch_assoc($result);
$_FILES["size"] = $row["videoFile"];
$_FILES["tmp_name"] = $row["videoName"];
move_uploaded_file($_FILES["tmp_name"], "download/" . "sample.mp4");
}
HTML a tag:
<html lang = "en">
<body>
<a id = "download" href = "main2.php?download=1">download</a>
</body>
</html>
move_uploaded_file($_FILES["tmp_name"], "download/" . "sample.mp4");
make sure about this path and Check if the download/ dir is writeable.

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

Update image path

I'm fairly new to PHP programming and I've looked around but I'm still confused. I'm trying to update the image path in my users table and I'm not quite sure how to do it. This is the code I have for putting the image into the database and it works to insert it in, but I'm not sure how to UPDATE the image picture path in my database to use the newly inserted image as opposed to the one the user selected when they created an account.
// Make sure we didn't have an error uploading the image
($_FILES[$image_fieldname]['error'] == 0)
or handle_error("the server couldn't upload the image you selected.",
$php_errors[$_FILES[$image_fieldname]['error']]);
// Is this file the result of a valid upload?
#is_uploaded_file($_FILES[$image_fieldname]['tmp_name'])
or handle_error("you were trying to do something naughty. Shame on you!",
"upload request: file named " .
"'{$_FILES[$image_fieldname]['tmp_name']}'");
// Is this actually an image?
#getimagesize($_FILES[$image_fieldname]['tmp_name'])
or handle_error("you selected a file for your picture " .
"that isn't an image.",
"{$_FILES[$image_fieldname]['tmp_name']} " .
"isn't a valid image file.");
// Name the file uniquely
$now = time();
while (file_exists($upload_filename = $upload_dir . $now .
'-' .
$_FILES[$image_fieldname]['name'])) {
$now++;
}
// Finally, move the file to its permanent location
#move_uploaded_file($_FILES[$image_fieldname]['tmp_name'], $upload_filename)
or handle_error("we had a problem saving your image to " .
"its permanent location.",
"permissions or related error moving " .
"file to {$upload_filename}");
$insert_sql = "UPDATE users set user_pic_path WHERE user_id = $user_id =
replace(user_pic_path, '$upload_filename', '$upload_filename' );
//insert the user into the database
mysql_query($insert_sql);
</code>
EDIT:
I was missing a " which I fixed and now there is no SQL error, it puts the picture into the database but does not replace the image path in the database. I've been messing with the $insert_sql but it still doesn't update the database with the new image path, what can I do? Here's my new update code:
<code>
$insert_sql = "UPDATE users WHERE user_id = $user_id set user_pic_path =
replace(user_pic_path, '$upload_filename', '$upload_filename')";
</code>
In the final lines, insert a test of your SQL:
$insert_sql = "UPDATE users WHERE user_id = $user_id set user_pic_path = replace(user_pic_path, '$upload_filename', '$upload_filename')";
// check the query
echo $insert_sql."<br />";
//insert the user into the database
mysql_query($insert_sql);
Then you can watch the query your about to run, test it in PHPMyAdmin, work out what it should be. It's worth doing for other key variables as well. Even better, you should write a "debug" function, that logs what's going on in a file on the server so that when an error occurs, you can track details of it, including values of key variables in every file.

PHP upload file

i have been stressing for an hour at this stupid script i am trying to make it uploa an MP3
file to a folder it creates.
It is putting the information into mysql and making the folder bu when i ftp the folder is empty with no music file in there
here is the script thanks so so so much!
BTW $name is the POSTED name and full name is the posted name + ".mp3"
// BEGIN ENTERING INFORMATION TO MYSQL TABLE
$sql = mysql_query("INSERT INTO mattyc (name, date, length, size, link)
VALUES('$name','$date','$length','$size','$link')"
) or die (mysql_error());
mkdir("../music/albums/donjuma/$name", 0777);
$song = ("../music/albums/donjuma/$name/$fullname");
if (file_exists($song)) {
unlink($song);
}
$newname = "$fullname";
$newfile = rename(($_FILES['song']['tmp_name']),($newname));
$place_file = move_uploaded_file( $newfile, "../music/albums/donjuma/$name/"."$newname");
$success_msg = "<font color=\"#009900\">Your SONG has been updated, it may take a few minutes for the changes to show... please be patient.</font>";
echo $success_msg;
}
}
}
$newfile =
rename(($_FILES['song']['tmp_name']),($newname));
$place_file = move_uploaded_file(
$newfile,
"../music/albums/donjuma/$name/"."$newname");
rename() returns a bool, not a filename. So your move_uploaded_file() call is going to fail. Any file renaming should be part of your move_uploaded_file() call, don't try and do anything with your temporary file apart from move it.

Categories