PHP, Line break when writting to a file - php

I am trying to keep a running total of all the responses to a form I have written, but I am having trouble making it so that each response takes a new line. I have my code down below. I just want it so that it is easier to read because right now what happens is that all the responses are jammed together would like to have each one on a new line. I tried a few things and have them commented in the code and what the result was. Thanks in Advance.
<?php
if (isset($_POST['sometext']))
{
$myFile = "testFile.txt";
$thetext=$_POST['sometext'] ;//added + "\n" here but all response turned to 0
writemyfile($myFile,$thetext,"a");
} else
{
$thetext="Enter text here";
}
function readmyfile($thefile)
{
$file = fopen($thefile, "r") or exit("Unable to open file!");
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). "<br />";
}
fclose($file);
}
function writemyfile($thefilename,$data,$mode)
{
$myfile=fopen($thefilename,$mode);
fwrite($myfile, $data); // added + "\n" here and responses turned 0
fclose($myfile);
}
?>
<html>
<head>
<title> Zain's Test Site</title></head>
<body>
<form method="post" action="<?php echo $php_self ?>">
<input type="text" name="sometext" value="<?php echo $thetext ?>" >
<input type="submit" name="Submit" value="Click this button">
</form>
<?php readmyfile("testFile.txt"); ?>
</body>

Can you try appending the newline character (\n) to the $thetext variable like this:
$thetext=$_POST['sometext'] . "\n";
Remember to use '.' as the concatenation operator, and use double-quotes around the newline character.

$thetext."\n"
in php you concatenate strings using ".", you use "+" in javascript.

Use newline "\n" instead of the br's which is for html

$text = $text."\n" ?
Err here's some more text to fill out the answer

fwrite($myfile, $data); // added + "\n" here and responses turned 0
the concat string operator is (.) not (+)
you can also simplify your script thusly
echo nl2br(get_file_contents($file));

Related

PHP: "Submit" box

I am fairly new to PHP and am having trouble with an assignment. The assignment is to create a simple address book in PHP, and i would like my address book to display all addresses that are in it along with a submission box at the bottom to add more addresses. Currently, I can get the addresses to display, but the submission box gives me an error ") Notice: Undefined variable: addres_add in C:\wamp64\www\address_tmp\address.php on line 18"
This is my code thus far, I snagged the submission box code from another answer here on StackOverflow, but I don't know how to modify it to fit my needs.
<?php
//Open address book file and print to user
$fh = fopen("address_book.txt", "r+");
echo file_get_contents("address_book.txt");
//Perfom submit function
if(isset($_POST['Submit']))
fseek($fh, 0, SEEK_END);
fwrite($fh, "$addres_add") or die("Could not write to file");
fclose($fh);
print("Address added successfully. Updated book:<br /><br />");
echo file_get_contents("address_book.txt");
{
$var = $_POST['any_name'];
}
?>
<?php
//HTML for submission box?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="text" name="any_name">
<input type="submit" name="submit">
</form>
<p>
You never assigned the variable from the form input. You need:
$addres_add = $_POST['any_name'];
fwrite($fh, "$addres_add") or die("Could not write to file");
Also, if you're just adding to the file, you should open it in "a" mode, not "r+". Then you don't need to seek to the end, that happens automatically.
You probably should put a newline between each record of the file, so it should be:
fwrite($fh, "$addres_add\n") or die("Could not write to file");
Otherwise, all the addresses will be on the same line.
Here is a simpler version of your program.
<?php
$file_path ="address_book.txt";
// Extract the file contents as a string
$file_contents = file_get_contents($file_path);
if ($file_contents) // Check if the file opened correctly
echo($file_contents . " \n"); // Echo contents (added newline for readability)
else
echo("Error opening file. \n");
// Make sure both form fields are set
if(isset($_POST['submit']) && isset($_POST['any_name']))
{
// Append the new name (used the newline character to make it more readable)
$file_contents .= $_POST["any_name"] ."\n";
// Write the new content string to the file
file_put_contents($file_path, $file_contents);
print("Address added successfully. Updated book:<br /><br />");
echo($file_contents);
}
else
{
echo("Both form elements must be set. \n");
}
?>
//HTML for submission box?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<input type="text" name="any_name">
<input type="submit" name="submit">
</form>
Even with no comments it should be self explanatory. I leave the proper error dealing to you.
To answer your question, the error was being caused because the $address_add variable wasn't previously declared. You also added quotes to it, making it a string.

getting php as text on output

first of all this is my php code. i am trying to get this code as text on output. not sure how i do that. with html we can do \" to insert it inside php but how do i get this done like that on my code ?
<?php
$stringData = "
// Start here
<?php
$width = $_GET['width'];
$heigh = $_GET['height'];
echo 'Hello';
?>
// End here
";
?>
i have marked that part that i want to get it on output as text but when i put it like that on page i get syntax error not sure why.
EDIT #2
here below is my full code and i explain how my code works and for what.
my code is to create page and put something inside that page created
<form method="post">
<label>Page Name:</label><br>
<input type='text' name='filename' placeholder='page name'>
<label>Folders</label>
<select name="thisfolder">
<option value="">Default</option>
<option value="Folder1">Folder1</option>
<option value="Folder2">Folder2</option>
<option value="Folder3">Folder3</option>
</select><br><br>
<label>content</label><br>
<input type='text' name='strin' placeholder='content of created page'>
<input type='submit' value='Add Feed'>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
// the name of the file to create
$filename=$_POST['filename'];
// the name of the file to be in page created
$strin=$_POST['strin'];
// the name of the folder to put $filename in
$thisFolder = $_POST['thisfolder'];
// make sure #thisFolder of actually a folder
if (!is_dir(__DIR__.'/'.$thisFolder)) {
// if not, we need to make a new folder
mkdir(__DIR__.'/'.$thisFolder);
}
// . . . /[folder name]/page[file name].php
$myFile = __DIR__.'/'.$thisFolder. "/page" .$filename.".php";
$fh = fopen($myFile, 'w');
$stringData = "
<?php
$width = $_GET['width'];
$heigh = $_GET['height'];
echo '';
?>
";
fwrite($fh, $stringData);
fclose($fh);
}
?>
what i am trying to do is, passing that php code that is inside $stringData to that page that will be created
You'll want to escape the $'s in your text.
Set $stringData like this:
$stringData = "
// Start here
<?php
\$width = \$_GET['width'];
\$heigh = \$_GET['height'];
echo 'Hello';
?>
// End here
";
using highlight_string internal function
echo highlight_string($stringData);
or using htmlspecialchars
echo htmlspecialchars($stringData);
EDIT , as long as you don't want to print the php code literally to the output [as you've mentioned in your comment]
the problem here is that you are using (double quotes) to store values, which has special meaning in php
the solution is to store your text in single quotes ,
<?php
$stringData = '
// Start here
<?php
$width = $_GET["width"];
$heigh = $_GET["height"];
echo "Hello";
?>
// End here
';
?>
You're using double quotes (") which lets you use $variables inside the string where single quotes (') will not.
like so:
$color = 'red';
$string_one = "My car is $color."
echo $string_one; // My car is red.
$string_two = 'My car is $color.'
echo $string_two; // My car is $color.
So to fix your code you simply need to change the double quotes to single quotes (and escape [put a backslash before] the other single quotes).
Like so:
<?php
$stringData = '
// Start here
<?php
$width = \$_GET[\'width\'];
$heigh = \$_GET[\'height\'];
echo \'Hello\';
?>
// End here
';
?>
In your code I added:
<?php
$stringData = '
// Start here
<?php
$width = $_GET["width"];
$heigh = $_GET["height"];
echo "Hello";
?>
// End here
';
echo $stringData;
?>
When I opened this phap page, I had in browser:
// Start here // End here
In Page Source View I had:
// Start here
<?php
$width = $_GET["width"];
$heigh = $_GET["height"];
echo "Hello";
?>
// End here
There is no error! I see now what you wont.
This code with "(string) $price" working:
<?php
$price = 10;
$stringData = "start here (string) $price end here";
echo $stringData;
echo "(string) $price";
?>
Your code
?>
// End here must be in out put
";
?>
There is not start php delimiter <?php
Correct is:
?>
// End here must be in out put
<?php
";
?>
You missed one more php delimiter, total 2:
<?php
$stringData = "
**?>**
// Start here must be in out put
<?php
$width = $_GET['width'];
$heigh = $_GET['height'];
echo '';
?>
// End here must be in out put
**<?php**
";
?>

How to print "" in php varible in html file

Okay so when I do:
<br>
$line9 = "<button onclick='window.location.href='//home-pc/';'/>GoBack</button>";
$phpfiletxt
"$line1\n$line2\n$line3\n$line4\n$line5\n$line6\n$line7\n$line8\n$line9\n$line10\n$line11\n$line12\n$line13\n$line14\n$line15";<br>
$myfile = fopen("$folder/index.html", "w") or die("Unable to open file!");<br>
fwrite($myfile, $phpfiletxt);<br>
fclose($myfile);<br>
$wordlink = "<a class='list' target='_top' href='$folder'>$word</a>";<br>
$myfile = fopen("wordslist.php", "a") or die("Unable to open file!");<br>
fwrite($myfile, $wordlink);<br>
header("Location: $folder");<br>
where the button is i want to make it work because it doesn't do anything becuase the ' or " arent placed correctly
so i need it so this is a varible that i can print:
onclick='window.location.href='//home-pc/';'/>GoBack</button>";
into an html file. Thanks
In relation to :
How to print "" in php varible in html file
You do as follows:
$string = "The man said\"Hello\" and ran away!";
echo $string;
result: The man said"Hello" and ran away!
It's called escaping. http://php.net/manual/en/language.types.string.php
<button onclick="window.location.href='/home/pc'">GoBack</button>;
Is what you need to replace that with.
Try this
$line9 = "<button onclick=\"window.location.href='//home-pc/';\">GoBack</button>";
I always use ' instead of ", because html has so many " need to be escape like \"...\"
$string = '<a class="text-success" id="success">success></a>'

saving to text file with submit button

I have this code that displays contents of a particular file. I would like to add a submit button that when clicked saves the changes in to a file. Can anyone help me or give some examples that i can use to create this button. i have tried couple of example that i found on the web but could get it to work. is the solution hidden somewhere with $_POST. her is the code.
<?php
$relPath = 'test_file_1.php';
$fileHandle = fopen($relPath, 'r') or die("Failed to open file $relPath go and make me a sandwich! "); ;
while(!feof($fileHandle)){
$line = fgets($fileHandle);
$lineArr = explode('=', $line);
if (count($lineArr) !=2){
continue;
}
$part1 = trim($lineArr[0]);
$part2 = trim($lineArr[1]);
$simbols = array("$", "[", "]", "'", ";");
//echo "<pre>$part1 $part2</pre>";
echo '<form>
<pre><input type="text" name="content_prt1" size="50" value="' .str_replace($simbols, "",$part1).'"> <input type="text" name="content_prt2" size="50" value="' .str_replace($simbols, "",$part2).'"></pre>
<form />';
}
echo '<input type="submit" value="Submit">';
fclose($fileHandle) or die ("Error closing file!");
?>
EDIT
code for the updatefile.php
<?php
if(isset($_REQUEST['submit1'])){
$handle = fopen("test_file_1.php", "a") or die ("Error opening file!");;
$file_contents = $_REQUEST["content_prt1" . "content_prt1"];
fwrite($handle, $file_contents);
fclose($handle);
}
?>
the code stops at error opening file
If you look at the at purely submitting point of view then put the submit button inside the <form> tags
Also, the closing form tags must be form and not from. The updatefile.php I refer to is the file that you post the input box type text to that will update the file of the database field. Remember to close the file before writing to it again. Hope this helps.
<?php
$relPath = 'test_file_1.php';
$fileHandle = fopen($relPath, 'r') or die("Failed to open file $relPath go and make me a sandwich! ");
echo '<form action="updatefile.php" method="POST">';
while(!feof($fileHandle))
{
$line = fgets($fileHandle);
$lineArr = explode('=', $line);
if (count($lineArr) !=2){
continue;
}
$part1 = trim($lineArr[0]);
$part2 = trim($lineArr[1]);
$vowels = array("$", "[", "]", "'", ";");
echo '<pre><input type="text" name="content_prt1" size="50" value="' .str_replace($vowels, "",$part1).'">
<input type="text" name="content_prt2" size="50" value="' .str_replace($vowels, "",$part2).'">
</pre>';
}
echo '<input type="submit" value="Submit">';
echo '<form>';
fclose($fileHandle) or die ("Error closing file!");
?>
You can't submit more than one form with a single submit button. You'll have to echo the <form> tags outside of the loop so that only one form gets created.
The other problem is you have multiple inputs that are named the same, so $_POST will contain only the value of the last input of each name. You probably mean to append [] to the names of the inputs, e.g. name="content_prt1[]". This way, PHP will create an array of those inputs' values in $_POST['content_prt1'].
Finally, note that what you have so far may pose an HTML injection risk (when displaying the page) unless you're certain that the text coming out of the file doesn't contain characters like < and >. To mitigate this, you can use htmlentities when echoing the text into the inputs.

PHP writing a text file in the begin

So we are making in the class a sort of log. There is a input box and a button. Everytime the button is pressed, PHP will write on the text file and prints the current log. Now the text appears on the bottom, and we need to have the text appear on the top. Now how would we do that?
We tried doing this with alot of my classmates but it all resulted in weird behavours. (Like text is printed more then once, etc)
Thanks alot!
EDIT: Sorry, here is the code:
<html lang="en">
<head>
<title>php script</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<form name="orderform" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="text" name="text"/>
<input type="submit" value="Submit" />
<?php
//Basic variables
echo("<br/>");
$myFile = "log.txt";
$logfile = fopen($myFile,'r+');
$theData = fread($logfile,filesize($myFile));
//Cookie stuff so the username is rememberd.
$username = $_COOKIE['gebruikerscookie'];;
if(isset($_POST['username'])){
$gebruiker = $_POST['username'];
if($_COOKIE['gebruikerscookie'] == $gebruiker){
$username = $_COOKIE['gebruikerscookie'];
echo("Welcome back");
}else{
setcookie("gebruikerscookie", $gebruiker);
$username = $_COOKIE['gebruikerscookie'];
echo("Welcome dude!");
}
}
//Checks if theres something inside
if(isset($_POST['text'])){
$message = "<br/>". $username ." : " . $_POST['text'];
fwrite($logfile, $message ,strlen($message));
}
echo($theData);
?>
</form>
</body>
Check the fopen manual on modes: http://www.php.net/manual/en/function.fopen.php
Try 'r+' Open for reading and writing; place the file pointer at the beginning of the file.
Altough without any code this is hard to answer.
<?php
$contentToWrite = "Put your log content here \n";
$contentToWrite .= file_get_contents('filename.log');
file_put_contents('filename.log', $file_data);
?>
This will add the previous content of your file after your cureent content and write on your file.
Please reply if you have any doubt.
you're just missing the
fclose();
I assume, since not closing a filehandle can cause a lot of strange errors like this.
So
$myFile = "log.txt";
$logfile = fopen($myFile,'r+');
........
//Checks if theres something inside
if(isset($_POST['text'])){
$message = "<br/>". $username ." : " . $_POST['text'];
fwrite($logfile, $message ,strlen($message));
}
fclose($logfile); // close it outside the if-condition!
echo($theData);
should do the trick
$log = file('log.txt');
krsort($log);
foreach($log as $line) echo "$line<br>\n";

Categories