unlink is showing error that is not present - php

I am trying to delete image from server but unlink is showing error that is not a error at all. My code is given below:
private function delete_image($ad_id){
$this->load->helper('file');
$sql = "SELECT image1,image2,image3 from ads where AdId = ?";
$query = $this->db->query($sql,array($ad_id));
//for fetching result
$result = $query->result_array();
//to make a array of all images
$img = [$result[0]['image1'],$result[0]['image2'],$result[0]['image3']];
$i = 0;
while ($img[$i]!= "edubuylogo.png" && $i<3){
unlink('./uploads/'.$img[$i]);
$i++;
}
}
and the link to image is http://localhost/edubuy/uploads/IMG_20180120_210433.jpg
And image is perfectly loading.
The error is Message:
unlink(/uploads/IMG_20180120_210433.jpg): No such file or directory

It seems that your computer is confused, and you should specify an absolute path. In CodeIgniter you can use the FCPATH constant, so do like this:
unlink( FCPATH . 'uploads/' . $img[$i] );
That assumes your index.php file is inside edubuy. If it's not then:
unlink( FCPATH . 'edubuy/uploads/' . $img[$i] );

Related

Delete Array Of Filenames Inside A Foreach Loop Using PHP

I am creating a 'delete account' function for users of a site if they want to delete all of their details.
Deleting the relevant records from the database has been pretty straight forward. However, I want to deleted the images they have saved in the site's images folder.
Below is the code I'm trying, a part of which is based on #kmoser's suggestion.
// $db_image_id, $db_image_ext, $db_image_filename are fetched in a previous code block for when images are outputted on the page.
if(isset($_POST['delete-account'])) {
$loggedInUser = $_SESSION['logged_in'];
$imagesLibrary = 'images-lib/';
$imagesDownload = 'images-download/';
try {
$s = $connection->prepare("SELECT filename FROM `imageposts` WHERE user_id = :user_id");
$s->bindParam(':user_id', $loggedInUser);
$s->execute();
// -- DELETE THE USER'S IMAGE FILES FROM 'IMAGES-LIB' FOLDER
while ($row = $s->fetch()) {
if (isset($pattern)) {
$pattern = $imagesLibrary . $row['filename'] . '-{500,750,1000,1500}' . '.' . $row['file_extension'];
foreach (glob($pattern, GLOB_BRACE) as $filenames) {
unlink($filenames);
}
}
}
header("Location: index.php");
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
}
The key piece of the above code is this snippet below:
// -- DELETE IMAGE FILES FROM 'IMAGES-LIB' FOLDER
while ($row = $s->fetch()) {
if (isset($pattern)) {
$pattern = $imagesLibrary . $row['filename'] . '-{500,750,1000,1500}' . '.' . $row['file_extension'];
foreach (glob($pattern, GLOB_BRACE) as $filenames) {
unlink($filenames);
}
}
}
I was initially getting an error PHP Notice: Undefined index: file_extension in /Applications/MAMP/htdocs/site/profile-edit.php in relation to the 3rd line of PHP code above that declares the $pattern variable. I've managed to fix this by wrapping the code in the if(isset($pattern)) if statement that is now present. I don't get any error logs now, but the files are not being deleted out of the 'images-lib' directory.
A typical filename example is 6146972e2dc73_1632016174-500.jpeg
Here is an example of how the files look in the database:
When outputted onto a page in an <img> tag, the size e.g. -500 part of the filename is concatenated on with a string inside the src attribute.
src="<?php echo '/images-lib/' . $db_image_filename . '-500' . '.' . $db_image_ext; ?>"
Any help or assistance on how to delete images specific to a user from the images directory would be wonderful.
There's no need to store the filenames and extensions in separate arrays, or even in an array at all. Just fetch every image filename and extension in a loop, assemble it into a pattern (e.g. images/6146972e2dc73_1632016174-{500,750,1000,1500}.jpeg, then glob() the pattern to find each matching file and unlink it:
while ($row = $s->fetch()) {
$pattern = $imagesLibrary . $row['filename'] . '-{500,750,1000,1500}.' . $row['file_extension'];
foreach (glob($pattern, GLOB_BRACE) as $filename) {
unlink($filename);
}
}

Laravel show all images from folder

I upload from vue 4-5 images to different folders in laravel.
public function uploadImageso2orders(Request $request, $id)
{
$o2order = O2order::findOrFail($id);
$name = $o2order->contactname;
$name2 = str_replace(' ', '_', $name);
$image = $request->file('file');
$imageName = $name2.'.'.time().'.'.$image->extension();
$wwwPath = 'https://api2.api.sk/storage/';
$image->move(storage_path('app/o2/servisne' . '/' . $name2),$imageName);
$imagePath = 'https://api2.api.sk/storage/app/o2/' . ('servisne' . '/' . $name2);
$o2order->servisny = $imagePath;
$o2order->save();
}
This is working fine. In storage/app/o2/servisne_listy/ is folder created and multiple images stored. In sql is written full path to this folder.
I need to show this image or images, sometimes its one sometimes more, not same.
I have this:
public function showImageso2orders(Request $request, $id)
{
$o2order = O2order::findOrFail($id);
$servisny = $o2order->servisny;
return response()->json(['servisny' => $servisny], 200);
}
Its shows only the path from sql, but i need path to every file which is in this directory.
Thanks
May be this help you
$path = storage_path('app/o2/servisne');
$files = File::files($path)

How to remove image from web root when data edit and update by cakephp

I write a edit function to update news's info, delete previous image from web root and insert new image:
code is below:
if(unlink($data['News']['image_url']['tmp_name'], WWW_ROOT . 'media/' . $data['News']['image_url']['name'])) //delete image from root and database
{
echo 'image deleted.....'; //success message
}
I can't delete old image and insert new image,how can i correct my function ?
Here your data can not find existing data. use this code
$data1 = $this->News->findById($newsid);
$this->request->data = $data1;
$directory = WWW_ROOT . 'media';
if(unlink($directory.DIRECTORY_SEPARATOR.$data1['News']['image_url']))
{
echo 'image deleted.....';
}
Pass filepath as first argument of unlink():
unlink(WWW_ROOT . 'media/' . $data['News']['image_url']['name'] . '/' . $data['News']['image_url']['tmp_name']);
Also make sure that you have proper permissions to perform this operation in directory containing image.

rename file names php

I need to swap file names using php. For example I have two files, first file: image1.jpg and the second file: image2.jpg. I want to swap the file names. So that the first file will be names image2.jpg and the second file will be named image1.jpg;
my failed attempt at this:
function swap($name1, $name2)
{
$tempName1 = "temporary1";
$tempName2 = "temporary2";
myRename($name1, $tempName1);
myRename($name2, $tempName2);
myRename($tempName1, $name2);
myRename($tempName2, $name1);
}
function myRename($oldTitle, $newTitle)
{
$oldDirectory = "images/".$oldTitle.".jpg";
$newDirectory = "images/".$newTitle.".jpg";
rename($oldDirectory, $newDirectory);
}
How can I successfully swap the names?
Something like this will solve your problem:
swap($file1, $file2, 'test/');
function swap ($name1, $name2, $dir = '') {
rename($name1, $name1 . '-tmp');
rename($name2, $name2 . '-tmp');
rename($name2 . '-tmp', $dir . $name1);
rename($name1 . '-tmp', $dir . $name2);
}
Hope this helps!
<?php
rename('images/image1.jpg','images/tmp.jpg');
rename('images/image2.jpg','images/image1.jpg');
rename('images/tmp.jpg','images/image2.jpg');
function myRename($oldTitle, $newTitle)
{
$fullpath="C:\HD path to that file";//sth like that for full path
$oldDirectory = $fullpath."images/".$oldTitle.".jpg";
$newDirectory = $fullpath."images/".$newTitle.".jpg";
rename($oldDirectory, $newDirectory);
}
Use absolute or relative path to rename

How do I set relative paths in PHP?

I have an absolute path of (verified working)
$target_path = "F:/xampplite/htdocs/host_name/p/$email.$ext";
for use in
move_uploaded_file($_FILES['ufile']['tmp_name'], $target_path
However when I move to a production server I need a relative path:
If /archemarks is at the root directory of your server, then this is the correct path. However, it is often better to do something like this:
$new_path = dirname(__FILE__) . "/../images/" . $new_image_name;
This takes the directory in which the current file is running, and saves the image into a directory called images that is at the same level as it.
In the above case, the currently running file might be:
/var/www/archemarks/include/upload.php
The image directory is:
/var/www/archemarks/images
For example, if /images was two directory levels higher than the current file is running in, use
$new_path = dirname(__FILE__) . "/../../images/" . $new_image_name;
$target_path = __DIR__ . "/archemarks/p/$email.$ext";
$target_path = "archemarks/p/$email.$ext";
notice the first "/"
/ => absolute, like /home
no "/" => relative to current folder
That is an absolute path. Relative paths do not begin with a /.
If this is the correct path for you on the production server, then PHP may be running in a chroot. This is a server configuration issue.
Assuming the /archemarks directory is directly below document root - and your example suggests that it is -, you could make the code independent of a specific OS or environment. Try using
$target_path = $_SERVER['DOCUMENT_ROOT'] . "/archemarks/p/$email.$ext";
as a generic path to your target location. Should work fine. This notation is also independent of the location of your script, or the current working directory.
Below is code for a php file uploader I wrote with a relative path.
Hope it helps. In this case, the upload folder is in the same dir as my php file. you can go up a few levels and into a different dir using ../
<?php
if(function_exists("date_default_timezone_set") and function_exists("date_default_timezone_get"))
#date_default_timezone_set('America/Anchorage');
ob_start();
session_start();
// Where the file is going to be placed
$target_path = "uploads/" . date("Y/m/d") . "/" . session_id() . "/";
if(!file_exists( $target_path )){
if (!mkdir($target_path, 0755, true))
die("FAIL: Failed to create folders for upload.");
}
$maxFileSize = 1048576*3.5; /* in bytes */
/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$index = 0;
$successFiles = array();
$failFiles = null;
$forceSend = false;
if($_SESSION["security_code"]!==$_POST["captcha"]){
echo "captcha check failed, go back and try again";
return;
}
foreach($_FILES['attached']['name'] as $k => $name) {
if($name != null && !empty($name)){
if($_FILES['attached']['size'][$index] < $maxFileSize ) {
$tmp_target_path = $target_path . basename( $name );
if(move_uploaded_file($_FILES['attached']['tmp_name'][$index], $tmp_target_path)) {
$successFiles[] = array("file" => $tmp_target_path);
} else{
if($failFiles == null){
$failFiles = array();
}
$failFiles[] = array ("file" => basename( $name ), "reason" => "unable to copy the file on the server");
}
} else {
if($failFiles == null){
$failFiles = array();
}
$failFiles[] = array ("file" => basename( $name ), "reason" => "file size was greater than 3.5 MB");
}
$index++;
}
}
?>
<?php
$response = "OK";
if($failFiles != null){
$response = "FAIL:" . "File upload failed for <br/>";
foreach($failFiles as $k => $val) {
$response .= "<b>" . $val['file'] . "</b> because " . $val['reason'] . "<br/>";
}
}
?>
<script language="javascript" type="text/javascript">
window.top.window.uploadComplete("<?php echo $response; ?>");
</script>

Categories