(php) fwrite erase and doesn't write - php

I have a file "tw.txt" with the text "test text" in it.
If I try to write "lol" in "tx.txt" with fwrite, the content ("test text") is simply erased and not replaced.
There is no error displayed by the server, however, I can see my Error: can't write in file.
CHMOD is set to 777 in every files and folders, from the "var" rep to the website folder. If I try to read a file with fopen, no problem. I tried to change the chmod with PHP... no success. I tried to append, it erase.
The code works fine on two other servers.
Any clues ? Thanks.
<?php
ini_set('display_errors', 'On');
ini_set('allow_url_fopen', '1');
error_reporting(E_ALL);
$fd=fopen("tw.txt","w") or die("Error: can't open file.");
//chmod("tw.txt", 511);
fwrite($fd,"lol") or die('Error: can't write in file.');
fclose($fd);
?>

Have you tried other opening modes?
If you need to append some data, you should try something like:
$fd=fopen("tw.txt","a+")

$myFile = 'tw.txt';
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, 'lol');
fclose($fh);

Related

PHP fwrite can not write to a txt file

I'm using CentOS7. My index.html, action.php and file.txt are all in the same folder. I have already set chown apache:apache to the entire /var/www/html tree. The file does get open but I am not able to write anything to it. It's my first ever PHP code, so please let me know if I'm being stupid or something. The var_dump($_POST); works fine as well.
<?php
$name = $_POST['fname'];
$fp = fopen("file.txt","w") or die("Can not open file");
fwrite("file.txt",$name) or die ("can not write to file");
fclose($fp);
?>
You have to use the file handle resource in this case $fp, and not the name.
So this:
$name = $_POST['fname'];
$fp = fopen("file.txt","w") or die("Can not open file");
fwrite("file.txt",$name) or die ("can not write to file");
Should be:
//if(!empty($_POST['fname'])){ ..you should really check this
$name = $_POST['fname'];
$fp = fopen("file.txt","w") or die("Can not open file");
fwrite($fp,$name) or die ("can not write to file");
For reference:
http://php.net/manual/en/function.fwrite.php
int fwrite( resource $handle, string $string [, int $length ] )
That said in a case like this, writing a single line.
if(!file_put_contents("file.txt", $name)) die ("can not write to file");
Is a bit easier to use. But in any case these 2 things you don't need to do:
fclose($fp);
?>
The file is closed when PHP is done, and the ending tag can actually cause more issues then it's worth. The only time I use fclose is if I open a file and read from it and then delete it with unlink you can't unlink it if its open, otherwise I just let PHP close it. The ending tag is only needed if you plan to follow the PHP code with something like HTML. Having space (for example) after an ending tag can corrupt file downloads because any content that is output will be included in a download. What's worse is if you included a file that has the space (or other stuff) it can be really hard to find out why you can't open a zip file you sent as a download (for example).
Cheers, and good luck.
you need to pass the file object to the function
<?php
$name = $_POST['fname'];
$fp = fopen("file.txt","w") or die("Can not open file");
fwrite($fp,$name) or die ("can not write to file");
fclose($fp);
?>

PHP - Serverside console output

i'm using PHP as a server backend, to create API, and hence it doesn't console log to browser.
However I'm finding it very hard to debug without using console, and I have to use error_log(json_encode($variable)) all the time to write to error log to see what is being returned/received.
Is there anyway I can 'monitor' the API, and use console.log or similar to write to somewhere, where I can view my output live?
Thanks #Chris, for answering my need. So I'm using the following codes to do a simple print to text file and use tail to see the live output. Works brilliantly.
function mylog($data) {
$myFile = "/home/user/html/log.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
fwrite($fh, json_encode($data, JSON_PRETTY_PRINT));
fclose($fh);
}
My advice would be to write to a log file within your PHP:
$myFile = "log.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
fwrite($fh, "write this to my file\n");
fclose($fh);
If you have command line access then you can run this command to view the contents of the file live:
tail -f log.txt
This will then show anything written to the file immediately.
This might help.
ini_set('display_errors', 1);
as this will show errors when you call an API. You can check the errors by clicking on the API call made.

PHP Write File Error

I have a page called index.php which is calling a function "writelog" in includes/Logger.php
I have file located at includes folder and code is as below.
function writelog($logText){
$myFile = "testlog.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $logText + "\n";
fwrite($fh, $stringData);
fclose($fh);
}
It shows errror "can't open file" . I have set FullPermission for everyone and still it says it cant access file.I tried to put file in same folder as index.php and same error. What can be possible cause ? Am I having wrong path ?
Try using the full path of the log file
$myFile = "/full/path/to/testlog.txt";
I am assuming this file is also in includes, I'm guessing this is called from another script so the path would be one of the calling script. You can use this:
$prevdir = getcwd();
chdir(dirname(__FILE__));
$myFile = "testlog.txt";
chdir($prevdir);
But it's best to use absolute paths

php write file and set permission

I'm trying to create a php file which I can edit straight away without manually set the permissions.
I'm trying this...
<?php
$var = '<?php $mycontent = new Content(); echo $mycontent->block($p_name);?>';
$myFile = "testFile.php";
$fh = fopen($myFile, 'w+') or die("can't open file");
$stringData = $var;
fwrite($fh, $stringData);
fclose($fh);
?>
...it creates the file, but when I try to edit the file in my IDE it won't let me of course. I have to manually set the permission of the file created. Is there any way I can create the file and have the permission already set?
Thanks in advance
Mauro
Yes, you can thanks to PHP CHMOD
// Read and write for owner, read for everybody else
chmod("/somedir/somefile", 0644);
Since this aspect wasn't covered in previous answers I'll add it here:
chmod() will only take a path string as the 1st argument. So you cannot try to pass to resource that was open with fopen(), in this case $fh.
You need to fclose() the resource and then run chmod() with the file path. So a proper practice would be storing the filePath in a variable and using that variable when calling fopen() rather than passing it a direct string in the first argument.
In the case of the example code in the answer this would simply mean running chmod($myfile, 0755) (the permission code is only an example and be different of course.)
full code after corrections:
<?php
$var = '<?php $mycontent = new Content(); echo $mycontent->block($p_name);?>';
$myFile = "testFile.php";
$fh = fopen($myFile, 'w+') or die("can't open file");
$stringData = $var;
fwrite($fh, $stringData);
fclose($fh);
// Here comes the added chmod:
chmod($myFile, 0755);
?>
Php has chmod, works just like the Linux version.

Watching a directory and redirecting to PHP

Greetings,
I'm watching a postfix directory using iwatch.
iwatch /home/vmail/eamorr/photos/new/
When a new email is sent, iwatch outputs a line such as:
[11/Feb/2011 12:23:43] IN_CREATE /home/vmail/eamorr/photos/new//1297427022.Vca01I1e396M000383.eamorr
How do I redirect this to a PHP program for processing?
Here's what I've tried:
iwatch /home/vmail/eamorr/photos/new/ | php /home/hynese/sites/eamorr/emailPhotoHandler/handlePhotos.php
And here's the handlePhotos.php file:
<?php
$data = file_get_contents("php://stdin");
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $data;
fwrite($fh, $stringData);
fclose($fh);
?>
It should create a file "testFile.txt" and put "[11/Feb/2011 12:23:43] IN_CREATE /home/vmail/eamorr/photos/new//1297427022.Vca01I1e396M000383.eamorr" into it... But all I'm getting is nothing - the file isn't even created...
I think it's something to do with the piping and stdin in PHP.
Anyone got any ideas?
Many thanks in advance,
file_get_contents() does not return until the entire file/stream has been read. In this case, that's never. Assuming that iwatch keeps running, iwatch will keep PHP's STDIN open so file_get_contents() never gets to the end.
Try stream_get_line() or fgets() instead. That will give you the iwatch output line-by-line.
Edit: also, the command should be php -f <script>, not php <script>.

Categories