Combining HTML and PHP Code on a Single Page
- Write PHP code with HTML code on a single page as on hard copy.
- More flexibility to write the entire page dynamically.
- For this use a PHP_SELF variable is in the action field of the <form> tag.
- The action field of the FORM instructs where to submit the form data when the user presses the “submit” button.
- The same PHP page as the handler for the form as well.
- The action field of form use to switch to control to other page but Using PHP_SELF variable do not need to edit the action field.
Example:-
A file called form-abcd.php and want to load the same page after the form is submitted.
<form method="post" action="abcd.php" >
We can use the PHP_SELF variable instead of “abcd.php”.
The code becomes:
<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >
Example :-
<?php
if(isset($_POST['submit']))
{
$name = $_POST['name'];
echo "User Has submitted the form and entered this name : <b> $name </b>";
echo "<br>You can use the following form again to enter a new name.";
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name"><br>
<input type="submit" name="submit" value="Submit Form"><br>
</form>
- This PHP code is above the HTML part and will be executed first.
- The first line of code is checking if the form is submitted or not.
- The name of the submit button is “submit”.
- When the submit button is pressed the $_POST['submit'] will be set and the IF condition will become true.
- It is showing the name entered by the user.
- If the form is not submitted the IF condition will be FALSE as there will be no values in $_POST['submit'] and PHP code will not be executed.
- In this case, only the form will be shown.
- The PHP_SELF variable is used to get the name and path of the current file but it can be used by the hackers too.
- If PHP_SELF is used in your page then a user can enter a slash (/) and then some Cross Site Scripting (XSS) commands to execute.
- PHP_SELF exploits can be avoided by using the htmlentities() function.
Syntax:-
<form name="test" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
The htmlentities() function encodes the HTML entities. Now if the user tries to exploit the PHP_SELF variable, the attempt will fail and the result of entering malicious code in URL will result in the following output:
<form name="test" method="post"
action="form-action.php/"><script>alert('xss')&
lt;/script><foo">
=================================================
0 Comments