PHP - Stop while loop after reading every single line from text file - php

I want the Code below to read individual line of text from dataFile.txt and show it in input field.
Problem is After reading first line from text document it shows all remaining lines of text from text file into input field. But on clicking submit it should show second line only then again on submitting it should show third line only, inside input field. please help.
<?php
$file = __DIR__."/dataFile.txt";
$f = fopen($file, "r");
$array1 = array();
<form action="datagGet.php" method="get">
<input type="text" value="
<?php while ( $line = fgets($f, 100) )
{
$nl = mb_strtolower($line);
echo $nl;
if(isset($_GET['done']))
{
$nl++;
}
else
{
break;
}
}
?>"
name="someText">
<input type="submit" name="done" >
</form>

You have several problems with you code. And the first comment above points to many of the. Key is the fact that the $_GET['done'] is set for the form submit and therefore you will echo all the lines of the output. It never breaks.
Also there is the fact that you are opening the file for reading each submit of the form. Although I don't see a simple way around this unless you store the file contents between requests.
One possible option is to use 'file()' to read the entire contents into an array. And then use sessions to store which line has been read. Then on each submit, look for the index of the array from the session read; advance it by one read the file again and return that line. Wow wasteful. But okay for simple site.
so use file to get the lines in an array.
output the first line into the value.
store the next index to be read in the $_SESSION variable like $_SESSION['next_line'] = 1
then upon further submissions. read it all back in. look up the 'next_line', and output that line.
so, for example
$array = file('your file name');
$output = $array[0];
if (isset($_SESSION['next_line']))
$_SESSION['next_line'] = intval($_SESSION['next_line']) + 1;
else
$_SESSION['next_line'] = 1;//prime the pump
echo the form with $output
then rinse and repeat. e.g. read, get output (next_line) with file, set $_session = next_line + 1; render output in form.
ps. some extra notes
* of course you'll need to start session on each request.
* you'll need to check if the $_SESSION['next_line'] is set. if not, set it to 1 (prime it)

Related

PHP Get values from unknown numbers of text input

I have a div in my page called .highlights.
In this div I have a unknown numbers of text input(<input type="text" />). It can range from 0 to unknown.
When someone clicks at submit, I want to store in PHP all the values of the inputs, into one variable called myHighlights. The values must be seperated by ;
<input type="text" name="unlimited[]" />
if( isset($_POST['submit_button']) ) {
// Skip blank values
$unlimited = array_filter( $_POST['unlimited'] );
$myHighlights = implode(';', $unlimited);
}
To begin with, you'll have to assign names to the controls so they get sent together with the rest of of the form. Please have a look at the How do I create arrays in a HTML <form>? entry of the PHP FAQ for a nifty trick.
if($_POST)
{
$myHighlights = implode(';',$_POST);
print_r($myHighlights);
}

How to keep variable constant even after page refresh in PHP

I'm making a simple hangman application and I have my php file and a separate .txt file holding the words, one on each line.
What I want is for the $word variable to remain constant even after the page refreshes since I was planning on using a GET or POST to get the user's input.
In the example code below I want $word to stay the same after the form is submitted.
I believe it's a simple matter of moving code to another place but I can't figure out where any help for this PHP noob would be appreciated!
wordsEn1.txt:
cat
dog
functions.php:
<?php
function choose_word($words) {
return trim($words[array_rand($words)]);
}
?>
hangman.php:
<?php
include('functions.php');
$handle = fopen('wordsEn1.txt', 'r');
$words = array();
while(!feof($handle)) {
$words[] = trim(fgets($handle));
}
$word = choose_word($words);
echo($word);
echo('<form><input type="text" name="guess"></form>');
?>
use sessions:
session_start(); // in top of PHP file
...
$_SESSION["word"] = choose_word($words);
$_SESSION["word"] will be there on refresh
if you care about the "lifetime", follow also this (put it just before session_start)
session_set_cookie_params(3600,"/");
It will hold an hour for the entire domain ("/")
You could use a hidden input:
<form method="POST">
<input type="text" />
<input type="hidden" name="word" value="<?php echo $word; ?>" />
</form>
...and on the next page:
if(isset($_POST['word'])) {
echo $_POST['word'];
}
Or you could use a PHP $_COOKIE, which can be called forever (but kind of a waste if you just want it on the next page):
setcookie('word', $word, time()+3600, '/');
...and on the next page:
echo $_COOKIE['word'];
Just use hidden type forms for that issue.if we put it into session while page refreshes its hide also. if you can store that value in hidden form field it was stored and retrived any time .

Issue Passing JS variable to PHP include file

I have a php file where I am using it to setup dynamically generated pages based on the input variables. It starts on and index.html page where the variables are gathered some of which are not simple strings but complex Google Earth objects. On the submit of that page it is posted to another page and you are redirected to the created file. The trouble is coming when I try to use that variable within the php include file that is used to generate the pages.How do i properly get a variable from this form and then pass it through to be able to use it on the new generated page. Here is what I am trying currently.
On the click of this button the variable flyto1view is set.
$("#flyto1").click(function(){
if (!flyto1view){
flyto1view = ge.getView().copyAsLookAt(ge.ALTITUDE_RELATIVE_TO_GROUND);
$("#flyto1view1").val(flyto1view)
}
else {
ge.getView().setAbstractView(flyto1view);
}
});
Then from here I have tried setting the value to an hidden field but Im not sure if that kinda of variable has a value that can be set like that. Whats the best way to get this variable to here after post
<?
if (isset($_POST['submit']) && $_POST['submit']=="Submit" && !empty($_POST['address'])) {//if submit button clicked and name field is not empty
$flyto1view1 = $_POST['flyto1'];
$address = $_POST['address']; //the entered name
$l = $address{0}; // the first letter of the name
// Create the subdirectory:
// this creates the subdirectory, $l, if it does not already exists
// Note: this subdirectory is created in current directory that this php file is in.
if(!file_exists($l))
{
mkdir($l);
}
// End create directory
// Create the file:
$fileName = dirname(__FILE__)."/$address.html"; // names the file $name
$fh = fopen($fileName, 'w') or die("can't open file");
// The html code:
// this will outpout: My name is (address) !
$str = "
<? php include ('template.php') ?>
";
fwrite($fh, $str);
fclose($fh);
// End create file
echo "Congradualations!<br />
The file has been created.
Go to it by clicking here.";
die();
}
// The form:
?>
Firstly. creating files from user input is pretty risky. Maybe this is only an abstract of your code but doing a mkdir from the first letter of the input without checking that the first letter is actually a letter and not a dot, slash, or other character isn't good practice.
Anyway, on to your question. I would probably use $_GET variables to pass to the second file. So in the second file you use <?php $_GET['foo'] ?> and on the first file you do:
echo "Congradualations!<br />
The file has been created.
Go to it by clicking here.";
You could also echo the variable into your template like so:
$str = '
<?php
$var = \'' . $flyto1view1 . '\';
include (\'template.php\')
?>';

Using For loop to get values of multiple elements in PHP

The title is so general mainly because I don't know what should be the appropriate title for it. Let me just explain the situation:
Say that I have two textboxes named LastName0 and FirstName0 and a button called addMore. When I click addMore, another two textboxes will be created through JavaScript. These textboxes will be named LastName1 and FirstName1. When I click the addMore button again, another two textboxes button will be created and named LastName2 and FirstName2 respectively. This will go on as long as the addMore button is clicked. Also, a button named deleteThis will be created alongside the textboxes. This simply deletes the created textboxes when clicked.
I also initialized a variable called counter. Every time the addMore button is clicked, the counter goes up by 1, and whenever the deleteThis button is clicked, the counter decreases by 1. The value of the counter is stored in a hidden input type.
When the user submits the form, I get the value of the counter and create a For loop to get all the values of the textboxes in the form. Here is the sample code:
//Suppose that the user decides to add 2 more textboxes. Now we have the following:
// LastName0 FirstName0
// LastName1 FirstName1
// LastName2 FirstName2
$ctr = $_POST['counter']; //the counter == 3
for ($x = 0; $x < $ctr; $ctr++)
{
$lastname = $_POST["LastName$x"];
$firstname = $_POST["FirstName$x"];
//This will get the values of LastName0,1,2 and FirstName0,1,2
//code to save to database…
}
On the code above, if the value of counter is equal to 3, then the values of textboxes LastName0,1,2 and FirstName0,1,2 will be saved. Now here is the problem: If the user decided to delete LastName1 and FirstName1, the For loop will not be able to iterate properly:
$ctr = $_POST['counter']; //the counter == 2
for ($x = 0; $x < $ctr; $ctr++)
{
//Only LastName0 and FirstName0 will be saved.
$lastname = $_POST["LastName$x"];
$firstname = $_POST["FirstName$x"];
//code to save to database…
}
Someone told me to use the "push and pop" concept to solve this problem, but I am not really sure on how to apply it here. So if anyone can tell me how to apply it, it'll be grand.
Add your input text boxes with name as array ie, <input type="text" name="FirstName[]" />
In php you can fetch them as a array. ie,
foreach($_POST["FirstName"] as $k=>$val){
echo $val; // give you first name
echo $_POST["LastName"][$k]; // will give you last ame
}
In this case even if one set of field is removed in HTML will not affect the php code.
One solution would be to use the isset function like this:
$ctr = $_POST['counter'];
for ($x = 0; $x < $ctr; $ctr++)
{
isset($_POST["LastName$x"])?$lastname = $_POST["LastName$x"]:;
isset($_POST["FirstName$x"])?$firstname = $_POST["FirstName$x"]:;
}
If it is possible, instead of using LastNameN and FirstNameN names try using LastName[N] and FirstName[N], this way the result is an array and you can iterate through it with a foreach, meaning you will not need the counter and the index of the value will not be important:
foreach ($_POST["LastName"] as $i=>$lastname) {
if (!isset($_POST["FirstName"][$i])) {
// This should only happen if someone messes with the client side before posting
throw new Exception("Last name input does not have a related First name input");
}
$firstname = $_POST["FirstName"][$i];
}
If not, then you may have to use your $counter in a different way
$current = 0;
while ($counter) { // Stop only when i found all
if (isset($_POST["LastName$current"]) {
$counter--; // Found one
$lastname = $_POST["LastName$current"];
$firstname = $_POST["FirstName$current"];
}
$current++;
}
A better way to solve this would be to use arrays for Firstname and Lastname. Instead of calling them Lastname0 and Firstname0, then Lastname1 and Firstname1, call them all Lastname[] and Firstname[]. Give them ID's of Lastname0 and Firstname0 and so on for the delete function, but keep the names as arrays.
When the form is submitted use the following:
foreach($_POST['Lastname'] as $i => $lastname) {
$firstname = $_POST['Firstname'][$i]
//... code to save into the database here
}
Be warned though that in IE if you have an empty field it will not be submitted, so if Lastname0 has a value, but Firstname0 does not, then $_POST['Firstname'][0] will in fact contain the value of Firstname1 (assuming it has a value in it). To get around this you can use javascript to check if a field is empty when submitting the form, and if so put the word EMPTY in it.
Do not use counter if not required
A much easier way is to add array name when admore clicked.
Give a name like first_name[] in textbox
if you create form like that you can use foreach through $_POST['first_name']
try var_dump($_POST) in you php code to see how things goes on.
Inside your for loop, maybe you could try...
if ((isset($_POST["LastName$x"])) && (isset($_POST["FirstName$x"]))){
$lastname = $_POST["LastName$x"];
$firstname = $_POST["FirstName$x"];
//code to save to database…
}
This will check if the variables exists before you try to do anything with them.

cannot put new string into array

I have a form when the user types something in, it will appear on the screen. I kept the text that the user typed in a variable called $output, then I tried to put each $output into an array called $arrayText, my objective is to have the user type in something and click a button, then the user's text appears on the screen and when he tries for the second time, the first text is still there while the new one will be on the next line. However, it works only for the first time. For the second time, it replaces the second text with the old one, here is my code
if (isset($_POST['putContents'])) {
$output = $_POST['contents'];
test();
}
function test()
{
static $arrayText = array();
global $output;
$arrayText[]= $output;
for($i = 0; $i < count($arrayText); $i++){
echo $arrayText[$i];
echo "<br>";
}
}
}
?>
thanks for any help in advance
You can't "collect" the user input line-by-line into an array after each time he presses the submit button. The lines must be persisted (stored) somewhere. You can store each line as a record in a database or in a session cookie as suggested. I would persist the state by storing the entered lines in hidden input tags inside your form:
<input type="hidden" name="line[0]" value="What the user typed in first" />
<input type="hidden" name="line[1]" value="The second line that was typed in" />
<input type="text" name="contents" value="" />
By executing a second time your script your $_POST will only have the values of your last submit which in your case will override your array.
If you want to store data beyond the current process you'll have to store the date somewhere other then the $_POST global.
I'm suggesting you use sessions for this as a database query would certainly over blow your needs.
Use:
session_name("admin");
session_start();
if(empty($_SESSION["yourOldText"])) $_SESSION["yourOldText"]=$_POST["userinput"];
and if you want to access your old data then you can just use $_SESSION["yourOldText"]

Categories