PHP writing a text file in the begin - php

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

Related

Write and read username and password function in text file using php

i have problems with my login page. Im still new to php and my teacher told me to create a login page using php and you read your username and password from text file.. and if the username is correct then should go to next page and if there are no exists username it will print an output says that no username.
please help..
These are my login.php
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<form action="logg.php" method="POST">
<br /> Name: <input type="text" name="uname"><br /> Password: <input
type="password" name="password" size="15" maxlength="30" /> <br /> <input
type="submit" name="login" value="Post!"> <br />
</form>
</body>
</html>
And these are my login.php
<?php
if (isset($_POST['login'])){
$myFile = "accounts.txt";
$myFileLink = fopen($myFile, 'r');
$myFileContents = fread($myFileLink, filesize($myFile));
fclose($myFileLink);
echo $myFileContents;
?>
the answer only shows all the name but what my teacher asked me to do is that only read the certain names.. and i have no idea what to do.. please help
This should be like this :
I dont know what to do..
You can use regular expression to find the certain string (username = Bob) in your .txt
http://php.net/manual/en/function.preg-match.php
Or you can try to use unserialize
// set data for example
$store = array(
'username' => 'Bob',
'password' => 'YouShouldNotPass'
);
$fp = fopen('pass.txt','w');
fwrite($fp,serialize($store));
// Reading the data
$passtxt = file_get_contents('pass.txt');
$info = unserialize($passtxt);
echo $info['username'];
Or you can try json:
http://php.net/manual/en/function.json-decode.php
I hope it'll give you some intuition that how can you read specific username and match after login form submission.
$myFile = "accounts.txt";
//$string = file_get_contents($myFile); //you've to read it like this
$string = 'Hanna,2302 Lala,ha2302'; // I assume you have this data on file
$username_password = explode(' ',$string);
foreach($username_password as $u_p){
list($username,$password) = explode(',',$u_p); //map it to 2 different variable
// you can add any kind of condition to match specific user after login
echo "username = $username & password = $password <br/>";
}
Edit:
<?php
if (isset($_POST['login'])){
$myFile = "accounts.txt";
//$string = file_get_contents($myFile); //you've to read it like this
$string = 'Hanna,2302 Lala,ha2302'; // I assume you have this data on file
$username_password = explode(' ',$string);
foreach($username_password as $u_p){
list($username,$password) = explode(',',$u_p);//map it to 2 different variable
// you can add any kind of condition to match specific user after login
echo "username = $username & password = $password <br/>";
}
}
?>

Create file PHP file on form submit and frwite to it

Here's my code:
The PHP Code
<?php
if(isset($_POST['Submit'])){
$title ='myPost.php';
echo $title;
//the data
$data = "Hey I am Aidan\n";
//open the file and choose the mode
$fh = fopen($title, "a");
fwrite($fh, $data);
//close the file
fclose($fh);
}
?>
The HTML Form Code
<form action="<?php echo $title; ?>" method="post">
<input type="submit" name="Submit" value="submit">
</form>
When form is submitted I want to load that newly created file on the next page.
use this is php to move to next page . header('Location: /somewhere');
write this code in php tags of which you displayed in html and in place of somewhere you have to write the name of your file.php ... also write this code in first line of your php document inside php tags ob_start();
After you close the file, redirect the user to it:
//close the file
fclose($fh);
// eg: /path/to/page.php. Also try $_SERVER['PHP_SELF']
$currentPath = $_SERVER['SCRIPT_NAME'];
// replace the old filename with $title
$newPath = preg_replace('#(.*/)[^/]*#','$1' . $title, $currentPath);
// Redirect browser to new file and stop.
header("Location: $newPath");
exit;

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.

How can I set the value of a variable passed into a function?

I am working on a page that allows the user to "upload" multiple files at once (they are stored locally in folders relative to their type).
My problem is that when I try to pass $upFile1 and $fileInfo1 to writeResults() to update $fileInfo1 with information about $upFile1, the echoed result is empty.
I did some research and this appears to be a scoping issue, but I'm not sure about the best way to get around this having just started learning PHP last month.
Any help would be greatly appreciated.
foo.html
<!DOCTYPE HTML>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<form method="post" action="foo.php" enctype="multipart/form-data">
<p>
<b>File 1:</b><br>
<input type="file" name="upFile1"><br/>
<br/>
<b>File 2:</b><br>
<input type="file" name="upFile2"><br/>
<br/>
</p>
<p>
<input type="submit" name="submit" value="Upload Files">
</p>
</form>
</body>
</html>
foo.php
<?php
$upFile1 = $_FILES['upFile1'];
$upFile2 = $_FILES['upFile2'];
$fileInfo1 = "";
$fileInfo2 = "";
// Check if directories exist before uploading files to them
if (!file_exists('./files/images')) mkdir('./files/images', 0777, true);
if (!file_exists('./files/text')) mkdir('./files/text', 0777, true);
// Copies the file from the source input to its corresponding folder
function copyTo($source) {
if (($source['type'] == 'image/jpg') || ($source['type'] == 'image/png')) {
#copy($source['tmp_name'], "./files/images/".$source['name']);
}
if ($source['type'] == 'text/plain') {
#copy($source['tmp_name'], "./files/text/".$source['name']);
}
}
// Outputs file data for input file to destination
function writeResults($source, $destination) {
$destination .= "You sent: ";
$destination .= $source['name'];
$destination .= ", a ";
$destination .= $source['size'];
$destination .= "byte file with a mime type of ";
$destination .= $source['type'];
$destination .= ".";
// echoing $destination outputs the correct information, however
// $fileInfo1 and $fileInfo2 aren't affected at all.
}
// Check if both of the file uploads are not empty
if ((!empty($upFile1['name'])) || (!empty($upFile2['name']))) {
// Check if the first file upload is not empty
if (!empty($upFile1['name'])) {
copyTo($upFile1);
writeResults($upFile1, $fileInfo1);
}
// Check if the second file upload is not empty
if (!empty($upFile2['name'])) {
copyTo($upFile2);
writeResults($upFile2, $fileInfo2);
}
} else {
die("No input files specified.");
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>File Upload</title>
</head>
<body>
<p>
<!-- This is empty -->
<?php echo "$fileInfo1"; ?>
</p>
<p>
<!-- This is empty -->
<?php echo "$fileInfo2"; ?>
</p>
</body>
</html>
you are passing the values of $fileInfo1 and $fileInfo2 but they are empty. After that there is no relation between the $destination value and the fileininfo values.
Change your function to return the $destination value.
Change your writeResults command to $fileInfo1 = writeResults($upFile1);
Use the & sign to pass variables by reference
function addOne(&$x) {
$x = $x+1;
}
$a = 1;
addOne($a);
echo $a;//2
function writeResults($source, &$destination) {
$destination .= "You sent: ";
$destination .= $source['name'];
$destination .= ", a ";
$destination .= $source['size'];
$destination .= "byte file with a mime type of ";
$destination .= $source['type'];
$destination .= ".";
// echoing $destination outputs the correct information, however
// $fileInfo1 and $fileInfo2 aren't affected at all.
}
Adding & in front of $destination will pass the variable by reference, instead of by value. So modifications made in the function will apply to the variable passed, instead of a copy inside the function.

how to edit config php file with setting file

i have a little script and i want to give possibility to the user to edit the "config.php" file , with the script in the (setting.php) page .
For Example , they are some of codes in "config.php"
$title = 'myblog';
$email = 'info#google.com';
$desc = 'Something';
i want to have a "HTML" page , to get the value of the things that i said.
(the user enter the value and the value should be used in other parts of script)
if you want something like the user can change the title, if there are more than one user means if one changes config.php the title will be changed for the rest.
so, it's better to use a databases.
if it's only one user, you can use a file to store the information in.
please, explain more what you want to do, one user or more than one ?
You should better do this:
In the settings.php file:
<form action="settings2.php" method="POST">
Title:<input type="test" name="title"><br>
Email:<input type="test" name="email"><br>
Desc:<input type="test" name="desc"><br>
<input type="submit">
And settings2.php:
<?php
$title = $_POST['title'];
$email = $_POST['email'];
$desc = $_POST['desc'];
$content= '<?php
$title = "'.$title.'";
$email = "'.$email.'";
$desc = "'.$desc.'";
?>';
$file = "config.php";
$fh = fopen($file, 'w') or die("can't open file");
fwrite($fh, $content);
fclose($fh);
?>
These 2 pages will put in config.php the values submited by the form, for example:
<?php
$title = "PHP";
$email = "email#email.com";
$desc = "something";
?>

Categories