php form post method - php

I am trying to pass array using form post method :
submit.php
<form method="post" action="makepub.php">
<?php
.... Loop
....
echo '</td><td align="center">';
echo '<input type="checkbox" name="file_list[]" value="'.$pr.'">' ;
echo '</td><tr/>';
....
.... Loop end
?>
makepub.php :
if (isset($_POST['submit1'])) {
$file_list = $_POST["file_list"];
$how_many = count($file_list);
echo '<b>Total No of Public files chosen : </b>'.$how_many.'<br><br>';
if ($how_many>0) {
echo '<b>You changed following files to public : </b><br>';
}
for ($i=0; $i<$how_many; $i++) {
echo ($i+1) . '- ' . $file_list[$i] . '<br>';
// Some code here
}
echo "<br><br>";
}
Ok these two files works perfectly on my localhost with XAMPP.
php version 5.3
but on my server array is not getting passed.
I checked by replacing the array with single variable. Even so nothing is passed to file makepub.php
Is there anything i am missing with post here ???
Any suggestion is appreciated.
Thanks.

Your code should work as it appears, however you should make sure your submit button has a name of submit1 and then you close the form with a closing tag.

Related

Reading/Writing boolean values to INI file in PHP

First, forgive me if this is an overly pedantic question. I have searched trying to find answers but perhaps I'm using the wrong search terms.
Trying to use an INI file for a simple PHP application, where there is an admin page to allow application options to be easily changed. I'm able to read in the ini file with no issue, problem I'm coming across is on the write - if any boolean values are false, they won't get put into the _POST and as such don't get written back into the ini file. Here's my sample:
settings.ini file:
[Site options]
bRequireLegal['Require NDA before badge print'] = true ;
bCollectVehicleInfo['Collect vehicle information'] = false;
bShowAdditionalMessageBeforeBadgePrint['Show badge printing message'] = true;
[Company info]
companyname['Company Name'] = 'The Company, Inc.' ;
Code to read in the ini file (settings.php):
$filepath = 'settings.ini'; //location of settings file
$settings = parse_ini_file($filepath, true, $scanner_mode = INI_SCANNER_TYPED);
//pull everything in ini file in as variable
foreach($settings as $section=>$options){
foreach($options as $option=>$values){
foreach($values as $descriptor=>$value){
if(is_bool($value) === true) {
${htmlspecialchars($option)} = +$value;
}
else ${htmlspecialchars($option)} = $value;
}
}
}
And finally, the options setting page:
<?php
include 'settings.php';
//after the form submit
if($_POST){
$data = $_POST;
update_ini_file($data, $filepath);
}
function update_ini_file($data, $filepath) {
$content = "";
//parse the ini file to get the sections
foreach($data as $section=>$options){
//append the section
$content .= "[".$section."]\r\n";
//append the values
foreach($options as $option=>$values){
$content .= $option;
foreach($values as $descriptor=>$value){
$content .= "['".$descriptor."'] = '".$value."';\r\n";
}
}
$content .= "\r\n";
}
if (!$handle = fopen($filepath, 'w')) {
return false;
}
$success = fwrite($handle, $content);
fclose($handle);
return $success;
}
?>
<html>
<body>
<?php
?>
<div class="container-fluid">
<form action="" method="post">
<?php
foreach($settings as $section=>$options){
echo "<h3>$section</h3>";
//keep the section as hidden text so we can update once the form submitted
echo "<input type='hidden' value='$section' name='$section' />";
//print all other values as input fields, so can edit.
foreach($options as $option=>$values){
foreach($values as $descriptor=>$value){
if(is_bool($value) === true) {
echo "<p>".$descriptor.": <input type='checkbox' name='{$section}[$option][$descriptor]' ".(($value===true)?" checked":"")." /></p>";
} else
echo "<p>".$descriptor.": <input type='text' name='{$section}[$option][$descriptor]' value='$value' />"."</p>";
}
}
echo "<br>";
}
?>
<input type="submit" value="Update INI" />
</form>
</div>
</body>
</html>
Any help would be greatly appreciated!
In your update_ini_file() function, replace this:
$content .= "['".$descriptor."'] = '".$value."';\r\n";
with
$content .= "['".$descriptor."'] = '".($value ? 'true' : 'false')."';\r\n";
This will cause it to write the strings 'true' and 'false' instead of literal Boolean values. See How to Convert Boolean to String
Edit to add:
I think you're generating your checkboxes incorrectly:
<input type='checkbox' name='{$section}[$option][$descriptor]' ".(($value===true)?" checked":"")." />
This will cause the 'true' boxes to be checked, but they will still lack a value (and thus will not be transmitted to the server when the form is submitted). You should change that code to:
<input type='checkbox' name='{$section}[$option][$descriptor]' value='1'".(($value===true)?" checked":"")." />
In other words, all checkboxes should have a value of '1', but the way the browser works, only those which are checked will be submitted.
Edit to add:
Checkboxes that are not checked will not get submitted. That explains why you are not seeing any output for values that are 'false': they simply don't get submitted. When you loop through $data (which comes from $_POST), it is missing those unchecked (and thus 'false') checkboxes.
Using a solution found here: POST unchecked HTML checkboxes
Change this:
echo "<p>".$descriptor.": <input type='checkbox' name='{$section}[$option][$descriptor]' ".(($value===true)?" checked":"")." /></p>";
to this, which includes a hidden field that has the value '0', which will get submitted even if the corresponding checkbox is unchecked:
echo "<p>".$descriptor.": <input type='hidden' name='{$section}[$option][$descriptor]' value='0'><input type='checkbox' name='{$section}[$option][$descriptor]' ".(($value===true)?" checked":"")." /></p>";
However, this has its own set of potential problems, specifically when a checkbox is checked, you will send two identically named fields: one with a '0' value and the other with a '1' value. This is explained in the link above, and is left as an exercise for you to solve (or ask for further details on) if my answer doesn't work.

PHP not loading inline

I have a php file with the following code which is run inside a switch statement:
switch($valueFoo) {
case 'bar':
echo "<select id=\"selTheme\">";
$path = './files/css/themes/';
$files = array_values(array_diff(scandir($path), array('.', '..')));
for ($i = 0; $i < count($files); $i++) {
$cVal = substr($files[$i], 0, -4);
$cTitle = ucwords(substr($files[$i], 0, -4));
if ($cTitle==$_SESSION['setTheme']) {
echo "<option value='" . $cVal . "' onclick=\"changeColors('" . $cVal . "')\" selected>" . $cTitle . "</option>";
} elseif ($i>=count($files)) {
echo "<option value='" . $cVal . "' onclick=\"changeColors('" . $cVal . "')\">" . $cTitle . "</option></select>";
} else {
echo "<option value='" . $cVal . "' onclick=\"changeColors('" . $cVal . "')\">" . $cTitle . "</option>";
}
}
echo "...";
This is intended to create a list of options from a folder on my server. And it does indeed work. The problem is that it ONLY works AFTER the page is refreshed. I have been banging my head on my table trying to figure out why it does this only after the page is refreshed. I have no clue. I want the element to be filled with options as soon as it loads on page. I don't want the page to reload at all. It works by itself to populate an unordered list but I want it to be selectable options.
I don't see anything wrong with the code at all. I don't understand why the options list aren't being populated without a reloading of the page. I don't understand why it fills in perfectly when the page reloads. I would think that if it would do it properly AFTER the reload, it would do it just fine the first time it loads! Why isn't?
Please help me understand.
EDIT: This code comes as a return from an AJAX call. I am trying to run the for loop from that AJAX call. The loop doesn't run until the page reloads. Is there a way to force the AJAX call without the page load?
if you want a dynamic display of the folders content you'll have to use Ajax.
make sure that the session is already created and you're using 'session_start()' in the beginning of all your pages,
clarify your question/code to get precise answers

PHP script tags

Why does this if statement have each of its conditionals wrapped in PHP tags?
<?php if(!is_null($sel_subject)) { //subject selected? ?>
<h2><?php echo $sel_subject["menu_name"]; ?></h2>
<?php } elseif (!is_null($sel_page)) { //page selected? ?>
<h2><?php echo $sel_page["menu_name"]; ?></h2>
<?php } else { // nothing selected ?>
<h2>Select a subject or a page to edit</h2>
<?php } ?>
Because there is html used. Jumping between PHP and HTML is called escaping.
But I recommend you not to use PHP and HTML like this. May have a look to some template-systems e.g. Smarty or Frameworks with build-in template-systems like e.g. Symfony using twig.
Sometimes its ok if you have a file with much HTML and need to pass a PHP variable.
Sample
<?php $title="sample"; ?>
<html>
<title><?php echo $title; ?></title>
<body>
</body>
</html>
This is not much html but a sample how it could look like.
That sample you provided us should more look like....
<?php
if(!is_null($sel_subject))
{ //subject selected?
$content = $sel_subject["menu_name"];
}
else if (!is_null($sel_page))
{ //page selected?
$content = $sel_page["menu_name"];
}
else
{ // nothing selected
$content = "Select a subject or a page to edit";
}
echo "<h2>{$content}</h2>";
?>
You could echo each line of course. I prefer to store this in a variable so I can easy prevent the output by editing one line in the end and not each line where I have added a echo.
According to some comments i did a approvement to the source :)
Because the <h2> tags are not PHP and will display an error if the PHP Tags are removed.
This code will display one line of text wrapped in <h2> tags.
This is called escaping.
Because you cannot just type html between your php tags.
However, I would rather use the following syntax because it is easier to read. But that depends on the programmers opinion.
<?php
if(!is_null($sel_subject))
{ //subject selected?
echo "<h2>" . $sel_subject["menu_name"] . "</h2>";
}
elseif (!is_null($sel_page))
{ //page selected?
ehco "<h2>" . $sel_page["menu_name"] . "</h2>";
}
else
{ // nothing selected
echo "<h2>Select a subject or a page to edit</h2>";
}
Because inside the if-statement there is an HTML code, which you can put it by closing PHP tags and open it again like this:
<?php if(/*condition*/){ ?> <html></html> <?php } ?>
or:
<?php if(/*condition*/){ echo '<html></html>' ; }
That is because in this snippet we see html and php code. The code <?php changes from html-mode to php-mode and the code ?> changes back to html-mode.
There are several possibilites to rewrite this code to make it more readable. I'd suggest the following:
<?php
//subject selected?
if (!is_null($sel_subject)) {
echo "<h2>" . $sel_subject["menu_name"] . "</h2>";
//page selected?
} elseif (!is_null($sel_page)) {
echo "<h2>" . $sel_page["menu_name"] . "</h2>";
// nothing selected
} else {
echo "<h2>Select a subject or a page to edit</h2>";
}
?>
using the echo-command to output html, you don't need to change from php-mode to html-mode and you can reduce the php-tag down to only one.

how to use urlencode( ) in my example?

I checked php.net and read a few examples of how urlencode( ) works but somehow I just can't get it right. Can someone give me a hand?
it'll be a lot to example so hopefully my brief example would make sense.
I have a page called 2.php and it was called to show some contents of a .txt file choosen in 1.php.
I am told to make a link for 3.php and the link should look something like /3?filename=a.txt
with filename as GET parameter name and Ensure GET parameter value is urlencoded using the urlencode( ) function.
but I'm confused how and where I should put urlencode() to make it work.
I'll paste my 2.php code here...I simplified the codes a bit...
<?php
$fileContents = file("./aaa/" . $_GET["course"] . ".txt");
echo "<table border=\"1\">";
foreach($fileContents as $row)
{
echo "<tr>";
$contents = preg_split("/,/", $row);
foreach($contents as $eachline)
{
echo "<td>";
if(!(preg_match("/#/", $eachline)))
{
echo trim(ucfirst($eachline));
}
else
{
echo trim(strtolower($eachline));
}
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
echo "<a href='./1.php'>Choose another txt file</a><br/>";
echo "or<br/>";
echo "<a href='.3.php?'>Work with this txt file</a>";
?>
BUT…the 3.php option must have a query string appended to it: the name of the text file that was selected in 1, so instead of ./3.php, the url should be something such as ./3?filename=asdf.txt
Use “filename” as the GET parameter name. Ensure the GET parameter value is urlencoded using the urlencode( ) function.
but I'm just not sure how to get it to work....
You can wrap the part that should be url encoded in the function within the string:
$url = 'http://www.google.com?q=' . urlencode($search);
OR in html
http://www.google.com?q=<?php echo urlencode($search); ?>
Where . is the concatenation of 2 outputs.

Auto-submit form using PHP

I currently have this:
function submit()
{
document.getElementById("lostpasswordform").click(); // Simulates button click
document.lostpasswordform.submit(); // Submits the form without the button
}
<body onload="submit()">
<form name="lostpasswordform" id="lostpasswordform" action="/" method="post">
<input type="hidden" name="user_login" id="user_login" class="input" value="<?php echo ($user_login); ?>" />
</form>
</body>
it works on PC, but for some reason, javascript is not execute from iPhone so I'm wondering if theres a way to auto-submit the form using PHP instead of JS?
Thanks
There's no way to trigger a form submission server-side. You'd have to use a language that works in the DOM like JavaScript for this one. From what you've given us, I don't see why it wouldn't work with the way you have it set up now.
Check your code and if it still doesn't work, I'd suggest asking this question in a different context; something along the lines of getting your JavaScript to work on the iPhone instead of dumping it altogether.
As esqew points out, you can't perform a client side action from the server. Your options are to rework your function so it doesn't need the autosubmit (maybe you could use a GET variable rather than posting) or finding a work around for the iPhone.
For a workaround - the .click() function doesn't work on iPhones. You could try one of the solutions that have come up from this problem before such as using tap or this larger touch handler function.
No, PHP cannot do that, but your problem is due to the way the iPhone handles click events. Here's background info and a workaround. It seems like all you need is an empty onclick function to trigger it, so:
// untested
var f = document.getElementById('lostpasswordform');
f.onclick = function () { };
document.lostpasswordform.submit();
You might want to think of the experience for a user though -- why would clicking inside a form automatically submit the form? What's wrong with a submit button?
Here is a minimal javascript answer from a PHP Programmer like myself:
/** This is the script that will redraw current screen and submit to bank. */
echo '<script>'."\n" ;
echo 'function serverNotifySelected()'."\n" ;
echo '{'."\n" ;
echo ' window.open(\'\', \'BankPaymentScreen\');'."\n" ;
echo ' document.forms[\'bank_form\'].submit();'."\n" ;
echo ' document.forms[\'server_responder\'].submit();'."\n" ;
echo '}'."\n" ;
echo '</script>'."\n" ;
/** This form will be opened in a new window called BankPaymentScreen. */
echo '<form action="https://www.sandbox.bank.com/cgi-bin/webscr" name="bank_form" method="post" target="BankPaymentScreen">'."\n" ;
echo '<input type="hidden" name="cmd" value="_s-xclick">'."\n" ;
echo '<input type="hidden" name="custom" value="'.$transaction_start.'">'."\n" ;
echo '<input type="hidden" name="hosted_button_id" value="'.$single_product->hosted_button_id.'">'."\n" ;
echo '<table>'."\n" ;
echo ' <tr>'."\n";
echo ' <td><input type="hidden" name="'.$single_product->hide_name_a.'" value="'.$single_product->hide_value_a.'">Local</td>'."\n" ;
echo ' </tr>'."\n" ;
echo ' <tr>'."\n" ;
echo ' <td>'."\n" ;
echo ' <input type="hidden" name="'.$single_product->hide_name_b.'" value="'.$single_product->hide_value_b.'" />'.$single_product->short_desc.' $'.$adj_price.' USD'."\n" ;
echo ' </td>'."\n" ;
echo ' </tr>'."\n" ;
echo '</table>'."\n" ;
echo '<input type="hidden" name="currency_code" value="USD">'."\n" ;
echo '</form>'."\n" ;
/** This form will redraw the current page for approval. */
echo '<form action="ProductApprove.php" name="server_responder" method="post" target="_top">'."\n" ;
echo '<input type="hidden" name="trans" value="'.$transaction_start.'">'."\n" ;
echo '<input type="hidden" name="prod_id" value="'.$this->product_id.'">'."\n" ;
echo '</form>'."\n" ;
/** No form here just an input and a button. onClick will handle all the forms */
echo '<input type="image" src="https://www.sandbox.bank.com/en_US/i/btn/btn_purchaseimmediateCC_LG.gif" border="0" alt="This Bank - The safer, easier way to pay!" onclick="serverNotifySelected()">'."\n" ;
echo '<img alt="" border="0" src="https://www.sandbox.bank.com/en_US/i/scr/pixel.gif" width="1" height="1">'."\n" ;
This is the code for one button. The button will redraw the current page to go from purchasing to pre-approval AND also open a new window, give the new window focus and pass the new focused window to the payment provider.
This also prevents Chrome from blocking the new page from getting focus.
You can do this in deed.
There's an example how to, and even you can do it using cURL
<?php
//create array of data to be posted
$post_data['firstName'] = 'Name';
$post_data['action'] = 'Register';
//traverse array and prepare data for posting (key1=value1)
foreach ( $post_data as $key => $value) {
$post_items[] = $key . '=' . $value;
}
//create the final string to be posted using implode()
$post_string = implode ('&', $post_items);
//we also need to add a question mark at the beginning of the string
$post_string = '?' . $post_string;
//we are going to need the length of the data string
$data_length = strlen($post_string);
//let's open the connection
$connection = fsockopen('www.domainname.com', 80);
//sending the data
fputs($connection, "POST /target_url.php HTTP/1.1\r\n");
fputs($connection, "Host: www.domainname.com \r\n");
fputs($connection,
"Content-Type: application/x-www-form-urlencoded\r\n");
fputs($connection, "Content-Length: $data_length\r\n");
fputs($connection, "Connection: close\r\n\r\n");
fputs($connection, $post_string);
//closing the connection
fclose($connection);
?>

Categories