I've been working on a PHP form that changes values in a file on my server. The form changes the values correctly but I need the <option value="round" <?php if($shape == 'round'){?>selected="selected"<?php }?>>Round</option> part of the form to always show to current value that is set in the file, currently it does not.
#file contents (the lines the values are on changed on a regular basis)
size=large
color-name=red
shape=round
height=short
weight=heavy
<?php
$file = "/home/user/color.props";
$contents = file($file, FILE_SKIP_EMPTY_LINES);
foreach($contents as $line) {
list($option, $value) = explode('=', $line);
if ($option == 'color-name') {
$color_name = $value;
} elseif ($option == 'shape') {
$shape = $value;
}
}
if(isset($_REQUEST['color_choice'])){
exec('sed -i '.escapeshellarg('s/color-name=.*/color-name='.$_REQUEST['color_choice'].'/g')." /home/user/color.props");
echo 'Color setting has been updated';
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="color_choice">;
<option value="round" <?php if($shape == 'round'){?>selected="selected"<?php }?>>Round</option>;
<option value="square" <?php if($shape == 'square'){?>selected="selected"<?php }?>>Square</option>;
</select>
<input type="submit" name="Submit" value="Submit" />
</form>
I'm still unclear on what exactly you're trying to accomplish. Your current code is only saving the last 'color-name' and 'shape' objects being read in from the file. It then can configure the selected option by making this change:
<option value="red" <?php if($color_name == 'red'){?>selected="selected"<?php }?>>Red</option>;
<option value="blue" <?php if($color_name == 'blue'){?>selected="selected"<?php }?>>Blue</option>;
<option value="green" <?php if($color_name == 'green'){?>selected="selected"<?php }?>>Green</option>;
<option value="purple" <?php if($color_name == 'purple'){?>selected="selected"<?php }?>>Purple</option>;
NOTE: The way you're reading in the file appends carriage returns/line returns at the end of your variables...for example, $color_name on my end contains two extra hex values at the end of the string: x0d and x0a
EDIT #2: Try making your form like this:
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select id="color_choice">
<option id="round">Round</option>
<option id="square">Square</option>
</select>
<input type="submit" name="Submit" value="Submit" />
</form>
<script>
var option = document.getElementById("color_choice");
option.options['<?php echo $shape ?>'].selected = true;
</script>
I'm pretty sure this will work, changes I made were:
1) Using javascript instead of php to change selected
2) Using id attributes instead of value or name
3) Added <script> tag at the end of form (it may not work if it's before)
You'll have to make changes to the form and the script depending on what type of values you're pulling from the file...but you should be able to figure out how to handle that.
Related
I am trying to create a weather website, where the user has 4 options from a drop down menu to select what region they want the weather for, and then from my PHP script I can use file_get_contents() to output the weather once they've selected a region and hit the submit button.
Currently, I have an error displaying: "Notice: Undefined variable: site in ... on line 12".
(regarding my cases 'Horfield, 'Thornbury' etc.
I am not sure how to fix this as I have these values in my 'value' field in my tags.
here is my HTML:
<form name="Weather" method="GET" action="<? $_PHP_SELF ?>">
<select id="site" name="site">
<option value="" disabled selected> Select a weather station...</option>
<option value="Horfield" <php if($site == "Horfield") print('selected="selected"'); ?> Horfield (Bristol)</option>
<option value="Thornbury" <php if($site == "Thornbury") print('selected="selected"'); ?>Thornbury (Bristol)</option>
<option value="Glouc" <php if($site == "Gloucestershire") print('selected="selected"'); ?>Gloucestershire</option>
<option value="Newquay" <php if($site == "Newquay") print('selected="selected"'); ?>Newquay (Cornwall)</option>
</select>
<label for="submit"></label>
<input type="submit" id="submit" name="submit">
and here is my PHP file:
<?php
$horfield = file_get_contents("http://www.martynhicks.uk/weather/clientraw.txt");
$thornbury = file_get_contents("http://www.thornburyweather.co.uk/weatherstation/clientraw.txt");
$gloucestershire = file_get_contents("https://www.glosweather.com/clientraw.txt");
$newquay = file_get_contents("http://www.newquayweather.com/clientraw.txt");
if (isset($_GET['site'])){
$site = $_GET['site'];
}
switch ($site) {
case 'Horfield':
echo $horfield;
break;
case 'Thornbury':
echo $thornbury;
break;
case 'Glouc':
echo $gloucestershire;
break;
case 'Newquay':
echo $newquay;
break;
}
?>
I'm sorry if this question seems trivial.
Also, any comments on my lines would be great:
<option value="Horfield" <php if($site == "Horfield") print('selected="selected"'); ?> Horfield (Bristol)</option>
any help is appriciated!
thanks
I was initially perplexed how you're not getting the site value from the query string. I tried plugging your HTML code (minus PHP) via donor site (using browser's Dev Tools) and the request it made had the site value (eg, GET https://www.google.com/?site=Horfield&submit=Submit). Perhaps the issue was a failed installation, or misconfigured, PHP setup.
But then it occurred to me that both HTML and PHP code/files could "belong" to a single URL. Meaning, whether I visit the page, or submit the form, the PHP code will be executed. If that is the case, then the issue is merely due to referencing an uninitialized/undeclared variable.
This is what's causing the issue:
if (isset($_GET['site'])){
$site = $_GET['site'];
}
If you visit the page (ie, not submit the form>, there will be no query string; thus $_GET will be empty (ie, $_GET = []) and isset() will return false. Not only will the $site variable not be set, it won't even be declared. And when it's referenced in the switch() it'll throw a NOTICE.
To fix the issue, you must always declare the $site variable:
$site = isset($_GET['site']) ? $_GET['site'] : null; // or false or "unknown"
// Or if you're using >=PHP7, you can use the null coalescing operator ??
$site = $_GET['site'] ?? null; // or false or "unknown"
Of course, if you need to handle this event, don't forget to set the default in your switch().
Bonus: In your HTML code, avoid unnecessary repetitions, eg:
<!--
$selected = "selected=\"selected\"";
$sites = [
[
"value" => "Horfield",
"selected" => $site === "Horfield" ? $selected : "";
"text" => "Horfield (Bristol)",
],
...
];
-->
<form name="Weather" method="GET" action="<? $_PHP_SELF ?>">
<select id="site" name="site">
<option value="" disabled selected> Select a weather station...</option>
<?php foreach ($sites as $site) { ?>
<option value="<?php echo $site["value"] ?>" <?php echo "$site["selected"] ?>><?php echo $site["text"] ?></option>
<?php } ?>
</select>
<label for="submit"></label>
<input type="submit" id="submit" name="submit">
Of course it's still better to use a templating system except for the very basic page.
I have a select list, but on page reload , the data in the list is not saved of corse.
I have fixed this with TextBoxes and Radio buttons by reading the variables from $_GET.
Here is an example of the form I have now:
<form action="" id="exampleForm" method="get">
<input type="checkbox" name="exampleCheckbox" <?php if (isset($_GET['exampleCheckboxStatus'])) {echo "checked";} ?>>Check this
</br>
<select name="exampleList" multiple>
<option>Apple</option>
<option>Banana</option>
<option>Cherry</option>
</select>
<input type="submit" value="Submit" id="submitButton"> </form>
I would like to keep the values of the 'exampleList' once submitted
(I stay on the same page)
I have seen posts on here that almost look like what I ask, but most of them want to use javascript. Is there an solution for my problem, wich look similiar to what I already have right now? I would like to fix this with php because I dont think I have enough knowledge of Javascript (yet)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
var opts = localStorage.getItem('opts'); // get selected items from localStorage key
opts = opts.split(','); // split result from localstorage to array
$('#exampleList').val(opts); // select options with array
});
</script>
<html>
<body>
<select id="exampleList" multiple>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="cherry">Cherry</option>
</select>
</body>
</html>
When you POST the form you only need to write the selected option values, comma separated, to the localstorage.
I finally found a solution:
The only flaw is the order of the :)
But since I use a plugin for displaying it does not matter much.
The fix:
I created 2 Array lists
list1 with everying in it
list2 with all selected values
Then I subtract list2 from list1 and dont have duplicates
So I can print both in different print methods.
<?php error_reporting(E_WARNING);
$fruitArray = array("Apple", "Banana", "Cherry", "Durian", "Eggfruit", "Fig", "Grapefruit");
$selectedFruitArray = $_GET['exampleList'];
$fruitArray = array_diff($fruitArray, $selectedFruitArray);
?>
<form action="" method="get">
<select name="exampleList[]" multiple>
<?php
foreach($fruitArray as $value) {
echo "<option value='$value'>$value</option>";
}
foreach($selectedFruitArray as $value) {
echo "<option value='$value' selected>$value</option>";
}
?>
</select>
<input type="submit">
</form>
Use FormRepo, a plugin specially made for retaining form data
on page refreshes.
Its usage is also simple:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="FormRepo.js"></script>
<script>
var $form = $('#input')
, $output = $('#output')
, repo = new FormRepo('restclient')
;
// get the last submitted values back
repo.restore($form/*, $form.attr('id')*/ ); // don't necessarily need an identifier
$form.submit(function (e) {
// preserve the last submitted values
repo.preserve($form/*, $form.attr('id')*/ ); // don't necessarily need an identifier
});
console.log( repo.all() );
</script>
You can do it by using session. This is the way using it you can store last selected value in session. Session value will not be destroyed even if you reload paga.
For e.g.,
<?php
session_start(); // Other Code
<div>
<p>Subtitle needs to be
<input type="radio" name="subTitleRadio" <?php if ($_SESSION['subTitleRadio'] != "LIKE") echo "checked"; ?> value="LIKE">contain
<input type="radio" name="subTitleRadio" <?php if ($_SESSION['subTitleRadio'] == "=") echo "checked"; ?> value="=">be equal to
</p>
<input type="search" name="subTitleSearchBox" placeholder="filter for subtitle" class="chosenStyle" value="<?php echo $_GET['subTitleSearchBox'];?>">
</div> //Other Code
?>
PHP Code for set value in session after submit :
<?php
session_start(); //Not required if your form action is on same page, else required //Rest code
$_SESSION['subTitleRadio'] = $_GET['subTitleRadio'] // OR $_POST['subTitleRadio']; // Rest code
?>
Same code works for me.
first of all at value parameters to the options, then you can check if exampleList has the right value and use that. for example:
<option value="apple" <?php if (isset($_GET['exampleList']) && $_GET['exampleList'] == "apple") echo "selected=\"selected\""; ?>>Apple</option>
Well, you could try something along these lines. It's a bit lengthy, you could shorten it up quite a bit. By showing it this way, I hope it's simpler to understand.
<form action="" id="exampleForm" method="get">
<?php
if (isset($_GET['exampleCheckboxStatus'])) {
echo '<input type="checkbox" name="exampleCheckbox" checked> Check this';
} else {
echo '<input type="checkbox" name="exampleCheckbox"> Check this';
?>
<br />
<select name="exampleList[]" multiple>
<?php
if( in_array('apple', $_GET['exampleList']) ) {
echo '<option value="apple" selected>Apple</option>';
} else {
echo '<option value="apple">Apple</option>';
}
if( in_array('banana', $_GET['exampleList']) ) {
echo '<option value="banana" selected>Banana</option>';
} else {
echo '<option value="banana">Banana</option>';
}
if( in_array('cherry', $_GET['exampleList']) ) {
echo '<option value="cherry" selected>Cherry</option>';
} else {
echo '<option value="cherry">Cherry</option>';
}
?>
</select>
<input type="submit" value="Submit" id="submitButton">
</form>
Note that I added [] to the select's name and corrected the br tag.
Adding [] will change the type from "string" (text) to an array (several texts). Then we can check what texts are included.
Try it for yourself, play around with the code a bit.
I have an an html form with only <select> element. Below the form I have a text box, I want to update the value of the text box based on the option selected in the form.
I am not sure if this is possible in PHP, I know I can do it with Javascript/Jquery, but I am working on a school project and its a PHP project. My teacher has done it but Im not sure if he used PHP.
Here is my code:
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="books">
<?php
$books = simplexml_load_file("books.xml");
foreach($books->book as $book){
$code = $book->code;
$title = $book->title;
echo "<option value='$code'>$code: $title</option>";
}
?>
</select>
</form>
<?php
$choice = $_POST['books'];
echo "<input type='text' value='$choice'>";
?>
When the page first loads I want the value from the selected option to be in the text box. I am not sure how I could go about doing this in PHP. Help would be appreciated.
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="books" onchange="javascript:document.form.submit();">
<?php
$books = simplexml_load_file("books.xml");
foreach($books->book as $book){
$code = $book->code;
$title = $book->title;
echo "<option value='$code'>$code: $title</option>";
}
?>
</select>
</form>
<?php
$choice = isset($_POST['books'])?$_POST['books']:'';
echo "<input type='text' value='$choice'>";
?>
Edit, as a pure PHP solution with a submit button, which will load data on initial page load then load data with the submit button as per selection.
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="books">
<?php
$books = simplexml_load_file("books.xml");
foreach($books->book as $book){
$code = $book->code;
$title = $book->title;
echo "<option value='$code'>$code: $title</option>";
}
?>
</select>
<input type="submit" value="submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])){
$choice = isset($_POST['books']) ? $_POST['books'] : $books->book[0]->code;
echo "<input type='text' value='$choice'>";
}
else{
$choice = isset($_POST['books']) ? $_POST['books'] : $books->book[0]->code;
echo "<input type='text' value='$choice'>";
}
?>
Original answer with onchange
The following would work, using Javascript and getElementById which would echo the selection in a text box using an onchange function.
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="books" onchange="update_textbox()" id="id_books">
<?php
$books = simplexml_load_file("books.xml");
foreach($books->book as $book){
$code = $book->code;
$title = $book->title;
echo "<option value='$code'>$code: $title</option>";
}
?>
</select>
</form>
<?php
$choice = isset($_POST['books']) ? $_POST['books'] : '';
echo "<input type='text' value='$choice' id='showit'>";
?>
<script>
function update_textbox(){
var selectbox = document.getElementById('id_books');
var id_books = selectbox[selectbox.selectedIndex].text;
document.getElementById('showit').value=id_books ;
}
</script>
To load data into the text box at initial page load, use:
Replace:
$choice = isset($_POST['books']) ? $_POST['books'] : '';
with:
$choice = isset($_POST['books']) ? $_POST['books'] : $books->book[0]->code;
When you first load the page, there are no POST data, so you could set $choice to the first book in list:
$choice = isset($_POST['books']) ? $_POST['books'] : $books->book[0]->code;
But you have to udnerstand the difference between PHP and JavaScript in here.
PHP can only change the value, when there is a request on the server as it is a server-side language. If you wish to update the value instantly, without submiting the form, you need to use JavaScript.
if it must be purely PHP, then put a submit button on your form for when a selection is made. This will set the value you are looking for. Others have provided samples on how to do this form submission automatically with javascript, but the end result is the same.
You can do it with PHP, it looks as though you're just missing the submit button to actually post the selection.
To submit the form without a submit button, you need to use javascript, eg.
<select onchange="this.form.submit()">....</select>
Below is a simple example (static options rather than xml) that also sets the selected option in the select (IMO this is a more practical use than printing it in the text input)
<?php
$val = isset($_REQUEST['books']) ? $_REQUEST['books'] : null;
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<select name="books" onchange="this.form.submit()">
<option value=>Choose a book</option>
<option<?php if($val && $val === 'opt 1'){ print ' selected';}?>>opt 1</option>
<option<?php if($val && $val === 'opt 2'){ print ' selected';}?>>opt 2</option>
</select>
<noscript><button type="submit">Submit</button></noscript>
</form>
<?php if($val){ ?>
<input type="text" value="<?php echo $_REQUEST['books']; ?>">
<?php } ?>
This is probably ok just for a school exercise, but in the real world you would probably want to sanitize any user input ($_REQUEST['book'] / $_POST['book']) and use a better templating engine than vanilla PHP (I like Twig) to help separate presentation from functional logic.
i have created html form (in MyTestFile.php file) with several options, and what i want to do is to check if post request has been recievied. Or in other words when user chooses something from my combobox and pushes button "Go" then it goes to the same page and sends choosed size value and echoes the size, and then form is not visible any more when size has been set. So here is my form code which isn't really working:
if (isset($_POST('submit'))) {
?>
<html>
<h2>Select size:</h2>
<form action="MyTestFile.php" method="POST">
<div>
<select name="SIZE">
<option value="big">big</option>
<option value="medium">medium</option>
<option value="small">small</option>
</select>
<input type="submit" value="Go">
</form>
</html>
<?php
} else {
echo $_POST('submit');
//and do some stuff here
}
The main idea: check if post request with size has been recieved, if not - show the form, where user can choose size.
$_POST is an array, so you must use square brackets to access the elements, not parenthesies. So change this:
if (isset($_POST['submit'])) {
// ^ ^ square breackets not ()
Secondly your submit button doesn't have a name, so your isset() check will never be true. Give it a name:
<input type="submit" name="submit" value="Go">
Or use the SIZE select in the isset check:
if (isset($_POST['SIZE'])) {
Finally your isset check needs reversing, in order to show the form when the post value is not present:
if (!isset($_POST['SIZE'])) {
// ^ not operator to reverse the check
I can see you tried so here you go:
Just add an exclamation mark before isset, add a name to the submit button and replace those parentheses with square brackets.
if (!isset($_POST['submit']))
{
?>
<html>
<h2>Select size:</h2>
<form action="MyTestFile.php" method="POST"><div>
<select name="SIZE">
<option value="big">big</option>
<option value="medium">medium</option>
<option value="small">small</option>
</select>
<input type="submit" name="submit" value="Go">
</form>
</html>
<?php
}
else
{
echo $_POST['size'];
//and do some stuff here
}
Use [ don't use ( in $_POST method. Because $_POST is array so use square brackets. Use same submit as name in submit button.
$_POST['submit'] instead of $_POST('submit')
and add ! (Not Set) in if condition, use below code,
if(!isset($_POST['submit'])){
// Your Form Code
}
else{
print_r($_POST);
}
Hi just looking for some direction, I have a HTML form which has several fields and basically what I am wanting to do is save the data entered from the form to a PHP config file and also have the ability to edit the saved data by accessing and submitting the form again. I would prefer to do this without the use of a database.
So here's an example:
<form method="post" name="config_form">
<div id="field">
<label>Keywords</label>
<br />
<input type="text" name="keyword">
</div>
<br />
<select name="color">
<option value="green">Green</option>
<option value="orange">Orange</option>
<option value="blue">Blue</option>
<option value="red">Red</option>
</select>
</form>
So the user enters 'computer' as the keyword and selects the color 'blue'. I want to then save this data into my config.php file as variables allowing my other website pages to access this data. Should this all be in an array as well?
<?php
//config file
$keyword = "computer";
$color = "blue";
?>
Also when I go back access the form again can I make it so the fields are prefilled with the data from the config.php file?
Any help would be much appreciated thank you!
If you're dedicated to storing this sort of thing in a file, then probably the easiest way is to just store all the data in an array in the form of $keyword => $value then use the serialize() and unserialize() functions to transform them into a format that can be easily stored into and read from a file.
Keep in mind that if there is only one file, then a change made by one user will affect them all, so if that's not acceptable, then you'll need to come up with a way to determine the user and which file to use.
A much better way of doing this is to just store these values in a database. Create a table called options with two fields - option and value - which will store the configuration options. If you want different users to have their own options, then you could add another field - userid (as a foreign key to a users table) - to track which user an option pair applies to.
Further, if there are a predefined set of options a user can set, then you could have fields in the table for each option, with default values, and you can create a row for each user with the specific config options set in a single record for that user.
You can include your configuration file in your main php script file:
// main.php
<? php include("config.php"); ?>
and build the form with something like this:
// main.php
<?php
?>
<form method="post" name="config_form">
<div id="field">
<label>Keywords</label>
<br />
<input type="text" name="keyword">
</div>
<br />
<select name="color">
<option value="green" <? if ($color == "green") echo "SELECTED"; ?> >Green</option>
<option value="orange" <? if ($color == "orange") echo "SELECTED"; ?> >Orange</option>
<option value="blue" <? if ($color == "blue") echo "SELECTED"; ?> >Blue</option>
<option value="red" <? if ($color == "red") echo "SELECTED"; ?> >Red</option>
</select>
</form>
<?
?>
finally you can save the form data in your config.php file using fopen() and fwrite() functions on form submit:
$key = $_POST["key"];
$color = $_POST["color"];
if ($key != '' && $color != '') {
$f = fopen('config.php', 'w') or die("can't open file");
fwrite($f, '<?php $keyword=' . $key . ';$color=' . $color . ';?>');
fclose($f);
} else { // write default values or show an error message }
You can do this in multiple ways. Best way would be to use a database such as MYSQL. You are asking for persistence and that is what DBs are for. Try this.
$key = $_POST["key"];
$color = $_POST["color"];
mysql_query("INSERT INTO smeTbl VALUES ('1',$key,$color)");
THen in the config file or what ever other file you have you can retrieve these values.
$query = mysql_query("SELECT * FROM smeTbl WHERE id='1'");
$fetch = mysql_fetch_array($query);
$keyword = $fetch["key"];
$color = $fetch["color"];
This is just an example and you can refine it based on your needs
when you submit the form and you want to store the submitted form's data in one php file,ni must use the file action functions fopen the config.php,and write php code into it.
when you display the form,you can fopen the config.php,and use the function "eval" to get data.forgive my english.
//when submit form
$string = '<?php $keyword="computer";$color="blue";?>';
$fp = fopen('config.php', 'w');
fwrite($fp, $string);
fclose($fp);
//when display form
include("config.php");
//so you can use $keyword and $color