Using php to write to a log file - php

First of I am very very very very bad with php so sorry for this question
I have an application in which i would like to log some debug data
and through my project i make a webrequest to my site storing the information in
$msg i then want to write the data to my logfile.log on the site.
i first used fopen fwrite fclose, but heard that file_put_contents would be better
especially as i very likely will have several users trying to write to the file at once.
Here's the code:
$msg = $_GET['w'];
$logfile= 'logfile.log';
echo file_put_contents($logfile,$msg, FILE_APPEND | LOCK_EX);
But as you might guess the code does nothing for me
i got it working with fopen fwrite fclose
but i wanted to add each user to a new line.
If any smart brain out there would help me I would appreciate it a ton.
Regards.
EDIT:
#Jay
This is how i tried applying it (opening php on the first line)
EDIT: removed 'tag' from code due to a copy/paste error.
error_reporting(E_ALL); ini_set('display_errors', 1)
$msg = $_GET['w'];
$logfile= 'logfile.log';
echo file_put_contents($logfile,$msg, FILE_APPEND | LOCK_EX);

Why not just use error_log()? With the message_type set to 3 (second parameter) the message will be written the the file specified in the third parameter:
$message = $_GET['w'];
$logfile = 'logfile.log';
// Debug: A line for verifying I have the message
echo "Writing message '$message' to logfile<br>";
error_log($message."\n", 3, $logfile);
// Debug: read back the log file to verify thatthe line has been written
readfile($logfile);
Note the newline appended to the message as error_log() doesn't do this for you.
Note also that permissions must be set to allow the web server to write to the target file. This is true whether using error_log() or file_put_contents()
PHP reference is here

Related

I cannot read the data from file it gives me nothing in php?

I am trying to write/read data to a file, when I start the page I remove the file and create a new file:
unlink("t.txt");
$myfile = fopen("t.txt", "w+");
then I write data to file using the following:
file_put_contents('t.txt', $number.PHP_EOL , FILE_APPEND | LOCK_EX);
then I try to read each line of the file as the following:
$lines = file("t.txt");
foreach ($lines as $line_num => $line) {
echo "Line #<b>{$line_num}</b> : " . htmlspecialchars($line) . "<br />\n";
}
There is data in the file but the problem is the I get nothing on my screen, how can I solve this problem?
My guess would be the contents aren't ever written to the file.
The reason I've come to that conclusion: you have opened a file with a write lock on it, then you are trying to write to the same file using a different set of file access functions.
Consistency is key: if you want to use fopen, you should also use fwrite, and the rest of that set of commands (fclose when you are done, fread for reading a stream, etc).
Alternatively, use file_get_contents, file_put_contents, and file (as well as a few others) to avoid using streams. Personally, I prefer these for normal text files, but they can be costly for anything too large. Streams are great when dealing with large files or files that aren't text.
Probable solution to your problem: remove the fopen line.
The other potential cause could be down to access permissions. Might be best to do some further diagnosis if my solution above doesn't work for you.

Save the console text into a txt file? (PHP)

actual I finished writing my program. Because it is only a plugin and it runs on a external server I still want to see if I get some errors or something else in the console.
I wrote every console input with echo ...;. My question now is if it is possible to get the text of the console?
Because then I could easily safe it in a .txt file and could get access to it from the web :) - Or is there another way to get the console text?
I could probably just say fwrite(...) instand of echo ...;. But this will cost a lot of time...
Greetings and Thank You!
An alternative that could be usefull on windows would be to save all the output buffer to a txt, first check your php configuration for the console app implicit_flush must be off then
<?php
ob_start(); //before any echo
/** YOUR CODE HERE **/
$output = ob_get_contents(); //this variable has all the echoes
file_put_contents('c:\whatever.txt',$output);
ob_flush(); //shows the echoes on console
?>
If your goal is to create a text file to access, then you should create a text file directly.
(do this instead of echoing to console)
$output = $consoleData . "\n";
$output .= $moreConsoleData . "\n";
(Once you've completed that, just create the file:)
$file = fopen('output.txt', 'a');
fwrite($file, $output);
fclose($file);
Of course, this is sparse - you should also check that the file exists, create it if necessary, etc.
For console (commando line interface) you can redirect the output of your script:
php yourscript.php > path-of-your-file.txt
If you haven't access to a command line interface or to edit the cronjob line, you can duplicate the starndar output at the begining of the script:
$fdout = fopen('path-to-your-script.txt', 'wb');
eio_dup2($fdout, STDOUT);
eio_event_loop();
fclose($fdout);
(eio is an pecl extension)
If you are running the script using the console (i.e. php yourscript.php), you can easily save the output my modifying your command to:
php yourscript.php > path/to/log.txt
The above command will capture all output by the script and save it to log.txt. Change the paths for your script / log as required.

How to make flock block if other process locked the file?

I have a JavaScript application which posts messages to server. I have to gather those messages on server side and analyse them later, so I'm simply writing them to file. The problem is, when I open the file for reading, ie. in Notepad, messages are not being written. Since flock() is blocking and the locks should be mandatory on Windows, I expected the script to simply wait until I close the file and then save all pending messages, but it doesn't seem to work this way. Is there a way to make sure that all messages will finally be saved to the file, even if other process got exclusive access to it? I can't lose any message, even if someone opens the file for reading or copies it. Can I achieve it with PHP, or maybe I should rather send messages to database instead? PHP version is 7.0.4, my script looks like this:
$f = fopen('log.csv', 'a+');
flock($f, LOCK_EX);
$text = date('Y-m-d H:i:s'). ";" .htmlspecialchars($_POST["message"]). PHP_EOL;
clearstatcache();
fwrite($f, $text);
fflush($f);
flock($f, LOCK_UN);
fclose($f);
?>
flock returns true if successful or false if failed.
while(!flock($f, LOCK_EX)) {
sleep(5);
}
This won't fix the problem of your script timing out if another process has it locked for a long time. In that case, you might want to close the file and try opening a different file name.

php fopen() and fwrite() under heavy ddos attack

In normal condition , everything is ok, an I can write and create new files with fopen() and fwrite() but under "heavy" DDOS attacks , when file pointer is located at 0 , i cant write anything to file.eg. using "w" mod ,result will be a blank file , but by using "a" or "c" mod , if file not exist or be empty, nothing will be written (and just create a blank file too) , but if file has some characters , it will writes after characters or will clear and rewrite new characters respectively.
and when DDOS stopped , everything would be Ok.
here is simple code that I'm using for test, what is the problem? Can I fix it?
I'm using php5 in ubuntu with apache and lighttpd...
<?php
$fp = fopen('data.txt', 'w');
fwrite($fp, '1');
fputs($fp, '23');
fclose($fp);
?>
The way I understood the question is that you have problems running this code when there are multiple requests accessing the .php file (and thus the file you are writing to) at the same time.
Now, while it is far from being foolproof, flock() is there to help with this. The basic concept is that you'd ask for a lock of the file before writing and only write to a file if you're able to get the lock to that file, like
$fp = fopen( $filename,"w"); // open it for WRITING ("w")
if (flock($fp, LOCK_EX | LOCK_NB)) {
// do your file writes here
// when you're done,
// flush your file writes to a file before unlocking
fflush($fp);
// unlock the file
flock($fp, LOCK_UN);
} else {
// flock() returned false, no lock obtained
print "Could not lock $filename!\n";
}
fclose($fp);
You can read some more details from the manual entry or this article.

Email piping with php script

Hi' I want to forward all the emails(which are come to my inbox) to php script and retrieve email content and save it in a file. So do that I was add email forwarder with piping path correctly.
Address to Forward :tickets#ana.stage.centuryware.org
Pipe to a Program : /home/centuryw/public_html/stage/ana/osticket/upload/api/pipe.php
I have used following script as pipe.php
#!/usr/bin/php –q
<?
/* Read the message from STDIN */
$fd = fopen("php://stdin", "r");
$email = ""; // This will be the variable holding the data.
while (!feof($fd)) {
$email .= fread($fd, 1024);
}
fclose($fd);
/* Saves the data into a file */
$fdw = fopen("mail.txt", "w+");
fwrite($fdw, $email);
fclose($fdw);
/* Script End */
But there was no output file and all email are bounced to my inbox again. Can anyone help me please?
Make sure the PHP file has the execute bit set (i.e. chmod +x pipe.php).
I know this question is 2 years old but hopefully this will help anybody who stumbles across it as I did.
I had exactly the same issue and I spent ages trying to log errors etc. I then noticed that my script (and this one) had PHP short tags (i.e. <?) and my PHP config file had these turned off. I changed the tag to <?php and the script worked! Obvious but easy to miss...
try the following 2 options to check:
First, your php file must need to have execute permission(from owner group at least), otherwise it won't work.
What did you used when you were using forwarder? You need to mention php compiler path at the beginnig also.
I have recently written an article regarding the full detail process of piping email content to php program , you will may like to have a look. Let me know if you have any more question. Thanks.
Chanaka -
This doesn't address why there is no output file, but...
Don't you want to use a+ in your fopen() call? The w+ argument will delete any content that already exists in your output file.
PS: Have you tried doing a simple test which writes to the output file using dummy text (not the input from an e-mail) as the contents?
Jeff Cohan
I encountered the same problem. However I solved it by specifying the output file with full path name. Instead of just 'mail.text', i entered '/home/username/public_html/mail.txt'.
If this is actually an email box, why not use IMAP (PHP)? There are lots of classes to read the mail with imap # phpclasses.org

Categories