How to update the array after finish the code? - php

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...

Related

Form search save in file & display result

What is the most elegant and efficient way of search a string against injected script file in PHP.
The flow:
i want make form search when user input strings & click search, data searched save on txt/php file with auto create new file based on month & year ex: -201601.php / txt
then data was saved on safety query with serial key on each string
then if data on -201601.php contents have more than 1000+ query, the data old was deleted automatic
then how showing 50 strings based on random strings on -201601.php
then in -201601.php there are no double string or same string
If you have a solution for my issue and want to post an answer, please add some explanation so that I can understand why/how you did it so that I won't come asking the same questions all over again. Thanks
Im search & create file that i want making it with my plot imagination. Here is what I have so far manually :
<center>
<form action="./cari.php?q=" method="GET">
<input type="text" name="q" value="" placeholder=" Cari .." style="cursor: pointer;width:69%"/>
<input type="submit" value="Search"/>
</form>
</center><?php
if(isset($_GET['q'])) {
$data = ''.$_GET['q']."<br>\n";
$ret = file_put_contents('rcnt.php', htmlspecialchars($data), FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
//echo "$ret bytes written to file";
}
}
//else {die('no post data to process');}
?>
Im stuck searching with cant find related tutorial & hope find answer :(
Please your help, i want learn more with this, i use XAMPP 5.6
First step, the ?q= var the browser will create, you don`t need to set this on your form action.
<form method="get">
<input type="text" name="q" placeholder="search">
</form>
The PHP code will be:
<?php
if(!empty($_GET["q"]))
{
$file = fopen(date("Ym") . ".txt","a+");
fwrite($file, $_GET["q"] . "\r\n"); //\r\n jump the line
flose($file);
}
?>
If today is the 1st search of the 1st day of the month, the file will not exists, then, the PHP will create it, otherwise, will open and write on it.
Hope it could help you.
We could try this way:
<?php
$theFile = date("Ym") . ".txt";
$myFile = file($theFile);
for($i = 0; $i < 100; $i++){ //deleting the first 100 lines
unset($myFile[$i]);
}
//rewriting the file without the 100st first lines
file_put_contents($theFile, implode($myFile));
?>

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

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)

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

PHP best way to output certain data to text?

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.

How to Pass Variables Into PHP Ajax Handler Script?

I have a small ajax php application, which outputs data from a mysql db into a table. The rows are links, which when clicked will call an ajax function, which in turn will call another php file, which displays a different query from the same database in a layer without reloading the page.
I would like to know how to synchronize queries between both php files. So when I click on a row in the base page, the layer will be expanded to include additional information, or indeed the whole query.
I was thinking I could do this by having the primary key in the first query for the table, however I don't want it displayed and was wondering if there was a better approach to this?
with jQuery it's very simple, and I would definitely recommend using it in ajax calls and etc. Let's say you have a table like this;
<table>
<?php
// I'm using mysqli class by the way.
$ga = $DB->query("SELECT something FROM table");
for ($a = 0; $a < $ga->num_rows; $a++) {
$aa = $DB->fetch_assoc($ga); // I'm not sure about this, I have my own functions.
echo "
<tr class="clickable" id="<?=$aa["Id"] ?>">
<td>".$aa["NameOfColumn"]."</td>
</tr>
";
}
?>
</table>
and for the javascript part;
<script type="text/javascript">
$(document).ready(function() {
$(".clickable").on("click", function() {
// Get our row Id from the rows "id" attribute.
$id = $(this).attr("id");
alert($id);
});
</script>
Instead of displaying an alert you have to change what you need to do. For starters I would recommend using a preloaded div, and changing its content while using it like;
<div id="displayData" style="display: none;"> </div>
and for the JS function you can use it like;
$("#displayData").html($id).css("display","block");
The examples are numerous, and you should find what suits you best.
You can do in following way
There should be a hidden textbox in each row of table which will hold the promary key.
when you click the row it will call the javascript function and will pass the id through this like Text.
3.when the user clikc the row it will call the Callfunction in javascript and it will furthur call the ajax and passing the paramanter using GET ot POST method
You don't want it displayed, does that mean for security issues or something else.
If you want to lose the primary key in the table you can go with a query cache placed into a session object and then just retreive by place in array.
so something like:
page1:
create array with db objects
store array into session
display objects in table
add display layer function for eachrow in table using the index from the array as a parameter.
page2:
retrieve session object
show data for array spot
The best and easiest way to handle this would be the following:
USE A FRAMEWORK for your Ajax handling. It will make your life easier and they take care of a lot of stuff that generally you don't need to worry about like how to handle the XMLHttpRequest object across browsers and stuff.
When you load the first table, create a second tr for each tr that displays but make it hidden. You'll populate this second table row with the information from the ajax request.
Modify your ajax function to take the primary key as a parameter. Pass this parameter via either GET or POST to your second php script. You can look here for further clarification on that issue.
Specify the id of the second, hidden tr as the div to update with the response from your ajax request.
Current contents of file:
';
$myFile = "how-to-pass-variables-into-php-ajax-handler-script.php";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
}
?>
<?php
if (isset($_POST['submit'])) {
$myFile = "/posts/edit/644203";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = stripslashes($_POST['sf']);
fwrite($fh, $stringData);
fclose($fh);
('Location: edit.php?a=done');
}
?>
<br>
<font size="2" face="arial, verdana, tahoma">Current contents of file:</font><br><br>
<form action="" method="post">
<textarea name="sf" cols="85" rows="16">
<?php
$myFile = "/posts/edit/644203";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
?></textarea>
<br />
<input type="submit" name="submit" value="Save & Upload" />
</form>
<?php
if ($_GET['a'] == 'done') {
echo 'The file was saved and now it says:<br /><br />';
$myFile = "/posts/edit/644203";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
}
?>

Categories