I save the path to my images in my database. To delete these images, I get the path from the database.
This worked fine, until I added two folders to the path.
So far the path in my database looked like this (working!):
/var/www/myproject/public/images/550d744bd91d16.7869
Now, it looks like this (not working!): /var/www/myproject/public/images/5/profile/550d744bd91d16.7869
My Code
$folder_name = /var/www/myproject/public/images/ . $_GET['user_id'] . '/';
$profile_folder = $folder_name . 'profile/';
chmod($folder_name, 0777);
chmod($profile_folder, 0777);
// Get the images file path
$database = DatabaseFactory::getFactory()->getConnection();
$query = $database->prepare("SELECT image_path FROM images WHERE image_id = :image_id AND user_id = :user_id LIMIT 1");
$query->execute(array(':image_id' => $image_id, ':user_id' => Session::get('user_id')));
$img_path = $query->fetch();
// Convert array to string
$path = $img_path->image_path;
$file = $path . '.jpg';
if (file_exists($file)) {
// Delete the image file on the server
unlink($file);
} else {
echo 'An error occured';
return false;
}
What I tried so far
The path is definitely correct. I triple checked in the database and outputted the variable multiple times.
Therefore, I thought it must be the directory permissions, however, I added the permissions to the code and nothing changed.
I am not getting any error message and I would be beyond thankful for any kind of help with this!
Summary
file_exists(unlink($file)) returns FALSE.
unlink($file) returns TRUE.
The file permissions:
images drwxrwxrwx
5 drwxrwxrwx
profile drwxrwxrwx
image.jpg -rwxrwxrwx
Related
first of all to explain what I mean by my question, when I upload my files to the local storage I save them the following way:
$files = $request->file('files');
if ($request->hasFile('files')) {
foreach ($files as $file) {
//Get filename with the extension
$fileNameWithExt = $file->getClientOriginalName();
//Filename to store example: lead_4_document.pdf
$fileNameToStore = 'lead_' . $lead->id . '_' . $fileNameWithExt;
//Upload image
$path = $file->storeAs('/user_uploads', $fileNameToStore);
$lead->uploadFile()->create(array('filename' => $fileNameToStore, 'file_url' => $path, 'lead_id' => $lead->id));
}
}
So essentially I prepend lead_ the lead id and another _ to whatever the file is originally called during upload. The problem I face now is that I need to retrieve the associated files according to my lead ids. Here is my attempt so far:
$searchParam = 'lead_'.$lead->id.'_';
//$fileNames = File::glob('storage/user_uploads/'.$searchParam.'*');
//$files = File::get($fileNames);
$allFiles = Storage::files('user_uploads');
dd($allFiles);
Just to clarify, the 'File::glob' way seems to work, though it only outputs the names of the files not the actual files as object, which is what I need.
Okay, so I took a step back and went about this whole associated uploaded file to lead relationship a different way. Here is how I did it, just in case anyone stumbles across this and find themselves in the same boat as me.
The file upload now does a couple of things:
//check if file(s) is present in the request
if ($request->hasFile('files')) {
//checks if a directory already exists for a given lead (by id)
if (Storage::exists('/leads/'.$request->lead_id)) {
//if yes set the directory path to the existing folder
$directory = '/leads/'.$request->lead_id;
}
else {
//if not create a new directory with the lead id
Storage::makeDirectory('/leads/'.$request->lead_id);
$directory = '/leads/'.$request->lead_id;
}
foreach ($files as $file) {
//Get filename with the extension
$fileNameWithExt = $file->getClientOriginalName();
//Filename to store example: lead_4_document.pdf
$fileNameToStore = 'lead_' . $lead->id . '_' . $fileNameWithExt;
//Upload image
//'/user_uploads'
$file->storeAs($directory, $fileNameToStore);
//$lead->uploadFile()->create(array('filename' => $fileNameToStore, 'file_url' => $path, 'lead_id' => $lead->id));
}
}
So essentially, instead of trying to put all files into a single folder then checking the individual files for the 'lead_##' prepend, I instead create a folder with the id of the lead, this I then use the following way in my view function:
$directory = '/leads/'.$lead->id;
if (Storage::exists($directory)) {
$files = File::files('storage/'.$directory);
}
else {
$files = '';
}
Simply checking if the directory exists with the given lead ID, then if there are files uploaded either assign it the content, or set it blank (this is used for displaying an 'attachments' section on my page if not empty).
I have a code in codeigniter which i will store the path of my image in my database. It works fine in inserting but the path is not correct.
My folder name of my upload images are stored in upimages.
The upimages is located in outside of application folder in codeigniter where i created assets/upimages. Here is my path code in inserting to database:
$data = $this->upload->data();
$image_path = $data['full_path'];
//var_dump($image_path);
$userid = ($this->session->userdata['logged_in']['user_id']);
$imagedb = $this->prof_model->user_img($image_path,$userid);
if(file_exists($image_path)) {
$status = "success";
$msg = "File successfully uploaded";
}
my image_path is the full path of my image but it outputs none if i call it again and here is the output of the full_path in my database:
C:/xampp/htdocs/Uploadtest/assets/upimages/test.jpg
when i change the path in my db and change it to :
http://localhost/Uploadtest/assets/upimages/test.jpg
it works fine.
my question is. how can i adjust my full_path to come up with the 2nd path. Remember that the location of my upimages is outside of the application folder which i created an asset/upimages
Try to make your file path as like as following:
$image_url = base_url().'assets/upimages/'.$data['upload_data']['file_name'];
$imagedb = $this->prof_model->user_img($image_url,$userid);
I am trying to develop a user page for a forum and I'm kinda struggling with the image upload.
The problem is that I would like to limit the user to only be able to upload one single image, but be able to change it anytime. so basically, I would like to either overwrite the existing file either delete the old picture and add a new one instead.
At this point I have a piece of code that adds a timestamp at the end of the file (which I don't really need actually).
CODE:
if(isset($_POST['upload']))
{
$extension=strstr($_FILES['uploadedfile']['name'], ".");
$filename = "_/userfiles/userpics/".basename($_FILES['uploadedfile']['name'],
$extension);
$target = "_/userfiles/userpics/".basename($_FILES['uploadedfile']['name']);
$valid = true;
if(file_exists($target))
{
$filename = $filename . time();
$target = $filename . $extension;
}
if($valid)
{
// move the file into the folder of our choise
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target);
$img_sql = "INSERT INTO sp_userimage (imageid, path, id) value ('', '".$target."', '".$_SESSION['userid']."')";
$img_result = mysql_query($img_sql);
echo "upload sucessfull";
}
Make use of unlink() in PHP Manual.
if(file_exists($target))
{
unlink($target); // deletes file
//$filename = $filename . time();
//$target = $filename . $extension;
}
I think this might be a bit better suited for you. You might have to edit it a tad.
if($valid)
{
// Check if user has a file.
$img_check = mysql_query("SELECT * FROM sp_userimage WHERE id = " . (int) $_SESION['user_id']);
if( mysql_num_rows($img_check) > 0 ){
$row = mysql_fetch_object($img_check);
// Delete the file.
unlink($row->path);
}
// move the file into the folder of our choise
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target);
$img_sql = "INSERT INTO sp_userimage (imageid, path, id) value ('', '".$target."', '".$_SESSION['userid']."')";
$img_result = mysql_query($img_sql);
echo "upload sucessfull";
}
It might be easier to normalize the image type (e.g. only jpegs) and then name the file as the userid. For example:
$target = 'userpics' . DIRECTORY_SEPARATOR . $_SESSION['userid'];
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target);
This will simply overwrite the old picture with the new one. Given that this type of filename is deterministic, you also don't need to store the filename in the database.
Use unlink() function
read more here PHP unlink
okay ,if u want to delete the file for that particular user only.
then store the filename vs user in some MapTable in db.
mysql_query("CREATE TABLE t_usr_file_map(
usr_id INT NOT NULL ,
file_name VARCHAR(100),
)")
or die(mysql_error());
and at the time of reupload , fetch the filename from the table for that user , unlink it and reupload the fresh one again.
OR,
or u can use PHP file_rename function at the time of upload. rename filename to the userid
rename ( string $oldname , string $newname [, resource $context ] )
and u can always do unlink based on user-id
Its very simple by unlink()
as:
unlink(dirname(__FILE__) . "/../../public_files/" . $filename);
if (file_exists($path))
{
$filename= rand(1,99).$filename;
unlink($oldfile);
}
move_uploaded_file($_FILES['file']['tmp_name'],$filename);
I have a directory called 'files' that contains folders that represent upload space for a user, e.g. files/14 where '14' is the UserID of a user.
I am trying to create a simple script that when files are uploaded, the script:
Checks if the User's folder already exists
If user folder doesn't exist create one with the UserID, else ignore and continue
Upload files to the newly created directory (e.g. 14) or upload in previously created user directory.
This is the code:
<?php
include("dbConfig.php");
$Username = $_SESSION["username"];
global $userid;
$Password = $_SESSION["password"];
$Password = md5($Password);
$sql = "SELECT UserID FROM users WHERE Username = '".$Username."'";
$result = mysql_query($sql) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
$userid = $row['UserID'];
}
$dirname = (string)$userid;
$filename = ("$dirname" . "/");
if (!file_exists("../files/" .$filename)) {
mkdir("files/$dirname", 0775);
} else {
if (isset($_FILES['files'])) {
echo "<div id='files_table'><table class='center'.><tr><td>";
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name) {
$dest = ($filename . "{$_FILES['files']['name'][$key]}");
move_uploaded_file($tmp_name, $dest );
echo $_FILES['files']['name'][$key], " uploaded.", "<br>";
}
}
}
?>
The files are being uploaded into the root directory (../files), although the User Directory is being created.
Also, the warning is not being ignored, giving me this error:
**Warning: mkdir(): File exists in C:\xampp\htdocs\Task2PHP\final\upload.php on line 80**
Can anyone help me and tell me how to fix this?
How about using the same structure for both calls?
For example:
if (!file_exists("../files/" .$filename)) {
mkdir("../files/" .$filename, 0775);
You seem to be checking that one file/folder exists on one hand and create another one somewhere else since ../files != files/
Also navnav is right you should stop using relative paths. Garanteed problems down the road. Especially if you use some framework and url rewrinting.
I am trying to upload a picture. I have Form_Zend and I use:
$image = new Zend_Form_Element_File('image');
$image->setLabel('Upload an avatar:')
->setMaxFileSize(8388608)
// ->setDestination('./usersImages')
->setDescription('Click Browse and choose an image');
$image->addValidator('Count', false, 1);
$image->addValidator('Size', false, 8388608);
$image->addValidator('Extension', false, 'jpg,jpeg,png,gif');
$this->addElement($image, 'image');
My controller action code:
if ($form->image->isUploaded()) {
$values = $form->getValues();
$source = $form->image->getFileName();
$extention = substr($source, strrpos($source, '.', -1));
$date = date('mdYhisa', time());
$new_image_name = 'avatar_' . $date . '_' . $idUser . $extention;
$destination = "C:\\xampp\\tmp\\Srututututut.png";
$image_saved = move_uploaded_file($source, $destination);
if ($image_saved) {
$data = array(
'img' => $new_image_name,
);
$userDT->update($data, 'id=' . $idUser);
}
}
}
But this move_uploaded_file is not returning nothing :/
What I have done:
Checked if the file is uploading - yes it is in: C:\xampp\htdocs\Story\public\usersImages (if I set destination in this form element) or
C:\xampp\tmp (if I dont set it)
I was wondering about access to this folders but if it save there this images I think it has rights but I set in the apache:
<Directory "C:/xampp/htdocs/Story/public/usersImages">
Allow from All
</Directory>
I was even tried use this function only in C:\xampp\tmp folder:
$source: C:\xampp\tmp\database.png
$destination: C:\xampp\tmp\Srututututut.png
And still nothing :/
Do You have any suggestions?
I think that the problem is with $source = $form->image->getFileName();. The reason is that it will return a name of the file uploaded rather than where it was uploaded to (i.e. its temporary localization).
Thus, I think your source should be as follows:
$fileInfo = $mainForm->image->getTransferAdapter()->getFileInfo();
$source = $fileInfo['image']['tmp_name'];
// to check if the source really points to the uploaded file.
var_dump(file_exists($source));
Ok,
I have no idea why this function is not working. I have changed my idea to set the $form->image destination first in the controller and then rename it and it is working.
Thanks for help guys ;D