file create error in php - 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();
}

Related

PHP fwrite() not working

I'm writing a function in php, client side I have a canvas image which I use toDataUrl() along with a file name to save the image on the server. The here's the code:
<?php
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
$data = json_decode($imageData, true);
$file = $data["file"];
$image = $data["data"];
$filteredData=substr($image, strpos($image, ",")+1);
$unencodedData=base64_decode($filteredData);
$fp = fopen( 'image/' . $file , 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
?>
The thing is that this code works. And for two out of three of the pages I used it on it works fine. The problem is when I copy and pasted it a third time to implement it again, for some reason the file is made on the server except that no data get's written into the file. I don't think it's a problem client side because I write in a debug alert message in the javascript and a debug echo into the PHP and both are able to print out the data fine. I made this short debug file:
<?php
$fp = fopen('data.txt', 'wb');
if(is_writable('data.txt')){
echo "file is writable<br>";
}
if(fwrite($fp, 'test') == FALSE){
echo "failed to write data<br>";
}
fclose($fp);
?>
And the output is
file is writable
failed to write data
I've tried using chmod and setting everything, the folder, the text file before I write to it to 0777 and I still get the same result; the file is made but no data is written into it. Is there anything I'm missing or any other approaches that might help. I haven't found anything on google and am still baffled as to why the same code worked exactly as expected twice before suddenly stopping for no apparent reason.
Thanks in advance.
I know this is an old post, but I had a very similar problem and found a solution (for me at least)! I ran out of disk space on my server, so it could create a 0 byte file, but wouldn't write to it. After I cleared out some space (deleted a 13gb error.log file) everything started working again as expected.
If fopen works but fwrite mysteriously doesn't, check your disk space. 'df -h' is the command to check disk space on a linux server.
instead of $fp = fopen('data.txt', 'wb'); give $fp = fopen('data.txt', 'w'); and try
Changed "wb" to "w"
When you write $fp = fopen('data.txt', 'w'); for your domain website.com having root at /var/www/website/ and if the php file is located at /var/www/website/php/server/file/admin.php or something similar, it will actually create a file at /var/www/website/data.txt
Try giving absolute path or path relative to your domain root to create files like,
$fp = fopen('php/server/file/data.txt', 'w');
Try the find command to see if the file is created anywhere else in the folder directory by using the following in Ubuntu,
find /var/www/website/ -name 'data.txt'
I had this issue, probably can help you solve if you have similar issue.

Using fopen and fwrite with Zend Framework?

I'm attempting to check for file existence with Zend Framework and, if the file doesn't exist, have it be created. Here's the code being used:
$filename = "/assessmentsFile/rubrics/$rubricID.php";
$somecontent = "test";
if (!$handle = fopen($filename, 'w+')) {
echo "Cannot open file ($filename)";
exit;
}
// Write $somecontent to our opened file.
if (fwrite($handle, $somecontent) === false) {
echo "Cannot write to file ($filename)";
exit;
}
However, I assume due to Zend's way of handling file structure, if a file doesn't exist it just spits out:
Warning: fopen(/assessmentsFile/rubrics/1.php) [function.fopen]: failed to open stream: No such file or directory
Because the fopen function isn't working, fwrite is unable to write the file.
Is there another way of doing this?
Most likely the issue is with the path to $filename.
You have
$filename = "/assessmentsFile/rubrics/$rubricID.php";
which tries to create a file in the root of the server in a directory called assessmentsFile.
Most likely you need to be using:
$filename = $_SERVER['DOCUMENT_ROOT'] . "/assessmentsFile/rubrics/$rubricID.php";
$_SERVER['DOCUMENT_ROOT'] should do the trick if the assessmentsFile folder is in your web root. Otherwise there are other variables you can use to get a fully qualified path, or you can simply hard-code the path:
$filename = "/home/yoursite/public_html/assessmentsFile/rubrics/$rubricID.php";
There's a function file_exists that tells you if the file exists, and with is_file you can check it's a file (and not a directory for example).
(Another way is to suppress warnings by putting an # before the function call (e.g. $handle=#fopen(...), but it's better to check for file existence)
Try this:
if(is_file($filename)){ // exists
$handle=fopen($filename,"w+");
}else{
$handle=fopen($filename,"w"); // create it
}
// ...

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 file writing problem

I'm trying to write to a file in PHP to cache the output of a small portion of code.
ob_start();
echo "Hello";
$fp = fopen("cache/ttcache.php", 'w');
fwrite($fp, ob_get_contents());
fclose($fp);
ob_end_flush();
The file exists and is blank. The fwrite function points to the correct location. It just doesn't write.
Any help?
Try to write first small word or sentence first.
fwrite($fp, 'hello')
Also check your file permission's should be writable.
Make sure ob_get_contents() is really not empty. Then try
fflush($fp);
right before fclose().

Unable to open a file for writing

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.

Categories