Php unlink error no such file or directory
Я всюду искал эту проблему и не могу найти решение. У меня есть это:
unlink возвращает ошибку: No such file or directory , но если я попробую header(«location: $file_delete»); это открывает файл (изображение в этом случае).
Решение
У меня та же проблема с этим (упрощенным) кодом:
Где $ file — абсолютный путь к файлу.
Следующая ошибка генерируется в производстве (у провайдера), а не при локальном тестировании:
Got error 'PHP message: PHP Warning: unlink(/xxxx/yyyy/zzzz/abcdefg.txt): No such file or directory in /xxxx/yyyyy/zzzzz/phpfile.php on line 1234'
Другие решения
После некоторых исследований, unlink() похоже, не позволяет использовать относительные пути (с «../»).
$file_delete здесь абсолютный путь к файлу, который вы хотите удалить.
Напоминание: / используется для систем Unix, для Windows.
PHP документ:
— http://php.net/manual/en/function.unlink.php
— http://php.net/manual/en/function.dirname.php
У меня также была такая же проблема с моим кодом. Что я сделал, чтобы решить эту проблему:
var_dump($image_variable) // var_dump($file_delete) in your case.
Выводит: string (23) (my-image-path)
Когда я начал считать строку, я нашел 22 символа. Я задавался вопросом, где 23-й?
Я проверил и тщательно просчитал, в конце я обнаружил, что в конце пути к моему изображению есть место. Поэтому я использовал функцию php trim () для удаления пробелов. Подобно,
$trimed_path = trim($image_variable) // trim($file_delete) in your case.
Мне понадобилось пару часов, чтобы разобраться. Как упоминалось выше, unlink () требователен к путям.
1-й) Определите путь (вот как WordPress это кстати):
define( 'ROOTPATH', dirname(dirname(__FILE__)) . '/' );
unlink(ROOTPATH.'public_html/file.jpg');
За последние 24 часа нас посетили 13567 программистов и 1266 роботов. Сейчас ищут 385 программистов …
Здравствуйте, помогите пожалуйста! Не работает функция unlink с указанием ссылки на файл подписанный кириллицей. Вот ошибка:
Warning: unlink(../documents/reshenya/файл.doc): No such file or directory in D:OpenServerdomainsnew0engine1.php on line 3
Как можно решить данную проблему? Нужно что бы удалялись подобные файлы (Подписанные русскими буквами) средствами php
Вот сам код файла php:
Команда форума
Модератор
Команда форума
Модератор
Команда форума
Модератор
Команда форума
Модератор
у меня unlink не работает, указываю абсолютный путь вроде, пишут, что должно работать… в логах: ….html): No such file or directory in /var/…
ищет в той папке в которой расположен скрипт, но не в той куда указал может всё-таки права не те? 644, хотя выше написали, что варнинг другой был бы…
— Добавлено —
не получается, хоть тресни… и относительный и абсолютный пусть пробовал
мож теперь строго и только filename можно прописывать? удаляет только в том же каталоге, что и выполняется…
— Добавлено —
пробую с file://
та же ерунда, не находит у кого-нить работает? чтобы выполнялся в одной папке, а удалял в другой?
Команда форума
Модератор
Ты должен был насторожиться сразу, как увидел это: Потому что это не ошибка Unlink-а, это ошибка файловой системы машины в ответ на запрос дескриптора файла со стороны PHP.
@Fell-x27 там дальше был путь папки, где лежит исполняемый скрипт, вот я и подумал, что пути не работают, только filename… по идее в логах должен быть No such file or directory in в той папке где я ищу, а не там где исполняется скрипт
Recommended Answers
Of course you can.
The error ays that the image doesn’t exist. Make sure your script is in the same dir as you image, then try to add a «./» at the beginning of image-name. And if all doesn’t work, that you could try to delete the image giving …
i have changed the code now so that it uses the path to the iage but the problem i am having now is that if the file extension is not the same then it will not overwrite the image. how can i get it to delete the image no matter …
might want to set the umask to 0 before doing chmod. http://www.php.net/umask
$result = false; // result of the unlink (true|false) $exts = array('jpg', 'png', 'gif', 'jpeg'); foreach($exts as $ext) …
All 12 Replies
39
Posting Whiz in Training
The error ays that the image doesn’t exist. Make sure your script is in the same dir as you image, then try to add a «./» at the beginning of image-name. And if all doesn’t work, that you could try to delete the image giving the complete path (eg. «/home/acmeart/public_html/mercury/image/thumbs/thumb_1.jpg»).
Probably you don’t have the permission to unlink the file, but then I guess the error would be a different.
i have changed the code now so that it uses the path to the iage but the problem i am having now is that if the file extension is not the same then it will not overwrite the image. how can i get it to delete the image no matter if it is jpg, gif, png.
the code i am using now looks like this i have added a bit to delete both copies of the image (original and thumbnail).
$fileToRemove = '/home/acme/public_html/image/thumbs/thumb_image1'; if (file_exists($fileToRemove)) < // yes the file does exist unlink($fileToRemove); >else < // the file is not found, do something about it. >$fileToRemove = '/home/acme/public_html/image/image1'; if (file_exists($fileToRemove)) < // yes the file does exist unlink($fileToRemove); >else < // the file is not found, do something about it. >
i need some code to go on the end of the filetoremove line to it checks for all file extension or just delets it by name without the extionsion getting looked at.
399
Nearly a Posting Virtuoso
i have changed the code now so that it uses the path to the iage but the problem i am having now is that if the file extension is not the same then it will not overwrite the image. how can i get it to delete the image no matter if it is jpg, gif, png.
the code i am using now looks like this i have added a bit to delete both copies of the image (original and thumbnail).
$fileToRemove = '/home/acme/public_html/image/thumbs/thumb_image1'; if (file_exists($fileToRemove)) < // yes the file does exist unlink($fileToRemove); >else < // the file is not found, do something about it. >$fileToRemove = '/home/acme/public_html/image/image1'; if (file_exists($fileToRemove)) < // yes the file does exist unlink($fileToRemove); >else < // the file is not found, do something about it. >
i need some code to go on the end of the filetoremove line to it checks for all file extension or just delets it by name without the extionsion getting looked at.
The short way of doing this would be:
if (@unlink($fileToRemove)'.jpg' || @unlink($fileToRemove).'.png' || @unlink($fileToRemove).'.gif') < // unlinked successfully >
This just tries each one in succession and suppresses errors. This if the reason for the @ sign before the function calls.
It would probably be better to use a loop though, and check for file existence and permissions.
$exts = array('jpg', 'png', 'gif', 'jpeg'); foreach($exts as $ext) < if (file_exists($fileToRemove.'.'.$ext)) < if (!is_writable($fileToRemove.'.'.$ext) < @chmod(0777, $fileToRemove.'.'.$ext); >@unlink($fileToRemove); > >
399
Nearly a Posting Virtuoso
might want to set the umask to 0 before doing chmod. http://www.php.net/umask
$result = false; // result of the unlink (true|false) $exts = array('jpg', 'png', 'gif', 'jpeg'); foreach($exts as $ext) < if (file_exists($fileToRemove.'.'.$ext)) < if (!is_writable($fileToRemove.'.'.$ext) < umask(0); @chmod($fileToRemove, 077.'.'.$ext); >if (@unlink($fileToRemove)) < $result = true; >> >
btw: chmod takes the filename as first parameter, my previous post had it the other way round..
thanks for the replay i think it is working now i is just having a bit of trouble displying the images on the sent email.
as the images can have different extensions at the end. when i come to display the image using the html img tag with the path to the file the extension must be correct for it to display.
the code i have used to display the image looks like this
but because it has .gif on the end it will not work if a jpg or png is uploaded. i could fix it by only letting .gif be uploaded but this would not be useful for the user.
is there away of concatenating the file extensions so that it can select which one it needs to look for.
i have used php before to work through file extension until it finds the one it needs to display but as the email must be straight html how can this be done.
399
Nearly a Posting Virtuoso
thanks for the replay i think it is working now i is just having a bit of trouble displying the images on the sent email.
as the images can have different extensions at the end. when i come to display the image using the html img tag with the path to the file the extension must be correct for it to display.
the code i have used to display the image looks like this
but because it has .gif on the end it will not work if a jpg or png is uploaded. i could fix it by only letting .gif be uploaded but this would not be useful for the user.
is there away of concatenating the file extensions so that it can select which one it needs to look for.
i have used php before to work through file extension until it finds the one it needs to display but as the email must be straight html how can this be done.
You can use PHP to output the HTML for the email. It would be best if you had saved the image extensions with the images to begin with so that you don’t have to iterate through each possible extension each time you reference an image.
Anyways, just iterate through each image with file_exists() and which ever one exists, output it in the HTML.
the image extension are saved with the images. if the file_exists is used and the file is set to the variable how should the img tag be written to display this image. i have written it like this
as i am already using php to send the html out as an email i cannot use the echo function as it will not work inside the body of the message and i think it would not be sent any way as it is using php to display the image and only html can be sent in the body of the email.
at the top of the send mail page were the body is created i have entered the file_exists code so that when the file is sent the path to the file is held on this page and the variable will always hold a value.
399
Nearly a Posting Virtuoso
the image extension are saved with the images. if the file_exists is used and the file is set to the variable how should the img tag be written to display this image. i have written it like this
as i am already using php to send the html out as an email i cannot use the echo function as it will not work inside the body of the message and i think it would not be sent any way as it is using php to display the image and only html can be sent in the body of the email.
at the top of the send mail page were the body is created i have entered the file_exists code so that when the file is sent the path to the file is held on this page and the variable will always hold a value.
Lets say your email will be saved in the string: $email
$email = ''; $image = false; $image_name = 'my_jpg_png_or_gif_image'; $exts = array('jpg', 'png', 'gif', 'jpeg'); // check for each extension foreach($exts as $ext) < if (file_exists($image_name.'.'.$ext)) < $image = $image_name.'.'.$ext; >> // check if we have an image if ($image) < // ok we have the image $web_image_folder = 'http://example.com/images/'; // here we add teh correct image to the email. $email = 'hi, here is your image '; // send your email > else < // error, we can't find the image. >
thanks for that reply it looks like i will be able to get it work from that code you gave me. sorry it took so long for the reply i have been working on something different today.
i have changed the code a bit to suit how i needed it to work but it is not displaying the images on the page. i may have messed the code up. if you can see a problem please point this out.
$image = false; $exts = array('jpg', 'png', 'gif', 'jpeg'); $image_name = thumb_image1.'.'.$exts; // check for each extension foreach($exts as $ext) < if (file_exists($image_name.'.'.$ext)) < $image = $image_name.'.'.$ext; >> // check if we have an image if ($image) < // ok we have the image $web_image_folder = 'http://www.acmeart.co.uk/mercury/image/thumbs'; >else < // error, we can't find the image. >
the code i have used to display the image inside the body of the email looks like this:
i have now removed the bottom half of the code and move the some of it to the top part of the code. it now looks like this:
$image = false; $web_image_folder = 'http://www.acmeart.co.uk/mercury/image/thumbs'; $exts = array('jpg', 'png', 'gif', 'jpeg'); $image_name = 'thumb_image1.'.'.$exts'; // check for each extension foreach($exts as $ext) < if (file_exists($web_image_folder.'/'.$image_name.'.'.$ext)) < $image = $image_name.'.'.$ext; >>
the code is still not working though.
the reason i changed the code to your post is because the email message that i am sending has already been coded at the bottom of the page so all i need to do is add the images inside the body in the correct places.
with a bit of luck it will be working soon enough.