There's also one more way using a query string, as follows:
<?php
if ( isset($_SERVER['QUERY_STRING']) && $_SERVER['QUERY_STRING'] != null ) {
$qs = htmlentities($_SERVER['QUERY_STRING']);
list(,$ans) = explode("=",$qs);
if ($ans) {
echo "Your answer is $ans. ";
}
exit("Thank you");
}
?>
You could put the PHP code at the top of a web page, followed by HTML which contains the following JavaScript:
<script>
var ans = false;
if( ans = confirm("Are you sure?")) {
this.location += "?answer=" + ans;
}
else
{
document.write("Action cancelled since you seem unsure");
}
</script>
While Ajax is certainly elegant, dynamically generating a query string containing the variable is a viable option as well. If desired, you could POST the query string to another page without hard-coding a form by taking advantage of stream_context_create(), as follows:
<?php
error_reporting(E_ALL);
if ( isset($_SERVER['QUERY_STRING']) && ($_SERVER['QUERY_STRING'] != NULL))
{
$url = 'http://www.example.com/some_page.php';
$qs = htmlentities($_SERVER['QUERY_STRING']);
list($key,$value) = explode("=",$qs);
$arr = array($key => $value);
$options = array(
'http'=>array(
'method'=>"POST",
'header'=>
"Accept-language: en\r\n".
"Content-type: application/x-www-form-urlencoded\r\n",
'content'=>http_build_query( $arr )
));
$context = stream_context_create($options);
$fp=fopen($url,'rb',false,$context);
fpassthru($fp);
fclose($fp);
exit;
}
?>
At the desired url, you would just need to add a script that displays the content, such as:
<?php
var_dump($_POST['answer']);