When you use header
, you can't output anything in the document's body, making any alert()
ing impossible.
A often used trick to achieve this is to delegate the alert()
ing to the target page:
header( 'Location: http://localhost/assignment/WebForm.htm?alert='.
urlencode("Hello!")) ;
and then in WebForm.htm:
<?php if (isset($_GET["alert"])): ?>
<script type="text/javascript">
alert("<?php echo htmlentities(urldecode($_GET["alert"])); ?>");
</script>
<?php endif; ?>
just remember to htmlentities()
the output when outputting the message.
If you are already using sessions, for 100% security and elegant URLs, you could also generate a random key in PHP using rand
, store the message in $_SESSION["message_$randomKey"]
and pass the key in the GET request. That way, the only thing the user sees in the URL is the key, and not the message.