Output doesn't show when the page is reloaded - php

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);

Related

PHP fwrite without duplicate

I want to write the code in such a way that, it will write and save any input in a .TXT file. Then there should be functions that will search the whole file (txt) if a text or word has been written or saved before, it should bring error.
If someone has written Love and another person wants to input Love again, it should bring an error message.
here is my code
<?php
$name=$_POST['name'];
$myfile=
fopen("man.txt" , "a+") or
die("Unable to open file!");
fwrite($myfile, "Name:".$name. "\r\n")
?>
Here I have used the in_array function to check an array we have populated ($users) for the submitted name.
If the name is found, is echos "Name Exists". If it is not found it echos "No" and adds the name.
<?php
$name = $_POST['name'];
if (empty($name)) { echo "Please enter your name"; } else $name=$name;
$myfile= fopen("mam.txt" , "a+") or die("Unable to open file!");
$path="mam.txt";
if (file_exists($path)) {
$contents = file_get_contents($path);
$contents = explode("\r\n", $contents);
$users = array();
foreach ($contents as $value) {
$users[] = $value;
}
// Search the file for the submitted name
if (in_array($name, $users)) {
// The name already exists
echo "Name exist";
} else {
// The name doesnt exist
echo "NO";
// Add the new name
fwrite($myfile, $name. "\r\n");
}
}
?>

Reading textfiles from path in a text file [PHP]

I have a textfile ($file) that contains the path to other files. My goal is to read the content of those files and print it in a table. When reading the paths from $file, only the last line path works correctly.
<?php
$file = "log2.txt";
if(file_exists($file)) {
$handler = fopen($file,'r');
while(!feof($handler)) {
$lines = fgets($handler);
$wordarray = explode(' ', $lines);
#echo $wordarray[0]." ".$wordarray[1]." ".$wordarray[2];
if (strpos($lines, 'NOK') !== false) {
echo "<tr><td>".$wordarray[0]."</td></tr>";
if(file_exists($wordarray[2])){
$log = fopen($wordarray[2], 'r');
#echo "FILE EXISTS ".$log;
$logtext = fread($log,filesize($wordarray[2]));
echo "<tr><td>".$logtext."</td></tr>";
fclose($log);
} else {
echo "<tr><td>"."FILE ".$wordarray[2]." FAILED TO LOAD"."</td></tr>";
}
}
}
fclose($handler);
} else {
echo "FILE DOES NOT EXISTS";
}
?>
Here is an exemple of how log2.txt would look like:
POE NOK poelog.txt
LINK-ERRORS OK OK
LATENCIES NOK latencieslog.txt
VOLATILE NOK volatilelog.txt
I think that the problem could be about line endings or so, but cannot get the point.
You're right. The $wordarray[2] contains also new line character so before using it pass it through trim() function and store it in a variable ($filename in my case).
Updated inner if:
if (strpos($lines, 'NOK') !== false) {
echo "<tr><td>".$wordarray[0]."</td></tr>";
$filename = trim($wordarray[2]);
if (file_exists($filename)){
echo "FILE EXISTS ".$filename;
$log = fopen($filename, 'r');
$logtext = fread($log, filesize($filename));
echo "<tr><td>".$logtext."</td></tr>";
fclose($log);
}
else{
echo "<tr><td>"."FILE ".$filename." FAILED TO LOAD"."</td></tr>";
}
}
This short function works like a sharm:
function displayFileContent( $fileName )
{
$arrayWithFileNames = file ( $fileName );
echo "<table>";
foreach ( $arrayWithFileNames as $singleFileName )
{
# remove the trailing \n on Linux - windows has 2 character as EOL
$singleFileName = trim(preg_replace('/\s\s+/', ' ', $singleFileName));
$contentOfFile = file_get_contents( $singleFileName );
echo "<tr><td>{$contentOfFile}</td></tr>";
}
echo "</table>";
}
You use it like this:
displayFileContent ("path-to-your-file");
Remark: There is no check if the file does exist....

generate html file and download it with php

First goal: Create an index.html file and create a link to download the generated file
The issue here is when i click to generate new file the downloaded file is always the same and isnt updated
the variable $content has insite an entire html page with <headers><aside> and <sections>
I have the following code
if( empty( $error )){
echo "<h3>File generated</h3>";
$my_file = 'index.html';
if (file_exists($my_file)) {
if(unlink($my_file)){
};
$new_file = 'index.html';
$handle = fopen($new_file, 'w') or die('Cannot open file: '.$new_file);
$data = $content;
fwrite($handle, $data);
fclose($handle);
echo "<a download='index.html' href='index.html'><b class='download'>Download</b></a>";
} else {
$new_file = 'index.html';
$handle = fopen($new_file, 'w') or die('Cannot open file: '.$new_file);
$data = $content;
fwrite($handle, $data);
fclose($handle);
echo "<a download='index.html' href='index.html'><b class='download'>Download</b></a>";
}
hi i think it's will be work if variable $content will be contain correct data and you have permission to read, update, create file. in code I use file_put_contents function for minimize your code
if( empty( $error )){
echo "<h3>File generated</h3>";
$my_file = 'index.html';
file_put_contents($my_file, $content);
echo "<a download='index.html' href='index.html'><b class='download'>Download</b></a>";
}
UPDATE:
Are you sure that you have correctly generated content and the $content always contains different value?

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);
}
?>

Help writing to two files simultaneously in PHP?

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);
?>

Categories