passing parameters to php in a form? - php

I have the basic html form echoed through php:
<html>
<body>
<?php
if (isset($_GET["pk"]))
{ $pk = $_GET["pk"];}
echo '<form action="up.php" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>';
?>
</body>
</html>
I would like to pass the value of pk to up.php
Modifying action="up.php?pk=$pk" did not work.

Use a hidden field:
<input type="hidden" name="pk" value="<?php echo $pk; ?>">
By the way, printing large amounts of HTML like you have there is ugly. Consider either stepping out of PHP to do so, using HEREDOC, a template engine, or a framework.
EDIT:
As noted below, you should not print GET and POST data back to the page without sanitizing it first. Assuming pk is a primary key, you should wrap $pk above with the intval function, at the very least.

I agree with all the comments regarding some kind of input control of the $_GET['pk'] variable. I would recommend the filter module in php, which is pretty much a default installed module I believe.
<html>
<body>
<?php
$param = filter_input(INPUT_GET, 'pk', FILTER_SANITIZE_ENCODED);
?>
<form action="up.php<?php echo (isset($param) && $param != false) ? '?pk=' . $params : ''); ?>" method="post"enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
You can find more information about the filter module here: link text
I also agree with Paolo Bergantino, this is not the prettiest way to do it, and a template engine, heredocs or regexp could be a better way of increasing the readability and maintainability of the system.

You can't use a variable inside a single-quoted string:
$pk = 123;
echo 'Hello $pk'; // echos Hello $pk
echo "Hello $pk"; // echos Hello 123
echo 'Hello ' . $pk; // echos Hello 123
The best way to pass it through would be as a hidden field inside the form

Try sth like this:
<html>
<body>
<?php
$params = "";
if (isset($_GET["pk"]))
{ $params = "?pk=" . $_GET["pk"];}
echo '<form action="up.php' . $params . '" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>';
?>
</body>
</html>
Of course you should be aware that $_GET["pk"] may contain pretty much anything, so think about some kind of input sanitization.

Related

Add Web form input to an Array

I cannot figure out how to go about keeping the data saved on $myArray after hitting Save. Everytime i do that, it replaces the other input.
I need to be able to save all user enters and save in text file. basically keep saving data on array and update file as well.
Any suggestions?
<!DOCTYPE>
<html>
<body>
<form action="list.php" method="POST">
Name: <input type="text" name="name[]" /><br />
Email: <input type="text" name="name[]" /><br />
<input type="submit" name="save" value="Submit" /><br />
<?php
$myArray = array();
if (isset($_POST['save']))
{
array_push($myArray,$_POST['name']);
}
print_r($myArray);
?>
</body>
</html>
Every time your user hits Submit, there is a new request sent to your script.
The variable $myArray is created on the first line of your PHP code, and is an empty array.
Variables do not persist across requests. I suggest you use either a cookie, or a session variable for this.
Example of the latter is here:
<?php
session_start(); // This has to be done before any data is sent to the client
session_regenerate_id(); // Good practice to prevent session hijacking
?>
<!DOCTYPE>
<html>
<body>
<form action="list.php" method="POST">
Name: <input type="text" name="name[]" /><br />
Email: <input type="text" name="name[]" /><br />
<input type="submit" name="save" value="Submit" /><br />
<?php
if( !isset( $_SESSION['myArray'] ) || !is_array( $_SESSION['myArray'] ) )
{
$_SESSION['myArray'] = array();
}
if (isset($_POST['save']))
{
$_SESSION['myArray'][] = $_POST['name'];
}
print_r($_SESSION['myArray']);
// Here you can write the contents of $_SESSION['myArray'] to a file.
?>
</body>
</html>
This way you will keep track of it in the text file:
<html>
<body>
<form action="list.php" method="POST">
Name: <input type="text" name="name[]" /><br />
Email: <input type="text" name="name[]" /><br />
<input type="submit" name="save" value="Submit" /><br />
<?php
$myArray = array();
if (isset($_POST['save']))
{
$f = file_get_contents("myfile.txt");
$myArray = split($f, "\n");
array_push($myArray,$_POST['name']);
file_put_contents("myfile.txt", implode($myArray, "\n"));
}
print_r($myArray);
?>
</body>
</html>
(You may want to use PHP_EOL [or whatever that constant is - I always have to look it up] in place of "\n")
Since HTML is by nature transactional you do not keep track of ANYTHING except sessions, databases, files - any variables you have start over empty each time you load your page again.

Trouble getting echo syntax correct for html code

I am returning text results from a PHP FOREACH loop, and I want to add the links add and delete for each result where it looks like this: ADD | DELETE. The trick is, I need each link to be a form that is styled as a link so it looks like text links but I can use Post when the links are clicked. I can style the links with the class name "formlink", but my question is, how will the statement syntax look? I keep getting T_variable errors. Can someone help show how the code below so it will display error-free on the page?
<?php
echo "<hr>" . $results[text]
<form action="" method="post"><button type="submit" class="formlink">Approve</button>
</form> | <form action="" method="post"><button type="submit"
class="formlink">Delete</button></form>
That's one messy code though. Well I dunno, I could give you a brief idea, and the rest is up to you.
<?php
// Check clicked button
if (isset($_POST['btn_approve'])) {
$username = $_POST['username'];
}
if (isset($_POST['btn_disapprove'])) {
// Do something
}
?>
<form action="" method="post">
<input type="text" name="username" value="<?php echo (isset($username) ? $username : ''; ?>">
<input type="submit" name="btn_approve" class="form-link" value="Approve">
<input type="submit" name="btn_disapprove" class="form-link" value="Disapprove">
</form>
You could check isset() and How to write ternary operator.
<?php
echo "<hr>" . $results[text];
?>
<form action="" method="post">
<button type="submit" class="formlink">Approve</button>
</form> |
<form action="" method="post">
<button type="submit" class="formlink">Delete</button>
</form>

Update form fields after posting with PHP_SELF

I am using php_self to submit a form. Once the data has been posted, I want to pass a calculated value to another form field on the same page, original form.
The $title_insurance field stays blank. Any ideas on why? Thanks!
<?php
if(isset($_POST['submit']))
{
$sale_price = $_POST['sale_price']; // posted value
$title_insurance = ($sale_price * 0.00575) + 200;
?>
<script type="text/javascript">
document.getElementById("title_insurance").value='<?php echo $title_insurance ; ?>';
</script>
<?php } ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<input name="sale_price" type="text" id="sale_price" size="15">
<input name="title_insurance" type="text" id="title_insurance" size="15" value="<?php echo $title_insurance; ?>" />
<input name="submit" type="submit" class="bordered" id="submit" value="Calculate" />
</form>
The submit button is called button, also if you are outputting a javascript to amend the value it need to be run after the DOM has created the element title_insurance.
if(isset($_POST['button']))
{
$sale_price = $_POST['sale_price']; // posted value
$title_insurance = ($sale_price * 0.00575) + 200;
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<input name="sale_price" type="text" id="sale_price" size="15">
<input name="title_insurance" type="text" id="title_insurance" size="15" value="<?php echo $title_insurance; ?>" />
<input name="button" type="submit" class="bordered" id="button" value="Calculate" />
</form>
<script type="text/javascript">
document.getElementById("title_insurance").value='<?php echo $title_insurance ; ?>';
</script>
A better way in this case would be to forget about the javascript as it is unnecessary and do this
// I am assuming you have initialized $title_insurance
// somewhere above here to its default value!!!!
$title_insurance = isset($_POST['button']) ? ($_POST['sale_price'] * 0.00575) + 200 : $title_insurance;
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<input name="sale_price" type="text" id="sale_price" size="15">
<input name="title_insurance" type="text" id="title_insurance" size="15" value="<?php echo $title_insurance; ?>" />
<input name="button" type="submit" class="bordered" id="button" value="Calculate" />
</form>
You have an extra space in your getElementById parameter:
// VV
document.getElementById("title_insurance ").value='<?php echo $title_insurance ; ?>';
What you want to do is best done by AJAX. The <form> construction is outdated and not useful unless you are transferring the user to another page and sending some data along with it - or, if you are finished getting user data and just want to process what was entered and display a completion message.
If you wish to continue processing on the same page, then AJAX is the way to go. And the best way to use AJAX is to have a separate processor file (PHP) that receives the data, processes it, and sends it back.
To convert a <form> construct to AJAX, you really just need to remove the <form></form> tags and convert the submit button from type="submit" to type="button" id="mybutton", and use the IDs on the button and on the other elements to grab the data they contain and feed them to the AJAX code block. The examples in the link at bottom shows what you need to know - they are simple, helpful examples.
To conserve resources, you can use the same PHP processor page for multiple AJAX requests -- just send a variable (eg. 'request=save_to_db&first_name=bob&last_name=jones', ) and test for what "request" is received, that will determine what your PHP processor file does and echoes back.
This post, and the examples it contains, will help.
try this first
In you coding you missed this $_POST['button']
and
<?php
if(isset($_POST['button']))
{
$sale_price = $_POST['sale_price']; // posted value
$title_insurance = ($sale_price * 0.00575) + 200;
?>
<script type="text/javascript">
document.getElementById("title_insurance ").value='<?php echo $title_insurance ; ?>';
</script>
<?php } ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<input name="sale_price" type="text" id="sale_price" size="15">
<input name="title_insurance" type="text" id="title_insurance" size="15" value="<?php echo $title_insurance; ?>" />
<input name="button" type="submit" class="bordered" id="button" value="Calculate" />
</form>
and also refer this FIDDLE it will more helpful to you..

Use $_POST to get input values on the same page

Sorry if this is a rather basic question.
I have a page with an HTML form. The code looks like this:
<form action="submit.php" method="post">
Example value: <input name="example" type="text" />
Example value 2: <input name="example2" type="text" />
<input type="submit" />
</form>
Then in my file submit.php, I have the following:
<?php
$example = $_POST['example'];
$example2 = $_POST['example2'];
echo $example . " " . $example2;
?>
However, I want to eliminate the use of the external file. I want the $_POST variables on the same page. How would I do this?
Put this on a php file:
<?php
if (isset($_POST['submit'])) {
$example = $_POST['example'];
$example2 = $_POST['example2'];
echo $example . " " . $example2;
}
?>
<form action="" method="post">
Example value: <input name="example" type="text" />
Example value 2: <input name="example2" type="text" />
<input name="submit" type="submit" />
</form>
It will execute the whole file as PHP. The first time you open it, $_POST['submit'] won't be set because the form has not been sent.
Once you click on the submit button, it will print the information.

HTML submit forms using PHP

I am learning PHP now, so pardon my silly question which I am not able to resolve.
I have created a simple web form where in I display the values entered by a user.
function submitform()
{
document.forms["myForm"].submit();
} // in head of html
<form action ="res.php" id="myForm" method="post" >
Name: <input type="text" name="name" size="25" maxlength="50" /> <br> </br>
Password:<input type="password" name="password" size="25" maxlength="50" />
Description: <textarea name="editor1"> </textarea>
<input type="submit" value="Submit" onclick="submitForm()" />
</form>
and res.php contains:
foreach($_POST as $field => $value)
{
echo "$field = $value";
}
When I click on the submit button, I just get a blank page without any values from the form. Can anyone please let me know what am I missing?
There's no need for the javascript. This should do:
<form action ="res.php" id="myForm" method="post" >
Name: <input type="text" name="name" size="25" maxlength="50" /> <br> </br>
Password:<input type="password" name="password" size="25" maxlength="50" />
Description: <textarea name="editor1"> </textarea>
<input type="submit" value="Submit" />
</form>
Let's start with fixing errors:
JavaScript is case-sensitive. I see that your function name is submitform and the form's onclick calls submitForm.
The javascript is not really necessary from what you've shown us, I would try this on a single php page and see if it works:
Create a test.php file for test purpose:
<?php
if($_POST){
foreach($_POST as $key=>$value){
echo "$key: $value<br />";
}
}else{
<form action="test.php" method="post">
<input type="text" value="1" name="name1" />
<input type="text" value="2" name="name2" />
<input type="submit" value="submit" name="Submit" />
</form>
}
?>
If it does work, slowly work your way into your current form setup to see what is breaking it. If it doesn't work, there's something larger at play.
There are 2 things you should do now.
Remove the JavaScript function to submit the form. It's not required (or necessary). The default behavior of a submit button is to... well... submit. You don't need to help it with JavaScript.
Enable error display by using error_reporting(E_ALL).
After you do both things, you should be able to debug and assess the problem much more easily.
Put your php code inside php tags!
<?php
foreach($_POST as $field => $value)
{
echo $field ." = ." $value.'<br />';
}
?>
If you do
<?php
print_r($_POST);
?>
what do you get?
If this still doesn't work, does your server parse php?
Create the file test.php and access it directly http://localhost/test.php or whatever your URL is
<?php
echo 'Hello';
?>
if this doesn't work..it's a whole diferent problem
You can submit an HTML form using PHP with fsubmit library.
Example:
require_once 'fsubmit.php';
$html = "<form action ='res.php' method='post'><input type='text' name='name'/></form>";
$form = new Fsubmit();
$form->url = 'http://submit_url_here.com';
$form->html = $html;
$form->params = ['name'=>'kokainom'];
$response = $form->submit();
echo $response['content'];

Categories