this might be a really stupid question but I am getting the following error after the code has successfully deleted the file and I can not work out why, the code is very simple it gets the name and path of the file to be deleted from the database and then deletes it.
Code:
$getFiles = mysql_query("SELECT * FROM tempFiles WHERE pTID='$passedId'");
$numFiles = mysql_num_rows($getFiles);
for ($f=0;$f<$numFiles;$f++) {
$fileName = mysql_result($getFiles,$f,"fileName");
$deleteFile = "../../".$fileName;
unlink($deleteFile);
}
Warning: unlink(../../files/projects/files/643115.jpg): No such file or directory
The script for deleting the file is in a scripts/php/thefile and the file is in files/projects/files/thefile, so the ../../ is definitely needed and not the issue as far as I can tell. I know that the file is being deleted successfully because it is no longer in the folder after I run the script so I have no idea what is causing the error.
Any ideas why I might be getting the error?
Thank you in advance.
Possible causes to the error:
There are more than 1 record in the tempFiles table with the same fileName, so the first attempt removes it and the second causes the error.
The file didn't exists on the folder when you ran the script (as #AxelAmthor said on comment)
To solve it, just add a verification (as #Sammitch said on comment):
if (is_file($deleteFile)) {
unlink($deleteFile);
}
Related
My environment is: Windows, MsSQL and PHP 5.4.
My scenario:
I'm doing a small shell script that creates a full backup from my wanted database to a temp folder and then moves it to a new location.
The backup goes fine and the file is created to my temp folder. Then I rename it to the 2nd folder and sometimes it goes ok, sometimes it cannot find the source file.
Of course at this point I know that I could skip the temporary location alltogether, but the actual problem with not finding the file bothers me. Why is it so random and might it also affect other file functions I've written before this one... Also i need to be able to control how and when the files move to the destination.
The base code is simple as it should be (although this is a simplified version of my actual code, since I doubt anyone would be interested in my error handling/logging conditions):
$query = "use test; backup database test to disk '//server01/temp/backups/file.bak', COMPRESSION;";
if($SQLClass->query($query)) {
$source="////server01//temp//backups//file.bak";
$destination="////server02//storage//backups//file.bak";
if(!rename($source , $destination)) {
//handleError is just a class function of mine that logs and outputs errors.
$this->handleError("Moving {$source} to {$destination} failed.");
}
}
else {
die('backup failed');
}
What I have tried is:
I added a file_exists before it and it can't find the source file either, when rename can't.
As the file can't be found, copy() and unlink() will not work either
Tried clearstatcache()
Tried sleep(10) after the sql backup completes
None of these didn't help at all. I and google seem to be out of ideas on what to do or try next. Of course I could some shell_execing, but that wouldn't remove my worries about my earlier products.
I only noticed this problem when I tried to run the command multiple times in a row. Is there some sort of cache for filenames that clearstatcache() won't touch ? It seems to be related to some sort of ghost file phenomena, where php is late to refresh the file system contents or such.
I would appreciate any ideas on what to try next and if you read this far thank you :).
You may try calling system's copy command.
I had once problem like yours (on Linux box) when i had to copy files between two NFS shares. It just failed from time to time with no visible reasons. After i switched to cp (analog of Windows copy) problem has gone.
Surely it is not perfect, but it worked for me.
It might be cache-related, or the mysql process has not yet released the file.
mysql will dump the file into another temp file, first and finally moves it to your temp folder.
While the file is beeing moved, it might be inaccessible by other processes.
First I would try to glob() all the files inside temp dir, when the error appears. Maybe you notice, its still not finished.
Also have you tried to implemente something like 10 retry iterations, with some delay?
$notMoved = 0;
while($notMoved < 10){
$source="////server01//temp//backups//file.bak";
$destination="////server02//storage//backups//file.bak";
if(!rename($source , $destination)) {
//handleError is just a class function of mine that logs and outputs errors.
if ($notMoved++ < 10){
sleep(20);
} else {
$this->handleError("Moving {$source} to {$destination} failed.");
break;
}
}else{
break;
}
}
To bypass the issue:
Don't dump and move
Move then dump :-)
(ofc. your backup store would be one behind then)
$source="////server01//temp//backups//file.bak";
$destination="////server02//storage//backups//file.bak";
if(!rename($source , $destination)) {
//handleError is just a class function of mine that logs and outputs errors.
$this->handleError("Moving {$source} to {$destination} failed.");
}
$query = "use test; backup database test to disk '//server01/temp/backups/file.bak', COMPRESSION;";
if($SQLClass->query($query)) {
//done :-)
}
else {
die('backup failed');
}
Try
$source = "\\server01\temp\backups\file.bak";
$destination = "\\server02\storage\backups\file.bak";
$content = file_get_content($source);
file_put_contents($destination, $content);
I am writing some php script to update the code on my sites. In order to do that I have written the following lines which checks for the update version and bring the name from where I use to distribute my updates ans then creates the link of that name. I have done something like this.
$filename = "http://www.hf-live.com/codeupdate/Get_Files_Name.php";
$contents = file_get_contents($filename);
echo $contents;
I am getting this error
failed to open stream: No such file or directory.
Even though the file is present still I am getting the same error. I have turned on my allow_url_fopen to on. The above code is working from my local host but not from the server. I have to update a major bug fix and I am stuck.. Please someone help me soon..
remove extra .php from url
$filename = "http://www.hf-live.com/codeupdate/Get_Files_Name.php";
You will get error if you are doing this way...
$filename = "marynyhof.com/Info.php"; // will give you error, which exactly you are getting
use full url like this
$filename = "http://www.marynyhof.com/Info.php"; //will work
my code keeps on saying that the folder does not exist though it should be checked by the mkdir function..it creates the folder but does not go through the uploading process.. and displays the error on the couldnt find the folder.. is the algorithm correct? please help.. Your advice will help! :)
here is the code..
if(!(file_exists($target_path)))
{
if(!mkdir($target_path, 0777, TRUE))
{
die ("could not create the folder on mkdir");
}
//in this line the error occurs..printing what is below..//
die ("could not find folder on file exists");
}
else
{
umask($target_path);
...
}
file_exists() routine requires the complete path to file like
/var/www/uploads/file1.c
so the
file_exists($target_path);
call is ok . but second call to make directory, ie,
mkdir()
is requiring an directory , not an path to an file ie, it require /var/www/upload part only .
so you can remove the basename from path name and apply it to mkdir function()
try..
if(file_exists($target_path) && is_dir($target_path)){ //rest of the code...
}
instead of...
if(!(file_exists($target_path))){
}
Hope this will do something for you...
...............................
one thing more...
i think the problem is with if(!(file_exists($target_path))){} Statement,
THIS SHOULD BE...
if(!file_exists($target_path)){}
during the file upload process, your file saving path in move_uploaded_file()
function may be creating problem. I am saying may be because your given code is not clear enough to me. Second parameter of move_uploaded_file() is the destination where first parameter is the file name. please check the value of $target_path, it may solve your problem. thank you.
I'm writing a PHP application and in my code i want to create create and return images to the browser. However, sometimes i'm getting some weird results where the image cannot be created since the file does not seem to exist.
Here is a sample error message I get and the code in a nutshell. I do know that the image exists, but still the method sometimes fails, and sometimes it succeeds, even for the same file.
The error:
Warning: imagecreatefrompng(path/to/image.png) [function.imagecreatefrompng]: failed to open stream: No such file or directory in file test.php on line 301
The code:
if (file_exists($filename)) {
$image = imagecreatefrompng($filename);
}
I would greatly appreciate any hints or tips of what might be wrong and how I can improve the code to be more stabile.
I suggest you use is_readable
if (is_readable($filename)) {
$image = imagecreatefrompng($filename);
}
The file may "exist" but is the file accessible? what does file_exists actually do?
if it opens the file and then closes it make sure that the file is actualy closed and not locked before imagecreatedfrompng fires.
it would be a good idea to try catching the error in a loop and make 4 or 5 attempts before handing back a controlled error.
maybe try is_readable() or is_writable() instead?
Have you considered checking for the correct permissions? If the file cannot be read, but the directory can, you would get file_exists(...) = true, but would not be able to open a handle to the file.
Use is_readable() to check whatever you have permission to access that file.
You can try GD :
IF($img = #GETIMAGESIZE("testimage.gif")){
ECHO "image exists";
}ELSE{
ECHO "image does not exist";
}
bro check for white spaces in your filepath. I recently had this issue while i was tring to include a file from a module i was creating for an app. Other modules included well when called but one didnt. It turned out that there was a white space in the filepath. I suggest u try php trim() function. If this works holla.
I use a form where i have listed the data from database like title, date etc. from the database and using checkboxes i use the multiple delete operation
For example my code look like this
<form method="post" action="action.php">
<input name="checkbox[]" type="checkbox" id="checkbox[]" value="<?php echo $row['id']; ?>"/>
<input name="delete" type="submit" id="delete" value="Delete"/>
and in the action.php the code is like this
$checkbox = $_POST['checkbox'];
//count the number of selected checkboxes in an array
$count = count($checkbox);
//Create a for loop to delete
for($i=0;$i<$count;$i++) {
$del_id = $checkbox[$i];
$sql = "DELETE FROM news WHERE id='$del_id'";
$result_delete_data = mysql_query($sql);
}
Now the table i want to delete actually have 5 table entities like title, timestamp,pic_title,pic_brief,pic_detail the last three entities i.e pic_title, pic_brief and pic_detail is actually storing the path of the image for example the value stored in one of the 3 entity would look like this upload/file/pic_title1.jpg
My problem is when i run my first for loop it successfully deletes the table without any problem but the file which exist in the file directory remains intact. i want to delete that file too, to remove that file i thought of adding another for loop which i did something like this
for($j=0;$j<$count;$j++){
$delete_id = $checkbox[$j];
$query = "SELECT news.pic_title, news.pic_brief, news.pic_detail FROM news WHERE id = '$delete_id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
unlink($row['pic_title']);
unlink($row['pic_brief']);
unlink($row['pic_detail']);
}
The above code is unable to delete the requested file, my Query string is perfectly working fine i tested it by removing the unlink function and printing the values, it prints all the selected value , but it is refusing to delete the file and when i try to run the loop it shows error in the last three line, while i am pretty sure that, $row['pic_title'], $row['pic_brief'], $row['pic_brief'], have the full path of the image.
unlink($row['pic_title']);
unlink($row['pic_brief']);
unlink($row['pic_brief']);
where i am going wrong?
P.S: There is nothing wrong with file permission because when i individually try to run the function unlink it deletes the file from the same directory.
EDIT : This is the error message i get
Warning: unlink() [function.unlink]: No error in C:\wamp\www\bn\admin-login\action.php on line 580
Warning: unlink() [function.unlink]: No error in C:\wamp\www\bn\admin-login\action.php on line 581
Warning: unlink() [function.unlink]: No error in C:\wamp\www\bn\admin-login\action.php on line 582
To be more precise i tested this function individually in php and it is working perfectly fine
$target = 'upload/file/file1.jpg';
unlink($target);
and for this reason i dont think the file permission is causing the error, i guess i am going wrong somewhere with the logic.
#Lekensteyn got me the solution, thank you Lekensteyn.
actually i had to first hold the value in a variable and then unlink the file. the working code looks like this.
for($j=0;$j<$count;$j++){
$delete_id = $checkbox[$j];
$query = "SELECT * FROM news WHERE id = '$delete_id'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$pic_title = $row['pic_title'];
$pic_brief = $row['pic_brief'];
$pic_detail = $row['pic_detail'];
unlink($pic_title);
unlink($pic_brief);
unlink($pic_detail);
}
It could be file permissions. You need to be the owner of the file in order to delete it.
Some hosters run the website under the user 'apache' (or similar), but the files are owned by the ftpuser (accountxxxx for example).
Check the current working dir too, with echo getcwd() if the paths not absolute.
Your script is vulnerable to SQL injection too, a post request with checkbox[]='||1||' deletes everything.
Add
error_reporting(E_ALL);
at the top of your script.
Your problem is program flow related and can be found only by using debugging.
Start from displaying ALL errors occurred and repair them. This will most likely lead you to the reason you could not delete your files.
Probably your path to upload is the problem. In your test script:
$target = 'upload/file/file1.jpg';
unlink($target);
I bet you ran that from a directory right below 'upload/' right?
And this delete script, it's probably not in the same directory?
I recommend using the full path to the 'upload/file/' directory; this will vary depending on your configuration, but probably looks like /www/htdocs/upload/file or /var/www/public_html/upload/file.
To make the script more transportable, you can use the PHP constant FILE to figure out the directory. I usually set this app/site wide in a bootstrap or universal configuration file, along the lines of
define('PATH', dirname(__FILE__)); # sets PATH with the directory name of the bootstrap file where this code lives
I sometimes key on something in my path I can rely on, say my app name. Say my bootstrap is here:
/www/apps/golf-scorecard/bootstrap.php
I might split on 'golf-scorecard'.
list($path,) = explode('golf-scorecard',dirname(__FILE__)); # $path should be /www/apps/
define('PATH', $path.'golf-scorecard'); # since I split on it, I have to add it back in
This means if I move the app/site to another server, or clone it from a repository onto a machine where the document root is, say /home/username/apps/golf-scorecard/htdocs/, then it won't matter. It does couple the app name but I am okay with that.
first thing is you need to check the file permissions .you need to give 777 permission to the folder.and then follow below code
$target = 'upload/file/file1.jpg';
unlink($target);