Category Archives: PHP

PHP Form Example |Forms – Validate E-mail and URL |Forms – Required Fields |Form Validation

  • This chapter shows how to keep the values in the input fields when the user hits the submit button.

PHP – Keep The Values in The Form :

  • To show the values in the input fields after the user hits the submit button, we add a little PHP script inside the value attribute of the following input fields: name, email, and website. In the comment textarea field, we put the script between the <textarea> and </textarea> tags. The little script outputs the value of the $name, $email, $website, and $comment variables.
  • Then, we also need to show which radio button that was checked. For this, we must manipulate the checked attribute (not the value attribute for radio buttons):
Name: <input type="text" name="name" value="<?php echo $name;?>">E-mail: <input type="text" name="email" value="<?php echo $email;?>">

Website: <input type="text" name="website" value="<?php echo $website;?>">

Comment: <textarea name="comment" rows="5" cols="40"><?php echo $comment;?></textarea>

<strong>Gender:</strong>

</div>
<div><input type="radio" name="gender"
<?php if (isset($gender) && $gender=="female") echo "checked";?>
value="female">Female
<input type="radio" name="gender"
<?php if (isset($gender) && $gender=="male") echo "checked";?>
value="male">Male

PHP – Complete Form Example :

  • ¬†Here is the complete code for the PHP Form Validation Example:

Forms РValidate E-mail and URL  :

  • This chapter shows how to validate names, e-mails, and URLs.

PHP – Validate Name :

  • The code below shows a simple way to check if the name field only contains letters and whitespace. If the value of the name field is not valid, then store an error message:
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}

PHP – Validate E-mail :

  • The easiest and safest way to check whether an email address is well-formed is to use PHP’s filter_var() function.
  • In the code below, if the e-mail address is not well-formed, then store an error message:
$email = test_input($_POST["email"]);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}

PHP – Validate URL :

  • The code below shows a way to check if a URL address syntax is valid (this regular expression also allows dashes in the URL). If the URL address syntax is not valid, then store an error message:
$website = test_input($_POST["website"]);
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}

PHP – Validate Name, E-mail, and URL :

  • Now, the script looks like this:

Example :

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
$nameErr = "Only letters and white space allowed";
}
}

if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emailErr = "Invalid email format";
}
}

if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
// check if URL address syntax is valid (this regular expression also allows dashes in the URL)
if (!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) {
$websiteErr = "Invalid URL";
}
}

if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}

if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>

Forms – Required Fields :

  • This chapter shows how to make input fields required and create error messages if needed.

PHP – Required Fields :

  • From the validation rules table on the previous page, we see that the “Name”, “E-mail”, and “Gender” fields are required. These fields cannot be empty and must be filled out in the HTML form.
Field Validation Rules
Name Required. + Must only contain letters and whitespace
E-mail Required. + Must contain a valid email address (with @ and .)
Website Optional. If present, it must contain a valid URL
Comment Optional. Multi-line input field (textarea)
Gender Required. Must select one
  • In the previous chapter, all input fields were optional.
  • In the following code we have added some new variables: $nameErr, $emailErr, $genderErr, and $websiteErr. These error variables will hold error messages for the required fields. We have also added an if else statement for each $_POST variable. This checks if the $_POST variable is empty (with the PHP empty() function). If it is empty, an error message is stored in the different error variables, and if it is not empty, it sends the user input data through the test_input() function:
<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $websiteErr = "";
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$nameErr = "Name is required";
} else {
$name = test_input($_POST["name"]);
}

if (empty($_POST["email"])) {
$emailErr = "Email is required";
} else {
$email = test_input($_POST["email"]);
}

if (empty($_POST["website"])) {
$website = "";
} else {
$website = test_input($_POST["website"]);
}

if (empty($_POST["comment"])) {
$comment = "";
} else {
$comment = test_input($_POST["comment"]);
}

if (empty($_POST["gender"])) {
$genderErr = "Gender is required";
} else {
$gender = test_input($_POST["gender"]);
}
}
?>

PHP – Display The Error Messages :

  • Then in the HTML form, we add a little script after each required field, which generates the correct error message if needed (that is if the user tries to submit the form without filling out the required fields):

Example :

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
E-mail:
<input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
Website:
<input type="text" name="website">
<span class="error"><?php echo $websiteErr;?></span>
<br><br>
<label>Comment: <textarea name="comment" rows="5" cols="40"></textarea>
<br><br>
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male
<span class="error">* <?php echo $genderErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">

</form>

Form Validation :

  • This and the next chapters show how to use PHP to validate form data.

PHP Form Validation :

  • The HTML form we will be working at in these chapters, contains various input fields: required and optional text fields, radio buttons, and a submit button:
  • The validation rules for the form above are as follows:
Field Validation Rules
Name Required. + Must only contain letters and whitespace
E-mail Required. + Must contain a valid email address (with @ and .)
Website Optional. If present, it must contain a valid URL
Comment Optional. Multi-line input field (textarea)
Gender Required. Must select one
  • First we will look at the plain HTML code for the form:

Text Fields :

  • The name, email, and website fields are text input elements, and the comment field is a textarea. The HTML code looks like this:
[]phpName: <input type=”text” name=”name”>
E-mail: <input type=”text” name=”email”>
Website: <input type=”text” name=”website”>
Comment: <textarea name=”comment” rows=”5″ cols=”40″></textarea>[/php]

Radio Buttons :

  • The gender fields are radio buttons and the HTML code looks like this:
Gender:
<input type="radio" name="gender" value="female">Female
<input type="radio" name="gender" value="male">Male

The Form Element :

  • The HTML code of the form looks like this:
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

Big Note on PHP Form Security :

  • The $_SERVER[“PHP_SELF”] variable can be used by hackers!
  • 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.
  • Assume we have the following form in a page named “test_form.php”:
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
  • Now, if a user enters the normal URL in the address bar like
  • “http://www.example.com/test_form.php”, the above code will be translated to:
<form method="post" action="test_form.php">

So far, so good.

  • However, consider that a user enters the following URL in the address bar:
http://www.example.com/test_form.php/%22%3E%3Cscript%3Ealert(‘hacked’)%3C/script%3E

In this case, the above code will be translated to:

<form method="post" action="test_form.php/"><script>alert('hacked')</script>
  • This code adds a script tag and an alert command. And when the page loads, the JavaScript code will be executed (the user will see an alert box). This is just a simple and harmless example how the PHP_SELF variable can be exploited.
  • Be aware of that any JavaScript code can be added inside the <script> tag! A hacker can redirect the user to a file on another server, and that file can hold malicious code that can alter the global variables or submit the form to another address to save the user data, for example.

How To Avoid $_SERVER[“PHP_SELF”] Exploits? :

  • $_SERVER[“PHP_SELF”] exploits can be avoided by using the htmlspecialchars() function.

The form code should look like this:

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
  • The htmlspecialchars() function converts special characters to HTML entities. Now if the user tries to exploit the PHP_SELF variable, it will result in the following output:
<form method="post" action="test_form.php/&quot;&gt;&lt;script&gt;alert('hacked')&lt;/script&gt;">

The exploit attempt fails, and no harm is done!

Validate Form Data With PHP :

  • The first thing we will do is to pass all variables through PHP’s htmlspecialchars() function.
  • When we use the htmlspecialchars() function; then if a user tries to submit the following in a text field:
<script>location.href('http://www.hacked.com')</script>
  • We will also do two more things when the user submits the form:
  • The code is now safe to be displayed on a page or inside an e-mail.
  • &lt;script&gt;location.href(‘http://www.hacked.com’)&lt;/script&gt;
  • - this would not be executed, because it would be saved as HTML escaped code, like this:
  • Strip unnecessary characters (extra space, tab, newline) from the user input data (with the PHP trim() function)
  • Remove backslashes (\) from the user input data (with the PHP stripslashes() function)
  • The next step is to create a function that will do all the checking for us (which is much more convenient than writing the same code over and over again).
  • We will name the function test_input().
  • Now, we can check each $_POST variable with the test_input() function, and the script looks like this:

Example :

<?php
// define variables and set to empty values
$name = $email = $gender = $comment = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = test_input($_POST["name"]);
$email = test_input($_POST["email"]);
$website = test_input($_POST["website"]);
$comment = test_input($_POST["comment"]);
$gender = test_input($_POST["gender"]);
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

 

Libxml Functions in PHP

PHP libxml Introduction :

  • The libxml functions and constants are used together with SimpleXML, XSLT and DOM functions.

Installation :

These functions require the libxml package. Download at xmlsoft.org

PHP libxml Functions :

  • PHP: indicates the earliest version of PHP that supports the function.
Function Description
libxml_clear_errors() Clear libxml error buffer
libxml_get_errors() Retrieve array of errors
libxml_get_last_error() Retrieve last error from libxml
libxml_set_streams_context() Set the streams context for the next libxml document load or write
libxml_use_internal_errors() Disable libxml errors and allow user to fetch error information as needed

PHP 5 Predefined libxml Constants :

Function Description
LIBXML_COMPACT Set small nodes allocation optimization. This may improve the application performance
LIBXML_DTDATTR Set default DTD attributes
LIBXML_DTDLOAD Load external subset
LIBXML_DTDVALID Validate with the DTD
LIBXML_NOBLANKS Remove blank nodes
LIBXML_NOCDATA Set CDATA as text nodes
LIBXML_NOEMPTYTAG Change empty tags (e.g. <br/> to <br></br>), only available in the DOMDocument->save() and DOMDocument->saveXML() functions
LIBXML_NOENT Substitute entities
LIBXML_NOERROR Do not show error reports
LIBXML_NONET Stop network access while loading documents
LIBXML_NOWARNING Do not show warning reports
LIBXML_NOXMLDECL Drop the XML declaration when saving a document
LIBXML_NSCLEAN Remove excess namespace declarations
LIBXML_XINCLUDE Use XInclude substitution
LIBXML_ERR_ERROR Get recoverable errors
LIBXML_ERR_FATAL Get fatal errors
LIBXML_ERR_NONE Get no errors
LIBXML_ERR_WARNING Get simple warnings
LIBXML_VERSION Get libxml version (e.g. 20605 or 20617)
LIBXML_DOTTED_VERSION Get dotted libxml version (e.g. 2.6.5 or 2.6.17)

What is a PHP Session? |Example

PHP 5 Sessions :

  • A session is a way to store information (in variables) to be used across multiple pages.
  • Unlike a cookie, the information is not stored on the users computer.

What is a PHP Session?

  • When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. The computer knows who you are. It knows when you start the application and when you end. But on the internet there is one problem: the web server does not know who you are or what you do, because the HTTP address doesn’t maintain state.
  • Session variables solve this problem by storing user information to be used across multiple pages (e.g. username, favorite color, etc). By default, session variables last until the user closes the browser.
  • So; Session variables hold information about one single user, and are available to all pages in one application.

Start a PHP Session :

  • A session is started with the session_start() function.
  • Session variables are set with the PHP global variable: $_SESSION.
  • Now, let’s create a new page called “demo_session1.php”. In this page, we start a new PHP session and set some session variables:

Example :

<?php
// Start the session
session_start();
?></span>
<!DOCTYPE html>
<html>
<body>

<span style="color: #ff0000;"><?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?></span>

</body>
</html>

Get PHP Session Variable Values :

  • Next, we create another page called “demo_session2.php”. From this page, we will access the session information we set on the first page (“demo_session1.php”).
  • Notice that session variables are not passed individually to each new page, instead they are retrieved from the session we open at the beginning of each page (session_start()).
  • Also notice that all session variable values are stored in the global $_SESSION variable:

Example :

<?php
session_start();
?></span>
<!DOCTYPE html>
<html>
<body>

<span style="color: #ff0000;"><?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?></span>

</body>
</html>

Another way to show all the session variable values for a user session is to run the following code:

Example :

<?php
session_start();
?></span>
<!DOCTYPE html>
<html>
<body>

<span style="color: #ff0000;"><?php
print_r($_SESSION);
?></span>

</body>
</html>

Modify a PHP Session Variable :

  • To change a session variable, just overwrite it:

Example :

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// to change a session variable, just overwrite it
$_SESSION["favcolor"] = "yellow";
print_r($_SESSION);
?>

</body>
</html>

Destroy a PHP Session :

  • To remove all global session variables and destroy the session, use session_unset() and session_destroy():

Example :

<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>

<?php
// remove all session variables
session_unset();

// destroy the session
session_destroy();
?>

</body>
</html>
1 2 3 7