tags:

views:

869

answers:

4

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.

+6  A: 

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 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.

Paolo Bergantino
Upvoted this, but see my note attached to the question about printing values from GET/POST data.
Rob
Sigh. Yeah, yeah, I know. I can only say it so many times in answers here until I stop caring. Edited to reflect this.
Paolo Bergantino
+1  A: 

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

Greg
A: 

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.

empi
+1  A: 

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.

Kristian Lunde