Ok, so I have a form that takes a username and a code. This is then passed to php for processing. I am not super php saavy, so I want to be able to take a specific portion of the out put and write it to a text file, this form would be used over and over, and I want the text to be appended to the file. As you can see from the output I'm looking to capture, it's basically writing to some code that will be used for usernames in a css. So here is what I have...
The HTML Form
<html><body>
<h4>Codes Form</h4>
<form action="codes.php" method="post">
Username: <input name="Username" type="text" />
Usercode: <input name="Usercode" type="text" />
<input type="submit" value="Post It!" />
</form>
</body></html>
The PHP
--><html><body>
<?php
$Usercode = $_POST['Usercode'];
$Username = $_POST['Username'];
echo "You have recorded the following in our system ". $Username . " " . $Usercode . ".<br />";
echo "Thanks for contributing!";
echo .author[href$="/$Username"]:after {
echo content: "($Usercode)"
echo }
?>
</body></html>
All that I would like to be written to the text file would be this portion..
--> .author[href$="/$Username"]:after {
content: "($Usercode)"
}
Basically, the text file would have line after line of that exact same code, but with different usernames and usercodes. Hopefully, the variable $Usercode and $Username can also be captured and written into the output in the manner that I have it written. I'm just baffled by output buffering in php and clean and flush etc, and fwrite doesn't seem to be able to write without wiping a file clean each time it writes to it. I may be wrong of course. Anyone care to help?
Try this:
<?php
$output = "--> .author[href=$Username]:after { \n"
."content: ($Usercode)\n"
."}";
$fp = fopen($file, 'a');
fwrite($fp, $output);
fwrite($fp, "\n");
fclose($fp);
?>
The flag a will open already a text file and place the pointer to the end of file, so this will not overwrite your already file, more information in fopen.
You can use the function file_put_contents($file, $data, FILE_APPEND); where $file is the path of the file you are writing to, data is the whatever value you are writing to the file. This assumes you are using php5. If not, you will have to create a handle with fopen, write to the file with fwrite and end with fclose to close the file pointed to in your fopen handle.
Related
I'm trying to store data in a .txt file..
The data is already appear on my HTML page but I couldn't know how to post them in a txt file or store them in a session.
In main page:
<?php
echo implode('<br/>', $res->email);
echo json_encode($res->password);
?>'
I want to do something like below:
<?php
$login = "
EMAIL : $_POST['$res->email'];
PASSWORD: $_POST['$res->password']; ";
$path = "login.txt";
$fp = fopen($path, "a");
fwrite($fp,$login);
fclose($fp);
?>
So this $_POST['$res->email']; doesn't work with me I get in the login.txt:
EMAIL : json_encode(Array)
PASSWORD: implode('<br/>', Array)
Neither function calls nor $_POST['$res->email'] would work in string/interpolation context.
While unversed, you should assemble your text data line by line:
$login = " EMAIL : "; # string literal
$login .= implode('<br/>', $res->email); # append function/expression result
$login .= CRLF; # linebreak
$login .= " PASSWORD: "; # string literal
$login .= json_encode($res->password); # append function/expression result
$login .= CRLF; # linebreak
And instead of the oldschool fopen/fwrite, just use file_put_contents with FILE_APPEND flag.
When you use post data you recieve it in your php file. You dont send post data from a php file. With that in mind you manipulate this data with php in the following way:
If is data you recieved from post:
echo $_POST['field'];
This will show the message stored on the field variable among the posted data. But check that the field will be always a string (even though the contents may not be so)
If you want to acces dynamically a field just have in mind that it should be a string for example:
$email = "example#gmail.com";
echo $_POST[$email]
This will NOT return the posted email, but will return the contents from a variable inside Post called "example#gmail.com". Which is the same as :
echo $_POST["example#gmail.com"];
But making now a correct example. if you have this html in your webpage
<form action="/yourphp.php" method="post" target="_blank">
<input type="text" name="email">
<input type="submit" value="Submit">
</form>
you will be able to recover the data from the input field named "email"
echo $_POST['email'];
and this will return the email inside the input.
After you have this clear, you can manipulate the data in different ways to send them to a file, but usually you will have to instantiate a handler, open a file, write content, save and close the file, all depending on your handler.
I have been trying to get the data input from <teaxtarea> and append it in a .txt file in the server everytime someone inputs there. The server-side language is currently PHP. I have been trying for a possible solution online or in the tutorials, but likely end up with unsatisfied result. I am pretty sure it's a really simple thing, but as a total newbie (just started PHP few days ago) I am really lost right now.
Help will be much appreciated.
I have tried so many methods, now a bit lost. Here's something I have tried and failed. -
<?php
$myfile = "input.txt";
$txt = $_POST["text"];
fopen($myfile, "a");
fwrite($myfile, $txt);
fclose($myfile);
?>
<!DOCTYPE html>
<html>
<head></head>
<body>
<form action = "<?php $_PHP_SELF ?>" method = "POST">
<textarea name="text"></textarea>
<input type="submit"></input>
</form>
</body>
</html>
Please refer to the documentation for fopen and fwrite.
fopen will return a file pointer which you will need to pass to any functions like fwrite and fclose. Passing the file name will not work.
Also, using "a" in fopen requires the file to exist. Change it to "a+" to create it if needed and make sure the script has permission to do so.
Finally, if you want new form submissions to go on a new line, you will need to add new line yourself because "a" will put the file pointer to the end of the file only. It will not add newlines for you.
This should work:
<?php
if (isset($_POST["text"])) {
$txt = $_POST["text"];
$fp = fopen("text.txt", "a+");
fwrite($fp, $txt . PHP_EOL);
fclose($fp);
}
?>
<!DOCTYPE html>
<html>
<body>
<form method = "POST">
<textarea name="text"></textarea>
<input type="submit"></input>
</form>
</body>
</html>
As an alternative to the fopen, fwrite, fclose combo, you could also just use
file_put_contents("text.txt", $_POST["text"] . PHP_EOL, FILE_APPEND);
Your form action is wrong.
You could leave it blank, because the target php-code is on the same page, or use
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
And like Gordon said, you have to define a file, e.g.
$filePath = './file/path.txt';
$file = fopen($filePath, 'a');
frwite($file, $message);
fclose($file);
How can I make my $superhero_list array updates after all the code on the superhero.php is done and I want to search for another name?
The problem I find is that after Im done with the superhero.php and go back to superhero.html, it doesnt save the last name on the $superhero_list array.
superhero.html
<html>
<head>
<title>Superhero List</title>
</head>
<body>
<form method="post" action="superhero.php">
<label for="heroname">Check The Super Hero Name:</label>
<input type="text" id="heroname" name="heroname">
</form>
</body>
</html>
superhero.php
<?php
$superhero_list = array();
if (in_array($_POST ["heroname"], $superhero_list)) {
echo 'Your hero was found.<br>';
echo "These are the Super Powers:<br> - Invisibility <br> - Xray Vision <br> - Flight <br> - Underwater Breathing <br> - Immortality <br> - Healing Power <br>
- Mind Reading <br> - Supersmart <br> - Strenght<br>";
} else {
echo "Hero was added to the Super Hero List!";
array_push($superhero_list,$_POST ["heroname"]);
}
echo '<br><br>';
echo 'This your Hero List:<br>';
echo implode("<br>",$superhero_list);
?>
Another thing, there is any better way to write this code? With functions or other loops?
Thanks in advance guys!
If you dont want to store in database then you need to store array value in cookie.
http://php.net/manual/en/features.cookies.php
For cookie you can store value until your browser will not close.
You are resetting the array every time you run the PHP script. You need to save the data so that next time it runs it can pull the data back.
You can either do this by building a database to hold all the names, or you can save them to a file. With something this small saving it to a file is probably the easiest and quickest option.
To save the data to a file change your php script to
<?php
$superhero_list = array();
//Load the list from the file
$filename = 'heroNames.txt';
//First check if the file exists
if (file_exists($filename)) {
//If the file exists load the data
//First open the file for reading using "r"
$myfile = fopen($filename, "r") or die("Unable to open file!");
//Save it into the temp string
$tempString = fgets($myfile);
//turn that string into an array using ":" as the seperator. We will save using ":" later
$superhero_list = explode(":", $tempString);
//ALWAYS CLOSE THE FILE!!!
fclose($myfile);
}
//Now the data is either empty since its the first time used or it has all the names of the old superheros
if (in_array($_POST ["heroname"], $superhero_list)) {
echo 'Your hero was found.<br>';
echo "These are the Super Powers:<br> - Invisibility <br> - Xray Vision <br> - Flight <br> - Underwater Breathing <br> - Immortality <br> - Healing Power <br>
- Mind Reading <br> - Supersmart <br> - Strenght<br>";
} else {
echo "Hero was added to the Super Hero List!";
array_push($superhero_list,$_POST ["heroname"]);
}
//Now to save the data.
//With PHP if you open a file to write and the file does not exist, it will create the file... SO...
//Open the file for writing using "w"
$myfile = fopen($filename, "w");
//Convert the superhero array to a string using ":" to separate them
$tempString = implode(":", $superhero_list);
//Now save that string to the file
fwrite($myfile, $tempString);
//ALWAYS CLOSE THE FILE
fclose($myfile);
echo '<br><br>';
echo 'This your Hero List:<br>';
echo implode("<br>",$superhero_list);
?>
To my understanding you want to:
If the hero exists, echo the information about the hero.
If the hero does not exist, add them to the array.
And you want to be able to keep track of every single hero that is added to the array, even after the user navigates away and back again.
When you navigate away from the php file/page, any data within the variables/file/class is lost. You would have to have some method to store the list of heros (Like a database/some other form of storage).
With a database, you would have fields for the name/each trait. When the user submits the form and sent to the superhero.php file, you would need to query the database for a list of entries/heros. Then you would be able to check if the hero exists or not. If the hero exists, echo that heros fields/data. If the hero does not exist, insert them into the database.
I guess another option would be to save each set of data to a text file. Then you would have to manage reading/writing to the file each time the script is called. However, I wouldn't do it this way...
I have a form element that gets user details and a php script that writes these inputs to a .txt file. What Im having trouble with is following the completion of the php script the url redirects to the http://. . ./the.php and displays a blank page- Im very new to server side scripts but what Im attempting to do is to allow the user to input data and store that data in a text file this text file should me made up of several different inputs collected on multiple days
<?php
if(isset($_POST['aDate'])) {
$aDate = $_POST['aDate'];
$fp = fopen("details.txt", "a");
fputs($fp, "date: $aDate");
fclose($fp);
?>
<form action="txtWrite.php" method="POST" onSubmit="detail()">
<input id="datepicker" name='aDate' type="text" class="time"/>
. . .
I have tested the input values by adding an echo($aDate) in the php script and it checks out, so how do I then redirect back to the html page that allows for more user input to be added to the text file? If you can understand what Im trying to accomplish and have an alternative route, Im all ears. Thanks for taking the time to help me out.
I think you're looking for header('Location:page.php'); which you would use like:
<?php
if(isset($_POST['aDate'])) {
$aDate = $_POST['aDate'];
$fp = fopen("details.txt", "a");
fputs($fp, "date: $aDate");
fclose($fp);
header('Location:page.php');
}
?>
<form action="txtWrite.php" method="POST" onSubmit="detail()">
<input id="datepicker" name='aDate' type="text" class="time"/>
. . .
header("Location: http://www.yousite.com/yourscript.html");
I encountered some problems, I want this script to:
Open test.txt file.
Check if user have added any text to the txt file.
If user have added any text, delete the existing line and replace it with the new. From $_POST.
If user have not, add $_POST in test.txt
Problem:
When I spam the submit button, the .txt will mess up. Anyone know how to make checks, so it does not mess up?
Please don't suggest MYSQL, I need these in .txt file.
Thanks.
function cutline($filename,$line_no=-1) {
$strip_return=FALSE;
$data=file($filename);
$pipe=fopen($filename,'w');
$size=count($data);
if($line_no==-1) $skip=$size-1;
else $skip=$line_no-1;
for($line=0;$line<$size;$line++)
if($line!=$skip)
fputs($pipe,$data[$line]);
else
$strip_return=TRUE;
return $strip_return;
}
if ($userid = 1) {
if(!isset($_POST['submit'])){
?>
<center><form action="" method="POST">
<b>HWID</b>
<input type="text" name="HWID" />
<input type="submit" value="Add HWID" name="submit">
</form>
</center>
<?php
}else{
$userid= 1;
$userid = "user=" . $userid;
$file = "test.txt";
$lines = file($file);
$count = 1;
foreach ($lines as $e) {
if(strpos($e, $userid) !== FALSE){
cutline($file,$count);
++$count;
}
}
$fh = fopen($file, 'a') or die("can't open file");
$stringData = $userid . $_POST['HWID'] . "\n";
fwrite($fh, $stringData);
}
}
}else{
echo "You're not logged in";
}
?>
I am not 100% sure how the text file is messing up, but I guess locking won't help here as locks are released when the script finished (or is reloaded).
It looks like you just "kill" your cutline while in progress and the remaining lines will not be written. One way to fix this could be to save the new content of the file in a temporary variable and call fwrite only once. (I am not 100% sure if this will work)
Another possibility is to write the results of cutline into a temporary file and replace the old file with the new one, when the cutline method is done. This can happen inside the method.
In either ways the existing file will not be touched if the script gets killed in an unsafe state. But you can still loose the new input from the user when he manages to reload the page right after the function call of cutline and before you add the new input in this line
fwrite($fh, $stringData);
I think this is really hard to force as this operation is quite fast.
EDIT:
Don't forget to test the script using multiple users at the same time, if this is a valid use case. If two or more guys are editing the same file at the same time it will mess up as well. So you might end up with some locking but that will not solve the problem described here.