PHP Read default values from file - php

I'm having an issue with the way my script works. What is supposed to happen is: when the form loads, it reads the last-used data from a .json file and populates the fields. It works, but when new data is submitted it populates the form with old data and not the new data.
The first part reads the JSON file and builds the form
<?php $old = json_decode((file_get_contents(dirname(__FILE__)."/json.json")), true); ?>
<!--Building the form-->
<table>
<form action="edit.php" method="POST">
<label for="time">Time:</label>
<input type="text" name="time" id="time" value="<?php echo ($old['time']); ?>"></input>
<br />
<label for="event">Event:</label>
<input type="text" name="event" id="event" value="<?php echo ($old['event']); ?>"></input>
<br />
<label for="event">Notes:</label>
<input type="textarea" name="notes" id="notes" value="<?php echo ($old['notes']); ?>"></input>
<br />
<input type="submit" name="task" value="Go" />
<input type="submit" name="task" value="Clear" />
</form>
This next section decides what to do if the clear button is pressed
<?php if ($_POST['task'] == 'Clear'){
$time = '';
$event = '';
$notes = '';
$remainingtime = '';
$task = 'clear';}
else {
?>
This final section populates the new array and saves it as the JSON file.
<?php if ($old['time'] != $_POST['time']){
$time = preg_replace("/[^0-9]/","",$_POST['time']);
$remainingtime = ((microtime())+($timein*60)*1000);
$task = 'countdown';}
else {
$remainingtime = $old['time'];
}
$event = $_POST['event'];
$notes = $_POST['notes'];
$remainingtime = '';
$task = 'display';
}
$new = array ('time' => $time, 'event' => $event,'notes' => $notes , 'remainingtime' => $remainingtime , 'task' => $task);
file_put_contents((dirname(__FILE__).'/json.json'), json_encode($new));
}
?>
When the clear button is pressed repeatedly, the form is cleared and the JSON file is cleared.
When the Go button is pressed the form and JSON file alternate between the new form submission and what is in the JSON file.
Any help would be appreciated.
NB Time comparison doesn't work in my current code

You say "this final section" does the saving. If you load the data at the top of the page and save it at the bottom, after you've generated the form, it will always be the old data that displays because that's what you loaded. You don't update the file until after you've loaded the old data and displayed it.
To fix this, change your code from this basic structure:
load data
display form using old data
decide what to do if the clear button is pressed
populate the new array
save the new array as the json file
to this:
decide what to do if the clear button is pressed
if there's new data:
populate the new array
save the new array as the JSON file
otherwise, load the old data
display form using the data (whether it's new or old
By the way, your comparison to $post['time'] doesn't make sense. The code you shared doesn't define $post (which is not the same as the superglobal $_POST, but is confusing).

Your problem is that the $_POST data is still present. If you resubmit the form, the old data will be inserted once more. What you will need to do is redirect the page after writing your form data to your json file.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
switch ($_POST['action']) {
case 'Clear':
// Do clear stuff
break;
case 'Go':
default:
// Do go stuff
break;
}
// Redirect
header("Location: ".$_SERVER['REQUEST_URI']);
exit;
}

Related

i want to be able to echo all the element in an array?

I pretty newbie to php and javascript but more i am curious about PHP. I want to add elements into a empty array every time i add a new element trough a input form, and after that i want those elements to be displayed in to the browser .The code i use is this
<form action="index.php" method="POST">
<input type="text" name="name" placeholder="name"><br><br>
<input type="submit" name="submit" value="enter"><br><br>
</form>
<?php
if (isset($_POST['submit'])) {
$_SESSION['names']=array();
$names=$_SESSION['names'];
$name=$_POST['name'];
array_push($names,$name);
for($i=0;$i<count($names);$i++){
echo $names[$i];
}
};
How could i achieve to display every element inside the array that i add trough the input field in php?
You overwrite the value every time because you wipe out the array on every page load: $_SESSION['names']=array();. Instead check to see if that session variable exists (and is an array) first and, if it doesn't, then create it. Otherwise just append to that array.
<form action="index.php" method="POST">
<input type="text" name="name" placeholder="name"><br><br>
<input type="submit" name="submit" value="enter"><br><br>
</form>
<?php
session_start();
if (isset($_POST['submit'])) {
if (!isset($_SESSION['names']) || !is_array($_SESSION['names'])) {
$_SESSION['names'] = array();
}
$name = $_POST['name'];
$_SESSION['names'][] = $name;
$num_names = count($_SESSION['names']);
for($i=0;$i<$num_names;$i++){
echo $_SESSION['names'][$i];
}
};

Saving form values with php and calling cookie using SESSION

I am making a form in html. When a person clicks on submit, it checks if certain fields are filled correctly, so pretty simple form so far.
However, i want to save the text which is typed into the fields, if a person refreshes the page. So if the page is refreshed, the text is still in the fields.
I am trying to achieve this using php and a cookie.
// Cookie
$saved_info = array();
$saved_infos = isset($_COOKIE['offer_saved_info']) ? explode('][',
$_COOKIE['offer_saved_info']) : array();
foreach($saved_infos as $info)
{
$info_ = trim($info, '[]');
$parts = explode('|', $info_);
$saved_info[$parts[0]] = $parts[1];
}
if(isset($_SESSION['webhipster_ask']['headline']))
$saved_info['headline'] = $_SESSION['webhipster_ask']['headline'];
// End Cookie
and now for the form input field:
<div id="headlineinput"><input type="text" id="headline"
value="<?php echo isset($_SESSION['webhipster_ask']['headline']) ?
$_SESSION['webhipster_ask'] ['headline'] : ''; ?>"
tabindex="1" size="20" name="headline" /></div>
I am new at using SESSION within php, so my quesiton is:
Is there a simpler way of achieving this without using a cookie like above?
Or what have i done wrong in the above mentioned code?
First thing is I'm pretty sure you're echo should have round brackets around it like:
echo (isset($_SESSION['webhipster_ask']['headline']) ? value : value)
That's not really the only question your asking though I think.
If you're submitting the data via a form, why not validate using the form values, and use the form values in your html input value. I would only store them to my session once I had validated the data and moved on.
For example:
<?php
session_start();
$errors=array();
if($_POST['doSubmit']=='yes')
{
//validate all $_POST values
if(!empty($_POST['headline']))
{
$errors[]="Your headline is empty";
}
if(!empty($_POST['something_else']))
{
$errors[]="Your other field is empty";
}
if(empty($errors))
{
//everything is validated
$_SESSION['form_values']=$_POST; //put your entire validated post array into a session, you could do this another way, just for simplicity sake here
header("Location: wherever.php");
}
}
if(!empty($errors))
{
foreach($errors as $val)
{
echo "<div style='color: red;'>".$val."</div>";
}
}
?>
<!-- This form submits to its own page //-->
<form name="whatever" id="whatever" method="post">
<input type="hidden" name="doSubmit" id="doSubmit" value="yes" />
<div id="headlineinput">
<input type="text" id="headline" value="<?php echo $_POST['headline'];?>" tabindex="1" size="20" name="headline" />
<!-- the line above does not need an isset, because if it is not set, it will simply not have anything in it //-->
</div>
<input type="submit" value="submit" />
</form>

when working with php sessions form input data not getting save

Hey i have having a problem i just found working with session i am using at the moment firefox 23 but i have check that on some other browsers as well.
I have created a simple code where i have created a form and just opened a session and i have noticed that once i have submit the form and then click on "Go Back" to return to the page the info i have inserted is not saved on the browser.
Normally when you submit a form once you go back the data you have entered is saved and you can just edit the inputs and resent it but when i have used session_start() on the page that function stopped working.
Well i am guessing maybe the browser save the form data in sessions as well and once i use it in php it's somehow effect the normally way the browser work.
I hope someone know how i can fix that i know you are able to save sessions with html5 and javascript now but i would rather do that with php.
Attached below is the code i have been using:
<?php
session_start();
// store session data
$_SESSION['name']= "name";
?>
<form method="post" action="index.php">
<input type="text" name="email" placeholder="Email" /><br />
<input type="text" name="name" placeholder="Name" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
The browser refilling the form is simply that, the browser. This is not something you should rely upon for form re-population.
Your PHP code does not attempt to refill the form by printing anything within the input value="" attributes.
Generally when a form is submitted a programmer will validate the submitted values, store them in some fashion (the session is fine) and if they need them to reappear on the form they will print those values back out like I described.
I think you want to put the CORRECT fields back into the form values and blank out the incorrect ones. You don't have to use sessions:
<?php // formx.php
// accept POST variables
$fld1 = isset($_POST['fld1']) ? $_POST['fld1'] : "";
$fld2 = isset($_POST['fld2']) ? $_POST['fld2'] : "";
// edit variables
$errmsg = "";
if (!$fld1 == "") { if($fld1 <> "1") { $errmsg .= "fld1 is not 1<br />\n"; $fld1 = ""; } }
if (!$fld2 == "") { if($fld2 <> "2") { $errmsg .= "fld2 is not 2<br />\n"; $fld2 = ""; } }
if ($errmsg == "") { $errmsg = "Values accepted"; }
// output form
$body = <<<EOD
<html>
<body>
<div>%s</div><!-- errmsg -->
<form name="formnm" action="formx.php" method="post">
Enter "1" <input type="text" name="fld1" value="%s" /><br />
Enter "2" <input type="text" name="fld2" value="%s" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
EOD;
printf($body, $errmsg, $fld1, $fld2);
?>

How to get input field value using PHP

I have a input field as follows:
<input type="text" name="subject" id="subject" value="Car Loan">
I would like to get the input fields value Car Loan and assign it to a session. How do I do this using PHP or jQuery?
Use PHP's $_POST or $_GET superglobals to retrieve the value of the input tag via the name of the HTML tag.
For Example, change the method in your form and then echo out the value by the name of the input:
Using $_GET method:
<form name="form" action="" method="get">
<input type="text" name="subject" id="subject" value="Car Loan">
</form>
To show the value:
<?php echo $_GET['subject']; ?>
Using $_POST method:
<form name="form" action="" method="post">
<input type="text" name="subject" id="subject" value="Car Loan">
</form>
To show the value:
<?php echo $_POST['subject']; ?>
Example of using PHP to get a value from a form:
Put this in foobar.php:
<html>
<body>
<form action="foobar_submit.php" method="post">
<input name="my_html_input_tag" value="PILLS HERE"/>
<input type="submit" name="my_form_submit_button"
value="Click here for penguins"/>
</form>
</body>
</html>
Read the above code so you understand what it is doing:
"foobar.php is an HTML document containing an HTML form. When the user presses the submit button inside the form, the form's action property is run: foobar_submit.php. The form will be submitted as a POST request. Inside the form is an input tag with the name "my_html_input_tag". It's default value is "PILLS HERE". That causes a text box to appear with text: 'PILLS HERE' on the browser. To the right is a submit button, when you click it, the browser url changes to foobar_submit.php and the below code is run.
Put this code in foobar_submit.php in the same directory as foobar.php:
<?php
echo $_POST['my_html_input_tag'];
echo "<br><br>";
print_r($_POST);
?>
Read the above code so you know what its doing:
The HTML form from above populated the $_POST superglobal with key/value pairs representing the html elements inside the form. The echo prints out the value by key: 'my_html_input_tag'. If the key is found, which it is, its value is returned: "PILLS HERE".
Then print_r prints out all the keys and values from $_POST so you can peek as to what else is in there.
The value of the input tag with name=my_html_input_tag was put into the $_POST and you retrieved it inside another PHP file.
You can get the value $value as :
$value = $_POST['subject'];
or:
$value = $_GET['subject']; ,depending upon the form method used.
session_start();
$_SESSION['subject'] = $value;
the value is assigned to session variable subject.
For global use, you may use:
$val = $_REQUEST['subject'];
and to add yo your session, simply
session_start();
$_SESSION['subject'] = $val;
And you dont need jQuery in this case.
function get_input_tags($html)
{
$post_data = array();
// a new dom object
$dom = new DomDocument;
//load the html into the object
$dom->loadHTML($html);
//discard white space
$dom->preserveWhiteSpace = false;
//all input tags as a list
$input_tags = $dom->getElementsByTagName('input');
//get all rows from the table
for ($i = 0; $i < $input_tags->length; $i++)
{
if( is_object($input_tags->item($i)) )
{
$name = $value = '';
$name_o = $input_tags->item($i)->attributes->getNamedItem('name');
if(is_object($name_o))
{
$name = $name_o->value;
$value_o = $input_tags->item($i)->attributes->getNamedItem('value');
if(is_object($value_o))
{
$value = $input_tags->item($i)->attributes->getNamedItem('value')->value;
}
$post_data[$name] = $value;
}
}
}
return $post_data;
}
error_reporting(~E_WARNING);
$html = file_get_contents("https://accounts.google.com/ServiceLoginAuth");
print_r(get_input_tags($html));
If its a get request use, $_GET['subject'] or if its a post request use, $_POST['subject']
<form action="" method="post">
<input type="text" name="subject" id="subject" value="Car Loan">
<button type="submit" name="ok">OK</button>
</form>
<?php
if(isset($_POST['ok'])){
echo $_POST['subject'];
}
?>

PHP form design best practice

I have been using PHP for a while now and I have always wondered how to represent a single form to handle updates and inserts into a database. At the present, I am using 2 seperate forms to do this and they both have basically the same information and textboxes, etc. I know there is a better way of handling this but I'm not sure what that is.
I have tried to use a single form in the past but the html mixed with the php looks terrible and is really hard to maintain. I am after "clean" and neat.
Can someone please put me on the right track.
One of the things that I have to use are POST values if the user submits the form and the validation didn't pass, the refresh should not wipe out the already entered values.
You could use a single form, with a hidden field for id. If this field is set - then you should update the $_POST['id'] record with the rest of the form. If the field is not set (that is, it has value=""), you should insert the form data to a new record.
You'll set the id field according to the action, for example /data/edit/1 will set the id field to , and/data/new` will not set value to it.
For example, your view could be
<form action="/data/edit/1">
<input type="hidden" value="<?php echo $data->id; ?>" />
<input type="text" value="<?php echo $data->name; ?>" />
</form>
In case of a new record, call your view with the following data
$data->id = '';
$data->name = '';
In case of a known record, simply init the $data object with the data
$data->id = $record_id;
$data->name = $record_name;
This is how I would probably do it without using any other frameworks/libraries etc. It is basically what Elazar Leibovich said.
<?php
//id is zero or a record id depending on whether updating or inserting
//an existing record could be edited using edit.php?id=10
//if the id GET parameter is omitted a new record will be created
$id = isset($_REQUEST['id']) ? (int) $_REQUEST['id'] : 0;
$error = '';
if ($id) {
//this array would be in the same format as the one below
$record = fetchRecordFromDb($id);
} else {
$record = array( 'field1' => 'default value', 'field2' => 'some other default' );
}
//allow POST data to override what is already in the form
foreach ($record as $key => $value) {
if (isset($_POST[$key])) {
$record[$key] = $_POST[$key];
}
}
if (isset($_POST['submit'])) {
if (!validateForm()) {
$error = 'Some form error';
} else {
if ($id) {
updateRecord($id, $record);
} else {
insertRecord($record);
}
//ok, redirect somewhere else
header('Location: http://somewhere');
exit();
}
}
?>
<form method="post">
<?php echo $error; ?>
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="text" name="field1" value="<?php echo htmlspecialchars($record['field1']); ?>"><br />
<input type="text" name="field2" value="<?php echo htmlspecialchars($record['field2']); ?>"><br />
<input type="submit" name="submit">
</form>

Categories