Unable to open a file for writing - php

I am trying to write to a file. I do a file_exists check on it before I do fopen and it returns true (the file does exist).
However, the file fails this code and gives me the error every time:
$handle = fopen($filename, 'w');
if($handle)
{
flock($handle, LOCK_EX);
fwrite($handle, $contents);
}
else
{
echo 'ERROR: Unable to open the file for writing.',PHP_EOL;
exit();
}
flock($handle, LOCK_UN);
fclose($handle);
Is there a way I can get more specific error details as to why this file does not let me open it for writing? I know that the filename is legit, but for some reason it just wont let me write to it. I do have write permissions, I was able to write and write over another file.

Just because the file exists doesn't mean that you have permission to write to it. Before trying to write to a file, you should check to see if PHP has permission to do so using is_writable.

or general way of getting errors:
ini_set('display_errors',1); // for the development PC only
error_reporting(E_ALL); // ALWAYS
to see the actual error message

If you're using php 5.2+ you might be interested in error_get_last().
On your development system you can also increase the error reporting level, either within the script via error_reporting() or (preferably) in your php.ini.
error_reporting(E_ALL);
ini_set('display_errors', 1);
$handle = fopen($filename, 'w');
if(!$handle) {
echo 'ERROR: Unable to open the file for writing.',PHP_EOL;
var_dump(error_get_last());
exit();
}
flock($handle, LOCK_EX);
fwrite($handle, $contents);
flock($handle, LOCK_UN);
fclose($handle);

Sounds like the directory you're writing to doesn't have the correct permissions.

Related

Cannot open file using fopen (php)

I am trying to open a file for reading in php script but having trouble.
This is my code
$fileHandle = fopen("1234_main.csv", "r")or die("Unable to open");
if (!file_exists($fileHandle))
{
echo "Cannot find file.";
}
The script is in the same directory as the file I am trying to read and there are no other read/write permission errors as I can create/read other files in the same directory.
When I run the script I just get the "Cannot find file" error message. Why is this error message being shown? Surely if fopen() can't open the file the "or die statement" should end the script?
Also, why can't I open the file when it definitely exists and is in the same location as the script (I have also tried using the full path of the filename instead of just the filename).
I am fairly new to php (but have exp in c++) so if its a stupid question I apologize.
Many thanks
In PHP, file_exists() expects a file name rather than a handle. Try this:
$fileName = "1234_main.csv";
if (!file_exists($fileName))
{
echo "Cannot find file.";
} else {
$fileHandle = fopen($fileName, "r")or die("Unable to open");
}
Also keep in mind that filenames have to be specified relative to the originally requested php-script when executing scripts on a web server.
You can use file_get_content() for this operation. On failure, file_get_contents() will return FALSE.For example
$file = file_get_contents('1234_main.csv');
if( $file === false ){
echo "Cannot find file.";
}
file_exists() take the file-name as input, but the logic of your code has problem. You first try to open a file then you check its existence?
You first should check its existence by file_exists("1234_main.csv") and if it exists try to open it.
file_exists takes a string, not a file handle. See http://php.net/manual/en/function.file-exists.php

file create error in php

I'm creating the file using the php function but it is not working.I have created the folder and set its permission 0777 but it is not creating the file.
I'm using the following code. plz let me know what is going wrong.
$cachefile ='/cache/cache.text';
$file=chmod($cachefile, 777);
if (file_exists($file)) {
include($file);
} else{
$fp = fopen('/cache/cache.txt', 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();
for ob_get_contents() function I'm using the ob_start () function. If I create the file manually it is working and showing the buffering data.Plz let me know how can I create the file using the fopen function.
This line has several issues:
$file=chmod($cachefile, 777);
At that time, the file may not exist, so it may show an error (you cannot do chmod on a file that does not exist).
chmod() will return either true or false. You are trying to use this return value in your code later, saved in the $file variable.
This should work if the cache folder is writable:
$cachefile ='cache/cache.txt';
if (file_exists($cachefile)) {
include($cachefile);
}
else {
$fp = fopen($cachefile, 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();
}

Php fopen write in css file -> file empty

i have this following php code :
$filename = '/front/style.css';
$cssfile='#h1{font-size:12px}';
if($id_file=fopen($filename, "w+"))
{
echo'file exist';
$id_file=fopen($filename, "w+");
flock($id_file,1);
fwrite($id_file,$cssfile);
flock($id_file,3);
fclose($id_file);
}
else
{
echo "file don t exist";
}
My file is empty but with space.
My file exist and it s writable.
I have nothing in my apache logs.
I m using Mamp with php 5.3.2.
Any ideas ?
Thx
A few mistakes I can see are:
You are using fopen to check if a file exists. That does not work. With the w+ mode PHP will try to create the file if it does not exist. Use the file_exits function to check the existence of a file.
You are opening the same file twice.
Also use PHP constants(LOCK_SH, LOCK_UN) for the second argument of flock. That will make your program more readable.
Updated
Have you checked if its writing to a different directory than you expect? Check your path to see where it defaults to, or even just do a search for the file and see where else it turns up. getcwd() will show what the current working dir is.
Have you checked the return value of fwrite to see if the write is actually working? If fwrite is successful, then try read the file in the code using the same $id_file and see if there is anything there while the program is still running.
You are calling fopen twice. w+ truncates the file and you are writing to the 2nd $id_file so my guess is that its being truncated when the 1st $id_file is being closed.
You can use this approach if your file empty after using fopen w+ option.
// only read
$filename = '/path/to/blah.txt';
$myfile = fopen($filename, "r");
$mydata = fread($myfile, filesize($filename));
$mynewdata = $mydata + 'abc';
fclose($myfile);
// only write
$myfile = fopen($filename, "w");
fwrite($myfile, $mynewdata);
fclose($myfile);

PHP writing to file without truncation

I am creating a flatfile database, and I am trying to solve the problem of multiple edits being made at the same time. I understand I need to truncate the file for editing and deleting rows but for adding rows this is not necessary.
So if I were to use fopen($file, 'a') to write to a file, and multiple people where to open the file and write to it, would they all be able to write to the file simultaneously?
Without truncating the file people shouldn't be overwriting each other right?
It's better to use some kind of helper for this.
PHP function flock (File LOCK)
//Open the File Stream
$handle = fopen($file,"a");
//Lock File, error if unable to lock
if(flock($handle, LOCK_EX)) {
$data;
// do anything to fill variable $data
fwrite($handle, $data); //Write the $data into file
flock($handle, LOCK_UN); //Unlock File
} else {
echo "Could not Lock File!";
}
//Close Stream
fclose($handle);
PHP file write threading issues
Read and write to a file while keeping lock

Cannot create a file

I am trying to create a file using php to a dirctory which has cmod 0777 so it should be fine.
Here is the code:
$fh = fopen("/_myfiles/myfile.txt", "w+");
if ($fh==false)
{
die("unable to create file");
}
But all I get is "unable to create file". Any ideas on what it could be?
Note: For the path I've also tried:
$fh = fopen($_SERVER['DOCUMENT_ROOT']."/_myfiles/myfile.txt", "w+");
with no success.
fopen() generates an E_WARNING message on failure.
I recommend using error_reporting(E_ALL) to show the warning and this should help you to troubleshoot the problem from there.
Check write permissions on the directory you want to create the file in.
Also the directory "_myfiles" should exist (it won't be created automatically).
If they are correct, then this will create the file in the same directory where the PHP script is located:
$basedir = dirname(__FILE__);
$fh = fopen($basedir . DIRECTORY_SEPARATOR . 'myfile.txt', 'w+');

Categories