I am trying to learn php today and I on the part of experimenting. I encountered problem using the drop down list, if and else and the function.
It's seems that its not working. I have no idea how to debug it. What I'm trying to do is that when the user selects "employed", it will simply return a "Do THIS!" text. but if the user selects any of the 3 (self employed, Voluntary member & OFW), it will display "DO THAT!".
It's really simple but i can't get it work, i just started php 6 hours ago. :)
Please help!
<form method="POST">
Salary: <input id="salarytext" type="text" name="salary" onkeypress="return isNumberKey(event)"><br>
Membership Type:
<select name="membershiptype">
<option value="employed">Employed</option>
<option value="SE">Self Employed</option>
<option value="VM">Voluntary Member</option>
<option value="OFW">OFW</option>
</select>
<br/>
<input type="submit" />
</form>
<?php
$a = (isset($_POST['salary'])) ? $_POST['salary'] : '';
$b = (isset($_POST['membershiptype'])) ? $_POST['membershiptype'] : '';
function employed () {
if (empty ($a)) {echo "";}
elseif ($a<10000) {$a * 2.0}
elseif ($a<20000) {$a * 2.3}
elseif ($a<30000) {$a * 2.7}
elseif ($a>30000) {$a * 3.0}
}
function sevmofw() {
if (empty ($a)) {echo "";}
elseif ($a<10000) { $a * 1.3}
elseif ($a<20000) { $a * 1.5}
elseif ($a<30000) { $a * 1.8}
elseif ($a>30000) { $a * 2.0}
}
if ( $_POST['membershiptype'] == 'employed' ){employed();
} elseif ( $_POST['membershiptype'] == 'SE' ){sevmofw();
} elseif ( $_POST['membershiptype'] == 'VM' ){sevmofw();
} elseif ( $_POST['membershiptype'] == 'OFW' ){sevmofw();
}
?>
Here's a flowchart of what i'm trying to do.
<select name="membershiptype" method="POST">
<option value="Employed" name="employed">Employed</option>
<option value="SE" name="sevmofw">Self Employed</option>
<option value="VM" name="sevmofw">Voluntary Member</option>
<option value="OFW" name="sevmofw">OFW</option>
</select>
should be
<select name="membershiptype">
<option value="employed">Employed</option>
<option value="SE">Self Employed</option>
<option value="VM">Voluntary Member</option>
<option value="OFW">OFW</option>
</select>
and your code should be
if (isset($_POST['membershiptype'])) {
if ( $_POST['membershiptype'] == 'employed' ){
employed();
} elseif ( $_POST['membershiptype'] == 'SE' ){
sevmofv();
}
}
...
I want to add this answer, because there is more potential in this topic and you're learning PHP so all bits add up.
Let's start with the PHP Tag. In your .php files you only need to add <?php once at the top and no close tag ?> at the end. Why? See this SO answer https://stackoverflow.com/a/4499749/2493918 .
Then put all the functions you want to be executed via the select in your script:
<?php
/**
* functions.php
*/
function employed()
{
return 'Employed function called.';
}
function sevmofw()
{
return 'Sevmofw function called.';
}
Note here that I replaced the " quotes with single ' quotes. Why? See this answer here:
https://stackoverflow.com/a/3446286/2493918 .
Then create another .php file containing your form (let's call it form.php):
<?php include 'functions.php'; // include the functions ?>
<!DOCTYPE html>
<html>
<head>
<title>Form Function Test</title>
</head>
<body>
<?php
// Check if the form was submitted
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset('membershiptype'))
{
// If the requested function exists, call it
if (function_exists($_POST['membershiptype']))
{
$func = $_POST['membershiptype'];
echo $func();
}
}
?>
<form action="" method="POST">
<div>
<label>
Salary: <input id="salarytext" type="text" name="salary" onkeypress="return isNumberKey(event);">
</label>
</div>
<div>
<label>
Membership Type:
<select name="membershiptype">
<option value="employed">Employed</option>
<option value="SE">Self Employed</option>
<option value="VM">Voluntary Member</option>
<option value="OFW">OFW</option>
</select>
</label>
</div>
<div>
<input type="submit" name="submit_btn" value="Submit form">
</div>
</form>
</body>
</html>
You see we include the functions into this forms page. This way you separate the functions from the so called view. Now you could include the same functions on other pages as well.
Then if you use PHP inside HTML you need to use both php tags <?php and ?> to separate the php part from the html.
If you submit the form the php part will check if the form was submitted and if the membershiptype is set. Then it continues and checks if the requested function exists. If so, it calls the function and returns the output.
Remember: It's better to return values inside functions and echo them where you want (see the example above).
A good resource to learn about PHP are the docs which can be found here:
For example the function_exists() documentation page http://www.php.net/manual/en/function.function-exists.php .
Try to switch to a PHP Framework as soon as you can. It'll help you immense. I recommend Codeigniter as it has a thorough documentation and a low learning curve. Later you could switch to something like Laravel, but I tell you, that's too soon now.
Good luck learning PHP :-)
Here's the answer for your help request after the question edit:
First of all, I love flow charts too! It's a clean way to plan a project or function.
I see you've used ternary operators. That's great :-)
Ok, so you've got a good idea of what you want to achieve (flowchart). I'll try to point you into the right direction with an example.
According to your flowchart "start" means the "form". This example shows the php part and expects that the form was submitted with the required data:
<?php
// START - Check if all required data was submitted
if ( isset($_POST['salary'], $_POST['membershiptype']))
{
// Get the form data
$salary = $_POST['salary'];
$member_type = $_POST['membershiptype'];
// USER SELECTS EMPLOYED?
$user_employed = ($member_type == 'employed') ? true : false;
// Create the multiplication table
// for the salary calculations
$multiBy = array(
'10000' => 1.3,
'20000' => 1.5,
'30000' => 1.8,
'30001' => 2.0,
'employed' => array(
'10000' => 2,
'20000' => 2.3,
'30000' => 2.7,
'30001' => 3.0,
),
);
// Create the calculation function
function calcSalary($s = 0, $employed = false)
{
// Use global here so you can access the
// $multiBy array from inside this function
// without the need to pass it separately
// like $s and $employed
global $multiBy;
// Check if $s is specified
if (empty($s)) return false;
// Round the $s value to be able to use
// it as key for the $multiBy array
// PHP Documentation: http://php.net/manual/en/function.round.php
$value = round($s, -4);
// Set the multiplication values
$multi = $multiBy;
if ($employed) $multi = $multiBy['employed'];
if ($value > 30000) $value = 30001;
if ($value < 10000) $value = 10000;
// Calculate the salary and return the result
return $s * $multi[$value];
}
// GET SALARY INPUT
// Putting the result in a var so you can process however you like
$calculated_salary = calcSalary($salary, $user_employed);
// END - Print the calculated salary
echo $calculated_salary;
}
else
{
// I guess this is self-explanatory :P
echo 'Please enter all required data and try again.';
}
This is a basic example. If you're going to accept user input (public form) remember to secure the input. With "secure" I mean htmlentities, CSRF (Cross Site Request Forgery), XSS (Cross Site Scripting), Code Injection (also SQL Injection if you're going to use Databases).
Also don't forget error handling e.g. missing form input (like if( ! isset($_POST['field'])) echo 'ERROR: Missing input'; else ...).
Here are some resources related to php security you might find useful:
PHP Functions…
PHP htmlentities()
PHP htmlspecialchars()
PHP strip_tags()
Articles with code examples…
Ned Batchelder: Xss with utf-7
Cross-Site Request Forgeries by Chris Shiflett
and some StackOverflow Questions:
"Why my code vulnerable to xss attack?"
How to prevent SQL injection in PHP?
Have fun reading and happy coding!
Related
I am trying to add a option value for select dropdown in CF7. I am using following shortcode to generate HTML like
<select name="Construction" class="form-control">
<option value="opt1">Masonry</option>
<option value="opt2">Frame</option>
<option value="opt3">Mixed Masonry-Frame</option>
</select>
My Shortcode is:
[select* Construction class:form-control "Masonry|opt1" "Frame|opt2" "Mixed Masonry-Frame|opt3"]
But All I got is:
<select name="Construction" class="form-control">
<option value="Masonry">Masonry</option>
<option value="Frame">Frame</option>
<option value="Mixed Masonry-Frame">Mixed Masonry-Frame</option>
</select>
I just followed the patterns used in https://contactform7.com/selectable-recipient-with-pipes/
Note : WPCF7_USE_PIPE was set true.
You might not need it anymore, but I came across the same problem today.
I solved it by filtering wpcf7_form_tag.
In my opinion a better solution than using JS because the values will be changed server-side before any form HTML is rendered.
Example implementation which should make the pipes work the way you want:
function so48515097_cf7_select_values($tag)
{
if ($tag['basetype'] != 'select') {
return $tag;
}
$values = [];
$labels = [];
foreach ($tag['raw_values'] as $raw_value) {
$raw_value_parts = explode('|', $raw_value);
if (count($raw_value_parts) >= 2) {
$values[] = $raw_value_parts[1];
$labels[] = $raw_value_parts[0];
} else {
$values[] = $raw_value;
$labels[] = $raw_value;
}
}
$tag['values'] = $values;
$tag['labels'] = $labels;
// Optional but recommended:
// Display labels in mails instead of values
// You can still use values using [_raw_tag] instead of [tag]
$reversed_raw_values = array_map(function ($raw_value) {
$raw_value_parts = explode('|', $raw_value);
return implode('|', array_reverse($raw_value_parts));
}, $tag['raw_values']);
$tag['pipes'] = new \WPCF7_Pipes($reversed_raw_values);
return $tag;
}
add_filter('wpcf7_form_tag', 'so48515097_cf7_select_values', 10);
Edit:
In the backend, the [tag] will be replaced by the value, not the label. But if you still want to have the label displayed in the e-mails instead, then that is also possible by recreating (reversing) the CF7 pipes. That way, you can actually choose which one to use. [tag] will display the label and [_raw_tag] will display the value.
I have edited the code above to reflect this. It is optional of course.
This will work server side only. According to the documentation this is to prevent values to be sent to the browser client.
I found this comment by Herbert Van-Vliet on this question
So, On submit you will get exact value which you have defined through Pipe Operator ("|")
On my page, the user has a choice of what data to display. I did this simply using a dropdown list and GET parameters. It currently looks like this:
The form:
<form method="get" action="contents.php">
<select name="TutorialBlock">
<option value="tuts1">Block One - Starting</option>
<option value="tuts2">Block Two</option>
<option value="tuts3">Block Three</option>
</select>
<input type="submit">
</form>
The script that loads the data depending what option the user chose:
<?php
$var_value = $_GET['TutorialBlock'];
include '/includes/'.$var_value.'.php';
?>
This works fine, and PHP includes the correct file depending on what option the user chose, the issue is, if the user hasn't chosen an option, PHP just throws up file not found errors, since it is looking for a file which isn't there. Is there a way that I can stop the PHP script from running if the GET parameter is not set?
What you're doing now is causing some serious vulnerabilities. You can never trust user input.
You should be running your $_GET['TutorialBlock'] against a whitelist. Here is an example for you.
$whitelist = array(
'page',
'blockpage',
//....etc
);
if(isset($_GET['TutorialBlock']) && !empty($_GET['TutorialBlock'])) {
// now make sure it's in the whitelist.
if(!in_array($_GET['TutorialBlock'], $whitelist)) {
die('bad page');
} else {
include '/includes/'.$_GET['TutorialBlock'].'.php';
}
} else {
// user didn't select page... do something here..
}
The above is only pseudo code (example), you still need to ensure user input is vaid.
$var_value = isset($_GET['TutorialBlock']) ? $_GET['TutorialBlock'] : false;
if($var_value) {
include '/includes/'.$var_value.'.php';
} else {
// query value wasn't there
exit("TutorialBlock is required");
}
Important
You're vulnerable to directory traversal attacks with your code as is.
if(isset($_GET['TutorialBlock'])) {
$var_value = $_GET['TutorialBlock'];
include '/includes/'.$var_value.'.php';
} else {
//not set
}
I´m trying to play around with languages and an own Database/CMS structure. I´ve got so far, that the Browserset language is selected. This works well. I know there are better solutions (other domains for each language, i´ve google´d a lot)...with an own added cookie (setcookie) it worked, too.
$lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
$langCookie = $_COOKIE['language'];
if(!empty($langCookie)){
$lang = $_COOKIE['language'];
}
if($lang == en){
//Select from database, got three languages, text (en), textOther1 (otherlang1) and textOther2
}elseif($lang == xy){
//other selecet
}else{
//select if nothing fits
}
My problem at this point is:
How can I let the user choose a language with a select on the page. I want to let the user choose the language by a select...but i can´t get it done to set my cookie as I selected an option...
I know that I have got to reload the page after this (header_location), but I can´t get further...
Any help or tipps for solving this would be very nice.
I think you can use the GET method to sent request to a page, just add the language code as a paramter, then check whether this parameter exists -- if not, take your value as it's now.
You can use this markup for example:
<form id="langForm" action="" method="GET">
<select name="lang" onchange="this.form.submit();">
<option value="en">English</option>
<option value="fr">French</option>
</select>
</form>
Then on-server side you should check if lang parameter exists:
<?php
if( isset( $_GET ) && ! empty( $_GET['lang'] ) ) {
// do something
} else {
// do something else
}
?>
Hope that helps!
I have form with lot of elements, most are select box, check box, radio . for example below selectbox chart[type] I am setting it value through php
<select name="chart[type]" id="chart_type" >
<option value="nps" <?php if ( $chart_data['chart']['type'] == 'nps' ) echo ' select="selected" '; ?> >NPS Barchart</option>
<option value="score" <?php if ( $chart_data['chart']['type'] == 'score' ) echo ' select="selected" '; ?>>Number/score</option>
<option value="top5" <?php if ( $chart_data['chart']['type'] == 'top5' ) echo ' select="selected" '; ?>>Top 5</option>
</select>
I tried a code to set from value using jQuery
<select name="chart[type]" id="chart_type" >
<option value="nps" >NPS Barchart</option>
<option value="score">Number/score</option>
<option value="top5">Top 5</option>
</select>
<script>
$(function(){
$('[name="chart[type]"]').val(
'<?php echo $chart_data['chart']['type']; ?>'
);
});
</script>
I feel code is much cleaner . I am planning to change all forms code refill to this way . I would like to know any disadvantage of using second ? .. my application is for chart rendering it will not work, if JavaScript is disabled !
If you're using PHP and have no real reason to use JavaScript to print HTML, I'd keep using PHP. Mixing like that is not a good idea, you should really consider AJAX. But you can make your PHP code more maintainable and dynamic:
<?php
$data = array(
'nps' => 'NPS Barchart',
'score' => 'Number/score',
'top5' => 'Top 5'
);
$options = '';
foreach ($data as $key => $value) {
$selected = $chart_data['chart']['type'] == $key ? 'selected' : '';
$options .= sprintf('<option class="%1$s" %2$s>%3$s</option>', $key, $selected, $value);
}
echo sprintf('<select name="chart[type]" id="chart_type">%s</select>', $options);
Since your application will not work at all without JS disabled, there is really nothing that could be considered a disadvantage to this approach. In fact, it might be easier this way to covert your select boxes to have values loaded by AJAX calls.
The disadvantage is that your code now has a dependency on JavaScript and jQuery. Some (very few % of people) have JavaScript disabled, and so won't have anything selected by default
It's not best practice, but I must admit that I have used JavaScript in similar ways in the past simply for convenience/ease. It feels somewhat "hacky"
Using two languages in one block isn't always a bad thing. But when your one line of
'<?php echo $chart_data['chart']['type']; ?>'
Become more than one line, it will start to look rather messy.
When that happen you can do the below.
<script>
$(function(){
// assignment from php
var chart_type = '<?php echo $chart_data['chart']['type']; ?>';
$('[name="chart[type]"]').val(chart_type);
});
</script>
Anyway, it will be best if you can convert your application to perform ajax posting so you won't have to setting form value through this way.
To put it simply I have this variable which carries a hyperlink:
$test3 = 'Move to Quotes';
and what I need is to execute this variable inside a switch case like below:
switch ($_POST['dropdown']) {
case "Select Folder":
echo "Please select";
break;
case "One":
exec($test3); <-- //here i want to run (if this is not execute, my misunderstanding) the link.
break;
case "Two":
header('Location: http://www.facebook.com/'); <-- //this is just a test
break;
default:
echo "<br></br>";
echo "Move multiple files:";
echo "<br></br>";
}
?>
<form method="post" name="theform" action="">
<select name="dropdown">
<option value="Move to Folder">Select</option>
<option value="One">One</option>
<option value="Two">Two</option>
</select>
<input type="submit" value="Move"/>
</form>
I'd like know how to execute the ahref link without the user clicking it, but simply set this link as a case and when the user submits the form, the selected case actions the hyperlink.
Any help appreciated.
MORE DETAIL
I understand that javascript and php are both seperate languages and that a better option would be to use Ajax, but my understanding of Ajax is limited.
To explain it better, this is what's going on in its entirety:
1) I have a mailbox with a selection of messages.
2) You are able to check these messages and then click a link "Trash Selected" which deletes the selected messages. This the link:
Trash Selected
The javascript function actions the php function in $muldel for all selected messages and updates the database.
This is the javascript function in question:
function inboxDelete(url) {
document.messages.action = url;
document.messages.submit();
}
archiveMove() is exactly the same, just duplicated temporarily to make things clear.
3) I have now re-used the ahref code to do the same procedure, but this time, for moving the selected messages into folders.
4) These folders can be selected from a drop down box - this is where the form comes in.
5) So although I can get it to work by adding a link like such:
$test3 = 'Move to Quotes';
echo $test3;
6) I now need this to work the same way but the link being changed, depending on which folder is selected.
That's the full extent to my problem, I hope this is more clear.
I am aware you can send variables into javscript using GET or POST and then carry out the function entirely through javascript. I have tried something like below, but to no avail:
<form method=post name="myform" action="<?php echo $PHP_SELF;?>">
<input type="hidden" name="formVar" value="">
<input type="text" value="Enter Text Here" name="myText">
<input type="text" value="Enter Text Here" name="myText2">
<input type="submit" value="Send form!" onClick="readmove()">
</form>
<?php
// Retrieve the hidden form variable (using PHP).
$myvar = $_POST['formVar'];
if ($myvar == "$mulmov"){
echo $mulmov;
}
?>
<script language="JavaScript">
<!--
function setText(){
document.myform.myText.value = document.myform.myText.value.toUpperCase();
}
function readmove(){
document.myform.myText.value = "<?php echo $myvar; ?>" ;
readmove2();
}
function readmove2(){
if (document.myform.myText.value == "$mulmov"){
document.myform.myText2.value = "<?php echo $mulmov; ?>" ;
<?php exec ('archiveMove(\''.$mulmov.'\'); return false;'); ?>
} else if (document.myform.myText.value == "$mulmov2"){
document.myform.myText2.value = "<?php echo $mulmov2; ?>" ;
}
}
</script>
First of all, you can't execute JavaScript from within PHP like this. At this point, the control has already moved to the server and JavaScript is run on the client-side.
Second of all Im assuming you dont want to just follow the link, you want to run the link's onClick event, since the href is just a hashtag. So you are trying to run a JavaScript function with PHP. You cant call a function in one language from a function in another language.
Its hard to tell what exactly you are trying to do, but if you want to run a function when a user selects a certain dropdown, write a php function that does what archiveMove() does. If you want this to happen without a page refresh, you can stop the submit process and call your archiveMove() function with javaScript and Ajax.
If elaborate on what exactly you are trying to do, maybe we can help more.
Ok, so the only difference between your working code and the not working code is that you want to dictate the submitted URL based on what is selected in the dropdown?
So you can use JavaScript to set the form action when the dropdown is selected.
BUT, It might be a better idea to submit the form with the same action everytime, and then use PHP to decide what to do. It seems like this is where you were headed initially. Just get the folder id in the switch statement and call a function to make your edits:
The PHP can be similar to the way you had it:
switch ($_POST['dropdown']) {
case "Two":
// set folder id
$folder_id = 2;
break;
}
moveMessages($_POST['Messages'], $folder_id);
function that moves the messages where they need to go.
function moveMessages($messages, $folder_id){
// depending on your form setup
foreach($data as $id => $value ){
if($value){
// code to move to folder
}
}
return true;
}
If there are other factors involved, let me know.
You can write JavaScript code that request a url using window.location.href in click hadler.
window.location.href="http://example.com";
Ok this was my solution but thank you also for your solution Jeff Ryan, this worked also.
<script language="javascript">
function buttons(str)
{
document.getElementById("txtHint").innerHTML = str;
if (document.f1.users.options[1].selected){
document.getElementById("txtHint").innerHTML ="<?php echo $mulmov; ?>";
document.messages.action = document.getElementById("txtHint").innerHTML;
}
else if (document.f1.users.options[2].selected){
document.getElementById("txtHint").innerHTML ="<?php echo $mulmov2; ?>";
document.messages.action = document.getElementById("txtHint").innerHTML;
}
}
function submit_mes(str)
{
document.messages.submit();
}
</script>
<form name="f1">
<select name="users" onChange="buttons(this.value)">
<option value="">Select a folder:</option>
<option value="Quotes">Quotes</option>
<option value="Projects">Projects</option>
<input type="button" value="Move" onClick="submit_mes(this.value)">
</select>
</form>
<div id="txtHint"><b>Folder will be listed here.</b></div>