PHP fwrite() not working - php

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.

Related

MAMP strange behaviour : php read external file from an http:// is very slow, but from https:// is quick

I have a simple PHP script to read a remote file line-by-line, and then JSON decode it. On the production server all works ok, but on my local machine (MAMP stack, OSX) the PHP hangs. It is very slow, and takes more than 2 minutes to produce the JSON file. I think it's the json_decode() that is freezing. Why only on MAMP?
I think it's stuck in while loop, because I can't show the final $str variable that is the result of all the lines.
In case you are wondering why I need to read the file line-by-line, it's because in the real scenario, the remote JSON file is a 40MB text file. My only good performance result is like this, but any good suggestion?
Is there a configuration in php.ini to help solve this?
// The path to the JSON File
$fileName = 'http://www.xxxx.xxx/response-single.json';
//Open the file in "reading only" mode.
$fileHandle = fopen($fileName, "r");
//If we failed to get a file handle, throw an Exception.
if($fileHandle === false){
error_log("erro handle");
throw new Exception('Could not get file handle for: ' . $fileName);
}
//While we haven't reach the end of the file.
$str = "";
while(!feof($fileHandle)) {
//Read the current line in.
$line = fgets($fileHandle);
$str .= $line;
}
//Finally, close the file handle.
fclose($fileHandle);
$json = json_decode($str, true); // decode the JSON into an associative array
Thanks for your time.
I found the cause. It is path protocol.
With
$filename = 'http://www.yyy/response.json';
It freezes the server for 1 to 2 minutes.
I changed the file to another server with https protocol, and used
$filename = 'https://www.yyy/response.json';
and it works.

Writing to file with fwrite appears successful, but no file appears

All I am attempting to do is append to a file, and then read the file. In this case, I am appending 'hi', so my results look like 'hi', 'hihi', 'hihihi', etc. This works. What is so baffling is that if I then look at my temp dir, I see no file /tmp/bb.txt. How am I able to append to a file I cannot find in my file system? Am I under some sort of fake root or something?
$content is becoming a longer string each time, so it must be saving somewhere. When I step through, $x is true.
public function testFileAction()
{
$file = '/tmp/bb.txt';
$x = file_exists($file);
$mf = fopen($file, 'a');
fwrite($mf, 'hi');
fclose($mf);
$mfr = fopen($file, 'r');
$content = fread($mfr, filesize($file));
fclose($mfr);
echo $content;
}
Code is correct.
How are you running this? File can be owned by user used by server (apache for example).
You (user in the terminal) probably don't have permission to read the file.
Try sudo ls /tmp.
The problem is that '/tmp' might not mean the actual path of '/tmp' to php. Linux can be configured in a way that each process has its own tmp directory that it uses separately from any other process.
https://blog.oddbit.com/post/2012-11-05-fedora-private-tmp/

PHP fopen doesn't find existing file

I'm currently writting a login-system with PHP, for that I need to read the files with some user-information in it.
But after changing the folder system, PHP fopen doesn't read the files anymore.
Both the users.php and userinf.csv files are in the samle folder.
I allready tried to change the filepath, hard-coded the filepath , recreated the file. All of which file.
//Read file
$fp = fopen("userinf.csv", "r");
if(!$fp)
{
echo "File couldn't be read";
return false;
}
Before changing the file system, it worked. But now I am geting the error:
Warning: fopen(userinf.csv): failed to open stream: No such file or directory in FILEPATH on line 45
When you use the fread function without any reference it could fail. I always say that you need to check your path first with getcwd()
<?php
echo getcwd(); //Current Working Directory
?>
Use absolute paths, always. It removes any ambiguity. Using a relative path may change based on where your script is located, among other things, depending on your system.
$fp = fopen("/home/somewhere/blah/userinf.csv", "r");
You can always use a variable for the path as well:
// Somewhere in your code
define('ROOT_PATH', "/home/somewhere/blah");
// In the implementation
$fp = fopen(ROOT_PATH . "/userinf.csv", "r");

PHP fopen() with "wb" not working

Here is a snippet of what I'm trying to do:
$file = fopen($path, "wb");
fwrite($file, $data);
fclose($file);
Simple enough.
But when I open the created file, I see 0x0D inserted before 0x0A everywhere. I understand that this will happen if I open the file without binary mode.
But I've clearly specified I want binary mode. Maybe my brain isn't functioning right or something, so.. Anyone got a solution?
It turns out, for some weird reason, the problem was with my $path. My $path value was "temp".
It would generate the file named "temp" but would refuse to open it in binary mode. Giving the file an extension like "temp.bin" or "temp.tmp" allowed it to work in binary mode.
Problem solved for now but I'm still wondering why it works like this.
Seems the problem is with the $path. Please make sure you have given the correct file path.
If you are defining the $path with a dynamic file name, use / before the file name. For example, $var = "/var/www/html/projectFolder/folderFile/". "Filename.fileformat"
If you're working with URLs in a redirection context, then the root directory ('/') refers to your domain's root. The same goes for paths for linking files or images and for include and require directives.
You're making the classic mistake of confusing data with the representation of that data.
Let's say you have a text file. If you open it in Notepad, you'll see the following:
$str = "Hello world!";
echo bin2hex($str); // output: 48656c6c6f20776f726c6421
$file = fopen($path, "wb");
$data = bin2hex($data);
fwrite($file, $data);
fclose($file);

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

Categories