Cannot write to a file using php - php

I've seen similiar questions but the answers did not help me. I'm using the code below. I have checked, the file is being read and it will output the number in count.txt on the page. $hit_count is indeed being incremented (I echoed that for a test). count.txt has permissions 777 and count.txt is in the same directory as the page I want the data to appear on. I have no idea what to do next. It's incredibly simple code and I have searched for an answer for hours.
<?php
$hit_count = #file_get_contents('count.txt'); // read the hit count from file
echo "Site visits since Jun 30,2012: ";
echo $hit_count; // display the hit count
$hit_count++; // increment the hit count by 1
#file_put_contents('count.txt', $hit_count); // store the new hit count
?>
If I remove the # sign to test the error I get the following:
Warning: file_put_contents(count.txt) [function.file-put-contents]: failed to open stream: Permission denied in D:\Hosting\9541237\html\indexTEST.php on line 220
What permissions? count.txt is 777.

I would check to see what php thinks your file permissions are using fileperms.
See this question for more info.

Related

PHP rename() function not working properly. Alternative access is denied (code: 5)

I am facing a strange situation with php rename() function. I download a file using API and then moved that file to destination folder.
$download_path =
C:\Users\JOHN\AppData\Local\Temp/downloaded_folder/downloaded_file.png
$moving_path = C:\xampp\htdocs\project-1/images/downloaded_file.png
Every time downloading is working perfectly and file downloaded
The rename() function is working alternatively. ie on first time it works second time fails. 3rd time ITS works 4th time fails etc.
ie first time file moved . and second time i am getting warning
Warning:
rename(C:\Users\JOHN\AppData\Local\Temp/downloaded_folder/downloaded_file.png,C:\xampp\htdocs\project-1/images/downloaded_file.png):
Access is denied (code: 5)
Warning: copy(C:\xampp\htdocs\project-1/images/downloaded_file.png):
Failed to open stream: Permission denied
Please see my code below.
if (file_exists($moving_path)) {
#unlink($moving_path);
}
if (file_exists($download_path) && !file_exists($moving_path)) {
if (!rename($download_path, $moving_path)) {
if (copy ($download_path, $moving_path)) {
echo 'no rename but copied';
} else {
echo 'not moved';
}
} else {
echo 'moved';
}
#rmdir(dirname($download_path))
}
Here what happen is first time it's moved and downloaded_file.png coming inside project-1/images folder & echo moved and second time there is no file coming and echo not moved .
Third time downloaded_file.png coming inside project-1/images folder & echo moved and 4th time there is no file coming and echo not moved.
How to solve this issue. Please help. I seen a similar question but that answer also not working for me
It seems that you do not have the correct folder permissions for:
C:\xampp\htdocs\project-1/images/
As you have this directory showing up in your error for the rename and the copy functions. Set this directory's permissions to 750, for your basic needs.
Since you're using windows:
Right Click>Properties>Security Tab
Change the permissions for your user the script is running under to "Read & execute" and "Write".

Receiving unlink() error after it has been successful

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);
}

how to open a file while inside a foreach(glob....PHP

I have a small number of image files and text files. They have the same file name with different extensions. I need to read the image files and for each image I need to read some (tool top) text from the corresponding text file. The problem is the file open inside the "foreach( glob("inserts/*.png")" loop fails. I have output the filename and the fopen works fine. I thought it may be you are unable to open two file concurrently in PHP but I could find nothing about it when I googled
foreach( glob("inserts/*.png" ) as $filename ) {
$path="public/xml/iweb/".$filename;
$insertpath=substr($filename, 0, -3)."txt";
$myfile = fopen($insertpath, "r");
$rec=fread($myfile,filesize($insertpath));
fclose($myfile);
$name=getInnerSubstring($rec,"-");
$HTML5.="<img class='insertimage' src='".$path."' title='".$name."' onclick='insertcomponent(\"".$insertpath."\")'>";
}
One day I hope I know enough to answer questions instead of just asking them. :(
There's no reason why you shouldn't be able to open multiple files and no reason the foreach should break anything that works. My hunch is that the path you're trying to open is wrong. I suggest either debugging the code to see the variables or add an echo to see their content. You should also check if fopen() and fread() don't return some false because they failed. Good luck :)

file_get_contents() failed to open stream: No such file or directory

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

Why i am not able to delete the files(PHP)?

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);

Categories