In the script below, I try to write in the same time in two files, but don't perform. How I can do it ?
$filename1 = "guestbook.doc" ;
$filename2 = "cour.doc" ;
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = stripslashes(nl2br(htmlentities($_POST['message'])));
$d = date ( "d/m/Y H:i:s" )
$handle1 = fopen($filename1, "w+");
$handle2 = fopen($filename2, "a+");
if ($handle1 && $handle2) {
fwrite($handle1, "<b>$name</b> "." - $d<br>$message<br><hr>\n");
fwrite($handle2, "<b>$name</b> ".$email." - $d<br>$message<br>\n");
}
if ($handle1) {
fclose($handle1);
}
if ($handle2) {
fclose($handle2);
}
then
{
header('Location: contact.php?' . http_build_query($_POST));
}
?>
One thing I do notice is that is kinda odd is :
then
{
header('Location: contact.php?' . http_build_query($_POST));
}
then is not a valid control structure. It's if/elseif/else.
writing to a file in PHP is procedural it will wait for handle1 to be written before moving onto handle2. It will not write them at the same time. There must be an error occurring or its not getting inside the if statement if($handle1 && $handle2) . It possibly cannot open those files for writing due to permission problems? are there any errors at all?
Try replacing that if statement with something like this and see if it breaks?
if (is_writable($filename1) or die ("Can not write to ".$filename1)) {
fwrite($handle1, "<b>$name</b> "." - $d<br>$message<br><hr>\n");
}
if (is_writable($filename2) or die ("Can not write to ".$filename2)) {
fwrite($handle2, "<b>$name</b> "." - $d<br>$message<br><hr>\n");
}
Just write one under another it will work perfect.
<?php
$filename = "guestbook.doc" ;
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = stripslashes(nl2br(htmlentities($_POST['message'])));
$d = date ( "d/m/Y H:i:s" )
$handle1 = fopen($filename, "w+");
$size = filesize($filename);
fwrite($handle, "<b>$name</b> "." - $d<br>$message<br><hr>\n");
$text = fread($handle, $size);
fclose($handle);
$filename = "cour.doc" ;
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = stripslashes(nl2br(htmlentities($_POST['message'])));
$d = date ( "d/m/Y H:i:s" )
$handle = fopen($filename1, "w+");
$size = filesize($filename1);
fwrite($handle, "<b>$name</b> ".$email." - $d<br>$message<br>\n");
$text = fread($handle, $size);
fclose($handle);
?>
Related
Hello,
I am making my first PHP using website and I have some things that I am writing to a log.txt. Everytime someone visits my website something gets written like this:
$dateTime = date('Y/m/d G:i:s');
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Date / Time: '."".$dateTime ."\n\n");
fclose($fh);
Now I would like to know, how to set a max file size for my log.txt to stop it from getting too big. For example; it'll auto delete the oldest content "block" of let's say 6 lines long and replace it with the new one after the file has exceeded (for example) 500 lines.
I couldn't find this problem online so I am very curious to how I would do this.
If you have any questions please let me know and I hope you can help me with this problem!
Please try this code. I have tested it it works fine. I use \r\n for line break so that your text file is more readable.
$dateTime = date('Y/m/d G:i:s');
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Date / Time: ' . "" . $dateTime . "\r\n");
fclose($fh);
now you check if the number of lines in the file exceed your limit, then remove the old lines from the top the the file and enter new line on the top, else just enter new line.
$block = 5; //block consist of 5 lines
$remove_blocks = 10; //remove the number of blocks
$remove = $block * $remove_blocks; //totle line to remove
$line_limit = 20;
$content = file_get_contents("log.txt");
$array = explode("\r\n", $content);
$count = count($array);
if ($count >= $line_limit) {
//Remove first few lines
$array = array_slice($array, $remove);
$new_data = implode("\r\n", $array);
$fh = fopen('log.txt', 'w');
fwrite($fh, $new_data . "\r\n");
fclose($fh);
} else {
$dateTime = date('Y/m/d G:i:s');
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Date / Time: ' . "" . $dateTime . "\r\n");
fclose($fh);
}
Edit: put this code in a new test.php adn experiment with it
<?php
$block = 2; //block consist of 5 lines
$remove_blocks = 1; //remove the number of blocks
$remove = $block * $remove_blocks; //totle line to remove
$line_limit = 5;
$content = file_get_contents("log.txt");
$array = explode("\r\n", $content);
$array = array_slice($array, -1);
$count = count($array);
if ($count >= $line_limit) {
//Remove first few lines
$array = array_slice($array, $remove);
$new_data = implode("\r\n", $array);
$fh = fopen('log.txt', 'w');
fwrite($fh, $new_data . "\r\n");
fclose($fh);
$dateTime = date('Y/m/d G:i:s');
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Date / Time: ' . "" . $dateTime . "\r\n");
fclose($fh);
} else {
$dateTime = date('Y/m/d G:i:s');
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Date / Time: ' . "" . $dateTime . "\r\n");
fclose($fh);
}
?>
I suggest using "rotation log files" for this instead. Research on google about this. You will get some easy solutions for it.
For example How to configure logrotate with php logs
Here is an Example how to get Lines Count from File https://www.w3resource.com/php-exercises/php-basic-exercise-16.php
or you can try to get file Size:
if(filesize("log.txt") >= 5000){ echo "file to is large"; }
or
$content = file_get_contents("log.txt");
$array = explode("\n", $content);
$count = count($array);
if($count >= 500){
echo "file too large";
}
You can name the file with the date as a filename
So basically for each day you will have another file
$dateTime = date('Y/m/d G:i:s');
//The file will have the name log_2019-10-09.txt
$fh = fopen('log_'.date('Y-m-d').'.txt', 'a');
fwrite($fh, 'Date/Time: '."".$dateTime ."\n\n");
fclose($fh);
I am trying to add certain variables to couple of files which already have some content.
I am using file_get_contents to copy the contents of a particular file and then using file_put_contents to paste variable values along with the existing contents to that file.
The problem is that, on the first instance it works properly but to the second file it pastes everything that has been stored in the memory. It puts all the contents from the first file along with the contents of the second file.
Is there any way that I can clear the memory before the next file_get_contents executes. Or my concept is false here.
Here is my code...
<?php
if ($_POST["submit"]) {
$ip = $_POST['ip'];
$subnet = $_POST['subnet'];
$gateway = $_POST['gateway'];
$hostname = $_POST['hostname'];
$domain = $_POST['domain'];
$netbios = $_POST['netbios'];
$password = $_POST['password'];
$ipfile = 'one.txt';
$file = fopen($ipfile, "r");
$ipfileContents = fread($file, filesize($ipfile));
$ipcontent = "ip='$ip'\n";
$ipcontent .= "netmask='$subnet'\n";
$ipcontent .= "gw='$gateway'\n";
$conten = $ipcontent . $ipfileContents;
$file = fopen($ipfile, "w");
fwrite($file, $ipfileContents);
fclose($file);
$ipsh = shell_exec('sh path/to/CHANGE_IP.sh');
$hostfile = 'two.txt';
$fileh = fopen($hostfile, "r");
$hostfileContents = fread($fileh, filesize($hostfile));
$hostcontent = "ip='$ip'\n";
$hostcontent .= "m_name='$hostname'\n";
$hostcontent .= "fqdn='$domain'\n";
$conten = $hostcontent . $hostfileContents;
$fileh = fopen($hostfile, "w");
fwrite($fileh, $hostfileContents);
fclose($fileh);
$hostsh = shell_exec('sh path/to/MODIFY_HOSTS.sh');
}
?>
I have tried unset, but didn't work
$ipfilecontents->__destruct();
unset($ipfilecontents);
UPDATE:
file_get_contents & file_put_contents has some concurrency problems. So I had to change my method to fopen/fwrite/fclose and it worked flawlessly. Thanks for your help Jacinto.
if ($_POST["submit"]) {
$ip = $_POST['ip'];
$subnet = $_POST['subnet'];
$gateway = $_POST['gateway'];
$hostname = $_POST['hostname'];
$domain = $_POST['domain'];
$netbios = $_POST['netbios'];
$password = $_POST['password'];
$ipfile = 'one.txt';
$file = fopen($ipfile, "r");
$ipfileContents = fread($file, filesize($ipfile));
$ipcontent = "ip='$ip'\n";
$ipcontent .= "netmask='$subnet'\n";
$ipcontent .= "gw='$gateway'\n";
$content = $ipcontent . $ipfileContents;
$file = fopen($ipfile, "w");
fwrite($file, $content);
fclose($file);
$ipsh = shell_exec('sh path/to/CHANGE_IP.sh');
//do the same to the next file
}
This isn't an answer - I'll delete it in a minute. It's just a convenient place to show how to do trace statements:
$ipfile = 'one.txt';
$ipfileContents = file_get_contents($ipfile);
$ipcontent = "ip='$ip'\n";
$ipcontent .= "netmask='$subnet'\n";
$ipcontent .= "gw='$gateway'\n";
echo "DEBUG: hostcontent=<pre>$ipcontent</pre><br />====<br />hostfileContents=<pre>$ipfileContents</pre><br />\n";
file_put_contents($ipfile, $ipcontent . $ipfileContents, LOCK_EX);
$ipsh = shell_exec('sh path/to/CHANGE_IP.sh');
$hostfile = 'two.txt';
$hostfileContents = file_get_contents($hostfile);
$hostcontent = "ip='$ip'\n";
$hostcontent .= "m_name='$hostname'\n";
$hostcontent .= "fqdn='$domain'\n";
echo "DEBUG: hostcontent=<pre>$hostcontent</pre><br />====<br />hostfileContents=<pre>$hostfileContents</pre><br />\n";
file_put_contents($hostfile, $hostcontent . $hostfileContents, LOCK_EX);
$hostsh = shell_exec('sh path/to/MODIFY_HOSTS.sh');
The most efficient would be to read and write the file in chunks simultaneously:
open the file in read-write mode
read the data chunk that will be overwritten by the new data
reset pointer to begin of read chunk
write new data
make the read data the new data to be written
repeat until there is no data to write
Example:
$bufw = "ip=''\n";
$bufw .= "netmask=''\n";
$bufw .= "gw=''\n";
$bufw_len = strlen($bufw);
$file = fopen($ipfile, 'c+');
while ($bufw_len > 0) {
// read next chunk
$bufr = fread($file, $bufw_len);
$bufr_len = strlen($bufr);
// reset pointer to begin of chunk
fseek($file, -$bufr_len, SEEK_CUR);
// write previous chunk
fwrite($file, $bufw);
// update variables
$bufw = $bufr;
$bufw_len = strlen($bufw);
}
fclose($file);
With this the total memory usage is only up to the length of the new data to be written.
You can make it a function like:
function file_prepend_contents($filename, $data, $flags = 0, $context = null) {
if (!is_null($context)) {
$handle = fopen($filename, 'c+', ($flags & FILE_USE_INCLUDE_PATH) === FILE_USE_INCLUDE_PATH, $context);
} else {
$handle = fopen($filename, 'c+', ($flags & FILE_USE_INCLUDE_PATH) === FILE_USE_INCLUDE_PATH);
}
if (!$handle) return false;
if (($flags & LOCK_EX) === LOCK_EX) {
flock($handle, LOCK_EX);
}
$bytes_written = 0;
$bufw = $data;
$bufw_len = strlen($bufw);
while ($bufw_len > 0) {
// read next chunk
$bufr = fread($handle, $bufw_len);
$bufr_len = strlen($bufr);
// reset pointer
fseek($handle, -$bufr_len, SEEK_CUR);
// write current chunk
if (ftell($handle) === 0) {
$bytes_written = fwrite($handle, $bufw);
} else {
fwrite($handle, $bufw);
}
// update variables
$bufw = $bufr;
$bufw_len = strlen($bufw);
}
fclose($handle);
return $bytes_written;
}
I have created a small application which writes the contents of the $email variable into the file mailadressen.txt. If the file exists, the message "Email address already exists" (E-Mail-Adresse bereits vorhanden) appears. If I change the mail adress and reload the page then it doesn't output nothing. But if I reload it again with the new email address if displays the message "Email address already exists" again.
Can someone give me a tip why it doesn't output anything on the first reload but only on the second reload?
<?php
$email = "Kevin#duck.ente";
// open file and read & write
$handle = fopen ("mailadressen.txt", "a+");
while ( $inhalt = fgets ($handle, 4096 ))
{
$inhalt = trim ( $inhalt );
echo "<li> |". $inhalt ."| </li>";
if ( $inhalt == $email)
{
echo "E-Mail-Adresse bereits vorhanden";
continue;
}
}
fwrite($handle, $email);
// new line
fwrite($handle, "\r\n");
fclose($handle);
?>
Here's one solution based on my comment.
$email = "Kevin#duck.ente";
// open file and read & write
$handle = fopen ("mailadressen.txt", "a+");
while ( $inhalt = fgets ($handle, 4096 )){
$inhalt = trim ( $inhalt );
echo "<li> |". $inhalt ."| </li>";
if ( $inhalt == $email){
$email_exists = true;
$msg = "E-Mail-Adresse bereits vorhanden";
continue;
}
}
//echo the message if email already exists
if(isset($email_exists) && $email_exists === true){
echo $msg;
}
else{
//let's write only non existing email to the file
fwrite($handle, $email);
// new line
fwrite($handle, "\r\n");
echo "Wrote new email: " . $email . " into the mailadressen.txt file.";
}
fclose($handle);
how can i customize the text name for the output on my fopen?
i tried using
$file = $Aname .'.txt';
but it won't output correctly, and also after creating the text file return to the page
and prompt the user regarding the creation of the file .
<?php
$saving = $_REQUEST['saving'];
if ($saving == 1){
$Aname = $_POST['Aname'];
$name = $_POST['name'];
$last = $_POST['last'];
$mob = $_POST['mob'];
$ext = $_POST['ext'];
$email = $_POST['email'];
$add = $_POST['add'];
$com = $_POST['com'];
$day = $_POST['day'];
$text = $_POST['text'];
$date = date("M j, Y ");
$data = "Date Sent: {$date}\n\nName: {$name} {$last}\nPhone : {$mob} ext: {$ext}\nCompany: {$com}\nAddress : {$add}\nE-mail : {$email}\nDay : {$day}\n\nNote :
\n{$text}\n---------------------------------------\n";
$file = $Aname.'.txt';
$fp = fopen($file, "a") or die("Couldn't open $file for writing!");
fwrite($fp, $data) or die("Couldn't write values to file!");
fclose($fp);
}
?>
and also instead of relocating the user to another page to give this error
die("Couldn't write values to file!");
just pop up an alert on the page.
Make sure that $_POST['Aname'] is actually populated (maybe it is coming from $_GET?).
Do note by the way that you have opened a rather big security issue here by using unsanitized data to write to disk. Potentially people could overwrite any file on your disk with PHP code and then execute that.
Try using file_put_contents(). It replaces the whole fopen, fwrite, fclose headache.
http://php.net/manual/en/function.file-put-contents.php
<?php
$saving = $_REQUEST['saving'];
if ($saving == 1){
$Aname = $_POST['Aname'];
$name = $_POST['name'];
$last = $_POST['last'];
$mob = $_POST['mob'];
$ext = $_POST['ext'];
$email = $_POST['email'];
$add = $_POST['add'];
$com = $_POST['com'];
$day = $_POST['day'];
$text = $_POST['text'];
$date = date("M j, Y ");
$data = "Date Sent: {$date}\n\nName: {$name} {$last}\nPhone : {$mob} ext: {$ext}\nCompany: {$com}\nAddress : {$add}\nE-mail : {$email}\nDay : {$day}\n\nNote :
\n{$text}\n---------------------------------------\n";
$file = $Aname.'.txt';
file_put_contents ( $file, $data );
}
?>
You should use an absolute path for the $filename parameter of fopen, so replace your following line:
$file = $Aname.'.txt';
for this one:
$file = dirname($_SERVER["SCRIPT_FILENAME"]) . '/' . $Aname.'.txt';
The above assumes your web server runs linux, if it's a windows one, you have to escape any backslashes, like fopen("c:\\my\\document_root\\myfile.txt", "a");
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);
}
?>