Validate input from drop down box - php

I have a drop down box which is pulling data from my database. when a user inputs data , should I still validate the drop down data on the server?

Yes. Always validate any information you are receiving from a client if you are storing, reading or performing some operation based on that data. Someone can always spoof a request not using a browser at all.

An easy way to validate it is...
<?php
$array = array(1 => 'a', 2 => 'b');
if ($_POST) {
if ( ! in_array($_POST['choose'], array_keys($array)) {
echo 'Invalid input';
}
}
?>
<form action="?" method="post">
<select name="choose">
<?php foreach($array as $value => $node): ?>
<option value="<?php echo $value; ?>"><?php echo $node; ?></option>
<?php endforeach; ?>
</select>
</form>
Which you must do, otherwise it may as well be a text input :)

Related

Printing array output in PHP in a readable format [duplicate]

This question already has answers here:
Is there a pretty print for PHP?
(31 answers)
Closed 7 months ago.
I'm trying to print multiple values user has selected on form submit. However with following what I'm seeing is only the last element printed irrespective whether it is selected or not.
Note that the print on the screen I'm looking at is a print that a layman can understand!
<?php
if(isset($_POST['submit'])) {
//I'm trying to show the user these are the values you've selected
print_r($option['name']);
}
?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER[" PHP_SELF "]);?>">
<td class="container">
<select multiple name="mercha_A[]" class="selectpicker form-control" title="Merchandiser type">
<?php foreach ($options as $option) { ?>
<option value="<?php echo $option['value']; ?>" <?php echo (isset($_POST[ 'mercha_A']) && in_array($option[ 'value'], $_POST[ 'mercha_A'])) ? ' selected="selected"' : ''; ?>>
<?php echo $option['name']; ?>
</option>
<?php } ?>
</select>
</td>
<td><button type="submit" name="submit">Submit</button></td>
</form>
Anyone needs a coffee on my account?
wrap your print_r in <pre> Tags
echo "<pre>";
print_r($option['name']);
echo "</pre>;
echo "<pre>";
print_r($_POST['mercha_A']); // you have to print the name attribute not option
echo "</pre>;
depending on your situation, you could use either of these, I think the last will best suite those who don't have a programming background. Because, I think JSON is a human readable format.
Method 1:
echo '<pre>'; print_r($_POST['mercha_A']); echo '</pre>';
Method 2:
echo json_encode($_POST['mercha_A']);
I think you meant to print
$_POST['mercha_A'];
Otherwise, $option['name'] is completely undefined in your case, but even if you put the print_r() at the end of the script, it would only be the name of the last option in $options.
In order to make print_r() readable, you can View Source (Ctrl+U) in your browser, or wrap it in <pre></pre> tags.
Using extbase debugger from TYPO3.
Check it out it's insane :) https://github.com/TYPO3/TYPO3.CMS/blob/master/typo3/sysext/extbase/Classes/Utility/DebuggerUtility.php
It helps you to debug arrays and object in a readable way
DebuggerUtility::var_dump($array)

Keep select list on reload

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.

How to successfully $_POST <options> from a <select> to another page in PHP?

I know there have a been a lot of questions like this but none (that I have found, and I've looked at many, but correct me if I am wrong) have solved my problem.
As the title of the question suggests, I need to Post select options to another page. My code looks something like this:
<form id="join_pool_form" name="join_pool_form" action="connect.php" method="post">
<select name="pool_name" style="width:170px">
<?php
//The options are from an array. This works fine.
foreach($poolnames as $value):
echo '<option value="">'.$value.'</option>';
endforeach;
unset($value);
?>
</select>
<input name="passcode" type="password" autofocus required id="passcode" size="35"style="width:170px">
<input type="submit" id="submit" value="Join Pool">
</form>
The connect.php (action of the form) page has something like this:
<?php
if (isset($_POST['pool_name'])) {
echo "do this";
}else {
echo "do other";
}
So the result of this should be "do this", but I always get "do other".
I'm very new to this, so excuse me if the solution is extremely simple. However, I have looked over it multiple times to no avail.
Thanks in advance.
Thanks everyone for your help. Problem solved.
you just have to pass the value in the html attribute of the option:
<select name="pool_name" style="width:170px">
<?php
//The options are from an array. This works fine.
foreach($poolnames as $value):
echo '<option value="'.$value.'">'.$value.'</option>';
endforeach;
unset($value);
?>
</select>
<?php
if (isset($_POST['pool_name'])) {
$variable = $_POST['pool_name'];
}else {
$variable = 'Unknown';
}
replace
echo '<option value="">'.$value.'</option>';
with
echo '<option value="'.$value.'">'.$value.'</option>';
The value of the select option has to be set to what your intending to send. If you don't set it, it will send nothing.
<option value='test'>Dont choose this</option>
The above will send the value test.

Writing and editing a PHP config file from a HTML form?

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

having PHP/javascript create a website based on options picked

I want the user to be able to pick two different variables from a website (from a drop down menu) and hit a button to bring them to a page where files are to download based on the variables picked.
I have the html ready to go.. and i have both menus in an array in php.. i was wondering how to pass both variables through to another site and then have unique content depending on which ones picked..
how do i get php to make it's own site?
Try something like this:
page1.php
<?php
$ar = array('foo', 'bar');
?>
<form action="page2.php" method="post">
<select name="choice">
<?php foreach($ar as $value) { ?>
<option value="<?php echo $value ?>"><?php echo $value ?></option>
<?php } ?>
</select>
<input type="submit" value="go to page2">
</form>
page2.php
<?php
$choice = $_POST['choice']; // sanitize as needed
if( $choice === 'foo' ) {
// do foo choice
}
else if( $choice === 'bar' ) {
// do bar choice
}
?>
Query strings are also ok, just change the form method to GET, and $_POST to $_GET.
have you tried using query variables? og perhaps posting the info to the page?
I would suggest using the query like: http://www.yourdomain.com/speciallayoutpage.php?layout=2&colortheme=1

Categories