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).
Related
<?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;
This is a php script for a user login system that I am developing.
I need it to read from, and write to, the /students/students.txt file, but it won't even read the content already contained in the file.
<?php
//other code
echo "...";
setcookie("Student", $SID, time()+43200, "/");
fopen("/students/students.txt", "r");
$content = fread("/students/students.txt", filesize("/students/students.txt"));
echo $content;
fclose("/students/students.txt");
fopen("/students/students.txt", "w");
fwrite("/students/students.txt", $content."\n".$SID);
fclose("/students/students.txt");
//other code
?>
You are not using fopen() properly. The function returns a handle that you then use to read or edit the file, for example:
//reading a file
if ($handle = fopen("/students/students.txt", "r"))
{
echo "info obtained:<br>";
while (($buffer = fgets($handle))!==false)
{ echo $buffer;}
fclose($handle);
}
//writing/overwriting a file
if ($handle = fopen("/students/students.txt", "w"))
{
fwrite($handle, "hello/n");
fclose($handle);
}
Let me know if that worked for you.
P.S.: Ty to the commentators for the constructive feedback.
There are many ways to read/write to file as others have demonstrated. I just want to illustrate the mistake in your particular approach.
fread takes a file handle as param, NOT a string that represents the path to the file.
So your line:
$content = fread("/students/students.txt", filesize("/students/students.txt")); is incorrect.
It should be:
$file_handle = fopen("/students/students.txt", "r");
$content = fread($file_handle, filesize("/students/students.txt"));
Same thing when you write contents to file using fwrite. Its reference to the file is a File Handle opened using fopen NOT the filepath. when opening a file using fopen() you can also check if the $file_handle returned is a valid resource or is false. If false, it means the fopen operation was not successful.
So your code:
fopen("/students/students.txt", "w");
fwrite("/students/students.txt", $content."\n".$SID);
fclose("/students/students.txt");
Needs to be re-written as:
$file_handle = fopen("/students/students.txt", "w");
fwrite($file_handle, $content."\n".$SID);
fclose($file_handle);
You can see that fclose operates on file handles as well.
File Handle (as per php.net):
A file system pointer resource that is typically created using fopen().
Here are a couple of diagnostic functions that allow you to validate that a file exists and is readable. If it is a permission issue, it gives you the name of the user that needs permission.
function PrintMessage($text, $success = true)
{
print "$text";
if ($success)
print " [<font color=\"green\">Success</font>]<br />\n";
else
print(" [<font color=\"red\">Failure</font>]<br />\n");
}
function CheckReadable($filename)
{
if (realpath($filename) != "")
$filename = realpath($filename);
if (!file_exists($filename))
{
PrintMessage("'$filename' is missing or inaccessible by '" . get_current_user() . "'", false);
return false;
}
elseif (!is_readable($filename))
{
PrintMessage("'$filename' found but is not readable by '" . get_current_user() . "'", false);
return false;
}
else
PrintMessage("'$filename' found and is readable by '" . get_current_user() . "'", true);
return true;
}
I've re-written your code with (IMO) a cleaner and more efficient code:
<?php
$SID = "SOMETHING MYSTERIOUS";
setcookie("Student", $SID, time()+43200, "/");
$file = "/students/students.txt"; //is the full path correct?
$content = file_get_contents($file); //$content now contains /students/students.txt
$size = filesize($file); //do you still need this ?
echo $content;
file_put_contents($file, "\n".$SID, FILE_APPEND); //do you have write permissions ?
file_get_contents
file_get_contents() is the preferred way to read the contents of a
file into a string. It will use memory mapping techniques if supported
by your OS to enhance performance.
file_put_contents
This function is identical to calling fopen(), fwrite() and
fclose() successively to write data to a file. If filename does not
exist, the file is created. Otherwise, the existing file is
overwritten, unless the FILE_APPEND flag is set.
Notes:
Make sure the full path /students/students.txt is
correct.
Check if you've read/write permissions on /students/students.txt
Learn more about linux file/folder permissions or, if you don't access to the shell, how to change file or directory permissions via ftp
Try to do this:
fopen("students/students.txt", "r");
And check to permissions read the file.
I have a complex php4 code and want to write something to a file, using file_put_contents, like the following:
$iCounter = 0;
foreach blah...
... code
file_put_contents("/tmp/debug28364363264936214", "test" . $iCounter++ . "\n", FILE_APPEND);
...code
I am using FILE_APPEND to append the data to the given file, I am sure that what I print does not contain control characters, the random number sequence makes sure the file is not used in any other context, and the counter variable (only used for the printout) is used to control how often file_put_contents is called.
Executing the code and looking at the file content I just see
test8
while I expect to see
test1
test2
test3
test4
test5
test6
test7
test8
Is there a problem with my syntax? Maybe the code does not work for php4? What else can I use instead?
P.S. I am working on a very large, quite ancient php4 project, so there is no way to recode the project in php5. Not within 2 years...
use fopen(); file_put_contents() is php5.
$file = fopen("/tmp/debug28364363264936214", "a+");
fwrite($file, "test" . $iCounter++ . "\n");
fclose($file);
you can use foreach it there is an array input it will be a similuar procedure
for ($iCounter = 1; $iCounter <= 10; $iCounter++) {
$test_var .= "test" . $iCounter . PHP_EOL;
}
if (file_exists("/tmp/debug28364363264936214")) {
file_put_contents("/tmp/debug28364363264936214", $test_var, FILE_APPEND);
echo "The file was written";
} else {
echo "The file was not written";
}
php4 code
if (file_exists("/tmp/debug28364363264936214")) {
$fp = fopen('/tmp/debug28364363264936214', 'a');
fwrite($fp, $test_var);
fclose($fp);
echo "The file was written";
} else {
echo "The file was not written";
}
your code might be in php4 but it should work in php5 if using php5 which you should be. you just need to recode the errors.
if you want to append data then do as follows
$file = "yourfile.txt";
$data = file_get_contents($file);
$data = $data . $newdata;
file_put_contents($file, $data);
I want to rewrite the code below to generate a string. This string I want to attach to an eamil. It should appear as a csv file.
$fh = fopen($file,'w');
function __outputCSV(&$vals, $key, $filehandler) {
fputcsv($filehandler, $vals, ';', '"');
}
array_walk($aData, '__outputCSV', $fh);
fclose($fh);
Any idea's?
The obvious and lazy approach would be not to rewrite it, but to simply create a temp file and call file_get_contents() on it afterwards.
This, however, would be boring, so I'm going to suggest what is arguably an over complicated approach, but it should work nicely and will be done entirely in memory:
Use this class that is provided in the PHP manual as an example of how to write a custom protocol handler, and the following example code:
function __outputCSV(&$vals, $key, $filehandler) {
fputcsv($filehandler, $vals, ';', '"');
}
stream_wrapper_register("var", "VariableStream");
$myCSVdata = "";
$fh = fopen('var://myCSVdata', 'w');
array_walk($aData, '__outputCSV', $fh);
fclose($fh);
echo $myCSVdata; // Ta Da!
Your best bet is to get a MIME compatible email class that can send emails with attachments. I recall using RMail or PHPMimeMail a while back, you'll have to google it.
Else, you'll need to learn how to build MIME mail yourself. But for all the trouble that it's worth i'll really recommend you to get a class that already does that for you.
EDIT:
I didn't understand your question at first, maybe you should completly reformat and change your title. Here is my suggestion:
$data = '';
foreach($aData as $aDataLine) {
foreach($aDataLine as $aDataKey => $aDataField) {
$aDataLine[$aDataKey] = '"'.str_replace('"', '\\"', $aDataField).'"';
}
$data .= implode(',', $aDataLine)."\n";
}
//$data contains your CSV
I dont think i forgot anything, it SHOULD work out of the box...
I am writing an email module for my web app that sends a html email to a user on completion of a task such as signing up. Now as the formatting of this email may change I've decided to have a template html page that is the email, with custom tags in it that need to be replaced such as %fullname%.
My function has an array in the format of array(%fullname% => 'Joe Bloggs'); with the key as the tag identifier and the value of what needs to replace it.
I've tried the following:
$fp = #fopen('email.html', 'r');
if($fp)
{
while(!feof($fp)){
$line = fgets($fp);
foreach($data as $value){
echo $value;
$repstr = str_replace(key($data), $value, $line);
}
$content .= $repstr;
}
fclose($fp);
}
Is this the best way to do this? as only 1 tag get replaced at the moment... am I on the right path or miles off??
thanks...
I think the problem is in your foreach. This should fix it:
foreach($data as $key => $value){
$repstr = str_replace($key, $value, $line);
}
Alternatively, I think this should be more effective:
$file = #file_get_contents("email.html");
if($file) {
$file = str_replace(array_keys($data), array_values($data), $file);
print $file;
}
//read the entire string
$str=implode("\n",file('somefile.txt'));
$fp=fopen('somefile.txt','w');
//replace something in the file string - this is a VERY simple example
$str=str_replace('Yankees','Cardinals',$str);
//now, TOTALLY rewrite the file
fwrite($fp,$str,strlen($str));
That looks like it should work, but I'd use "file_get_contents()" and do it in one big blast.
A slightly different approach is to use PHP's heredocs combined with string interpolation i.e.:
$email = <<<EOD
<HTML><BODY>
Hi $fullname,
You have just signed up.
</BODY></HTML>
EOD;
This avoids a separate file, and should make things beyond simple substitution easier later.