Log GET parameters to text file? - php

How to log GET request parameters to text file? For example write.php?info=LOG_THIS. I want to append the ip address followed by ": LOG_THIS" on new line in text file. How to do that?

file_put_contents("your_file.txt", $_SERVER["REMOTE_ADDR"].
":" . $_GET["info"], FILE_APPEND | LOCK_EX);
Documentation: http://php.net/manual/en/function.file-put-contents.php

<?php
//get data from file
$content=file_get_contents("info.txt");
//add ip
$content .=$_SERVER["REMOTE_ADDR"];
//add get
$content .= $_GET["info"];
//write to file
file_put_contents("info.txt",$content);
?>
You can find more infos on http://php.net ...

//**********************START generate Log File**************************
<?php
$content=$_GET["info"];
wh_log("Log generate".$content);
function wh_log($msg)
{
$logfile = 'log_' . date('d-M-Y') . '.txt';
file_put_contents($logfile, $msg . "\n", FILE_APPEND);
}
?>
//END generate LOG FILE

Related

PHP: Why file can only be written the first time and subsequent writes fail?

My code:
function log_message($user = "", $message = "") {
$log_file = LOG_PATH;
// if we can open the file
if($handle = fopen($log_file, "a")) {
$timestamp = strftime("%Y-%m-%d:%H %H:%M:%S", time());
$content = $timestamp . " | [{$user}] | " . $message . "\n";
fwrite($handle, $content);
fclose($handle);
} else {
die("error opening log file: {$log_file}");
}
}
Problem:
The first time I can write to the file no problem but any subsequent writes don't get make it through and falls into the else statement?
Other info:
The site is hosted on godaddy and i have set the privacy permissions on the folder to be writable.
What I tried:
I used the function
file_put_contents($log_file, $content . PHP_EOL, FILE_APPEND | LOCK_EX);
but same result.
I also tried the solution mentioned in this question: How to make sure a file handle has been closed before next operation?

file_get_contents doesn't write to a log file

I am trying to write content to a log file using form input data. This doesn't seem to work on a server that's is using php version 5.3.14 but when i put the same code on a server that uses 5.3.27 its working. Does any one have an idea on how to fix this?
Below is my code that i am using for my form action. incoming.log is the file that i am trying to write to and is found in the folder path live/lms on the server. Please not that i am not getting any errors.
<?php
$system_path = '/live/lms/';
$fh = fopen($system_path . "incoming.log", "a");
fwrite($fh, "\nReceived:\n" . date("Y-m-d H:i:s") . "\n" . file_get_contents("php://input"));
fclose($fh);
?>
Not exactly an answer, but advise:
You should add more error handling ...and structure the script in a way so you can add more error handling.
For starters (work in progress):
<?php
$system_path = '/live/lms/';
$fhSource = fopen('php://input', 'rb');
if (!$fhSource) {
trigger_error('fopen input: '. print_r(error_get_last(), true), E_USER_ERROR );
}
$fhTarget = fopen($system_path . "incoming.log", 'a');
if (!$fhTarget) {
trigger_error('fopen output: '. print_r(error_get_last(), true), E_USER_ERROR );
}
$cb = stream_copy_to_stream($fhSource, $fhTarget);
var_dump($cb);
fclose($fhSource);
fclose($fhTarget);

How to display a download link instead of displaying the file itself in php along with another form

I have a form to display which have file attachments at the time of form filling, I succeeded in attaching the file, but at the time of displaying the form it also showing the attached file in some binary/etc form, instead I want it to show just a file name and whenever we click on the file name it has to download the file... Please do help for this
My Code is:
<?php
...
$id = htmlentities($_GET['id'], ENT_QUOTES);
// Get the details of the risk
$risk = get_risk_by_id($id);
$status = htmlentities($risk[0]['status'], ENT_QUOTES);
$subject = $risk[0]['subject'];
//file retrival fields
$filename = $risk[0]['name'];
$mimetype = $risk[0]['type'];
$filedata = $risk[0]['content'];
...
?>
<html>
...
<?php
...
echo "<label>Risk Assessment</label>\n";
echo "<textarea name=\"assessment\" cols=\"50\" rows=\"3\" id=\"assessment\" disabled=\"disabled\">" . htmlentities(stripslashes($assessment), ENT_QUOTES). </textarea>\n";
echo "<label>Additional Notes</label>\n";
echo "<textarea name=\"notes\" cols=\"50\" rows=\"3\" id=\"notes\" disabled=\"disabled\">" . htmlentities(stripslashes($notes), ENT_QUOTES) . "</textarea>\n";
echo "<label>Files attached:\n</label>";
echo $filedata;
...
?>
...
</html>
and the o/p is displaying the file content... :(
you are echoing the $filedata content. you should echoing the $filedata location, not its content.
Here's an example of how to download a pdf file instead of displaying it:
You're Page:
<a href="dl.php?filnam=xyz.pdf>Download the file</a>
dl.php
<?php
$filnam = str_replace(" ", "%20", basename($_GET['filnam']));
header ("content-type: application/pdf");
header ("Content-Disposition: attachment; filename*=UTF-8'en'$filnam");
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($_GET['filnam']));
readfile($_GET['filnam']);
?>
So there are a few steps
Get the name of the file
Get the local path of the file
Respond with a link.
It's been a while since I used PHP but I believe you can get the name of the file with
//basename takes /a/b/c/d.jpg and returns d.jpg
$filename = basename($risk[0]['name']);
$localpath = $risk[0]['tmp_name'];
and then for your output do
echo " . $filename . "" . PHP_EOL
That will create a link with the label of the filename and the url of the local path on the server.
Update: Apparently the file doesn't actually exist yet. If this is the case, then you should write the contents of the file stored in your db. To do this, do
$handle = fopen($filename, "wb");
You can use whatever filename you want. You should add something like the timestamp or user ID or something to make the file unique so it's not overwritten by multiple requests. This will create the file. You can then fill in the file by doing
fwrite($handle, $risk[0]['content']);
finally close the file with
fclose($handle);
to output this new link you can just use the same filename if you like
echo " . $filename . "" . PHP_EOL
If you specified the filename by including some unique value then you can get the original name by using
echo " . $risk[0]['name'] . "" . PHP_EOL
Hope that helped!

PHP lock text file for editing?

I've got a form that writes its input to a textfile.
Would it be possible to lock a text file for editing, and perhaps give a friendly message "the file is edited by another user, please try again later."
I'd like to avoid conflicts if the file has multiple editors at the same time.
Here's how the entry is currently added.
$content = file_get_contents("./file.csv");
$fh = fopen("./file.csv", "w");
fwrite($fh, $date_yy . '-' . $date_mm . '-' . $date_dd . '|' . $address . '|' . $person . '|' . $time_hh . ':' . $time_mm);
fwrite($fh, "\n" . $content);
fclose($fh);
Any thoughts?
You can use flock() function to lock the file. For more see this
Something like:
<?php
$content = file_get_contents("./file.csv");
$fp = fopen("./file.csv", "w"); // open it for WRITING ("w")
if (flock($fp, LOCK_EX))
{
// do your file writes here
fwrite($fh, $date_yy . '-' . $date_mm . '-' . $date_dd . '|' . $address . '|' . $person . '|' . $time_hh . ':' . $time_mm);
fwrite($fh, "\n" . $content);
fclose($fh);
flock($fh, LOCK_UN); // unlock the file
}
?>
In order of desirability:
Use a database.
Use more than one text file.
Use locks:
eg:
$lockwait = 2; // seconds to wait for lock
$waittime = 250000; // microseconds to wait between lock attempts
// 2s / 250000us = 8 attempts.
$myfile = '/path/to/file.txt';
if( $fh = fopen($myfile, 'a') ) {
$waitsum = 0;
// attempt to get exclusive, non-blocking lock
$locked = flock($fh, LOCK_EX | LOCK_NB);
while( !$locked && ($waitsum <= $lockwait) ) {
$waitsum += $waittime/1000000; // microseconds to seconds
usleep($waittime);
$locked = flock($fh, LOCK_EX | LOCK_NB);
}
if( !$locked ) {
echo "Could not lock $myfile for write within $lockwait seconds.";
} else {
// write out your data here
flock($fh, LOCK_UN); // ALWAYS unlock
}
fclose($fh); // ALWAYS close your file handle
} else {
echo "Could not open $myfile";
exit 1;
}
You can use PHP's flock function to lock a file for writing, but that lock won't persist across web requests and doesn't work on NFS mounts (at least in my experience).
Your best be may be to create a token file in the same directory, check for its existence and report an error if it exists.
As with any locking scheme, you're going to have race conditions and locks that remain after the operation has completed, so you'll need a way to mitigate those.
I would recommend creating a hash of the file before editing and storing that value in the lock file. Also send that hash to the client as part of the edit form (so it comes back as data on the commit request). Before writing, compare the passed hash value to the value in the file. If they are the same, commit the data and remove the lock.
If they are different, show an error.
You could try flock — Portable advisory file locking ?
http://php.net/manual/en/function.flock.php
I would just use a simple integer or something like that.
$content = file_get_contents("./file.csv");
$fh = fopen("./file.csv", "w");
$status = 1;
...
if($status == 1){
fwrite($fh, $date_yy . '-' . $date_mm . '-' . $date_dd . '|' . $address . '|' . $person . '|' . $time_hh . ':' . $time_mm);
fwrite($fh, "\n" . $content);
fclose($fh);
$status = 0;
}
else
echo "the file is edited by another user, please try again later.";
Is that what you mean?

php file put contents reverse

Ok sorry if its a stupid question im a begginer.
Im making a small shoutbox just for practise.
It inserts the shout infos in a txt file.
My problem is that, it lists the text from top to bottom, and i would like to do this reversed.
if(isset($_POST['submit'])) {
$text = $_POST['text'];
if(!empty($text)) {
$text = $_POST['text'];
$name = $_POST['name'];
$time = date("H:i");
$content =
"<div class='text'><em>" . $time . "</em>
<span class='c11'><b>" . "<a href='userinfo_php_willbe_here.php' target='_blank'>" . htmlspecialchars($name) . "</a>" . ":</span></b>
" . htmlspecialchars($text) . "
</div>\n";
file_put_contents($file, $content, FILE_APPEND | LOCK_EX);
}
}
here is my code.
i was googleing around with not much luck maybe i wasnt looking hard enough.
could please someone give me a hint?
thank you
No way to do so with one function call. You need to read the content from your target file, prepend the data in php and rewrite the whole file (see file_get_contents).
$fileContent = file_get_contents($file);
$fileContent = $content . $fileContent;
file_put_contents($file, $fileContent, LOCK_EX);
You can also use the array_reverse like so:
// Data in file separated by new-line
$data = explode("\n",file_get_contents("filename.txt"));
foreach(array_reverse($data) as $value) {
echo $value."\n";
}
You can only prepend to a file by means of reading it and writing afterwards.
file_put_contents($file, $content . file_get_contents($file), LOCK_EX);

Categories