Unit 4 PHP
Unit 4 PHP
The PHP superglobals $_GET and $_POST are used to collect form-data.
<!DOCTYPE HTML>
<html>
<body>
</body>
</html>
Name:
E-mail:
Submit
When the user fills out the form above and clicks the submit button, the form
data is sent for processing to a PHP file named "welcome.php". The form data is
sent with the HTTP POST method.
To display the submitted data you could simply echo all the variables.
<html>
<body>
</html>
Welcome John
The same result could also be achieved using the HTTP GET method:
Example
Same example, but the method is set to GET instead of POST:
<html>
<body>
<input type="submit">
</form>
</body>
</html>
<html>
<body>
</html>
The code above is quite simple, and it does not include any validation.
You need to validate form data to protect your script from malicious code.
This page does not contain any form validation, it just shows how you can send
and retrieve form data.
Both GET and POST are treated as $_GET and $_POST. These are superglobals,
which means that they are always accessible, regardless of scope - and you
can access them from any function, class or file without having to do anything
special.
$_GET is an array of variables passed to the current script via the URL
parameters.
$_POST is an array of variables passed to the current script via the HTTP POST
method.
GET also has limits on the amount of information to send. The limitation is about
2000 characters.
Note: GET should NEVER be used for sending passwords or other sensitive
information!
However, because the variables are not displayed in the URL, it is not possible
to bookmark the page.
Name: *
E-mail: *
Website:
Comment:
Gender: Female Male Other *
Submit
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.
Radio Buttons
The gender fields are radio buttons and the HTML code looks like this:
Gender:
When the form is submitted, the form data is sent with method="post".
So, the $_SERVER["PHP_SELF"] sends the submitted form data to the page
itself, instead of jumping to a different page. This way, the user will get error
messages on the same page as the form.
<script>location.href('http://www.hacked.com')</script>
- this would not be executed, because it would be saved as HTML escaped code,
like this:
<script>location.href('http://www.hacked.com')</script>
We will also do two more things when the user submits the form:
1. Strip unnecessary characters (extra space, tab, newline) from the user
input data (with the PHP trim() function)
2. Remove backslashes \ from the user input data (with the
PHP stripslashes() function)
3. 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).
4. We will name the function test_input().
5. Now, we can check each $_POST variable with
the test_input() function, and the script looks like this:
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
} else {
$name = test_input($_POST["name"]);
if (empty($_POST["email"])) {
$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"])) {
} else {
$gender = test_input($_POST["gender"]);
<br><br>
E-mail:
<br><br>
Website:
<br><br>
<br><br>
Gender:
<br><br>
</form>
The next step is to validate the input data, that is "Does the Name field contain
only letters and whitespace?", and "Does the E-mail field contain a valid e-mail
address syntax?", and if filled out, "Does the Website field contain a valid URL?".
$name = test_input($_POST["name"]);
if (!preg_match("/^[a-zA-Z-' ]*$/",$name)) {
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)) {
Unit 4
What is a Cookie?
A cookie is often used to identify a user. A cookie is a small file that the server
embeds on the user's computer. Each time the same computer requests a page
with a browser, it will send the cookie too. With PHP, you can both create and
retrieve cookie values.
Syntax
setcookie(name, value, expire, path, domain, secure, httponly);
Only the name parameter is required. All other parameters are optional.
We then retrieve the value of the cookie "user" (using the global variable
$_COOKIE). We also use the isset() function to find out if the cookie is set:
Example
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() +
(86400 * 30), "/"); // 86400 = 1 day
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Note: The setcookie() function must appear BEFORE the <html> tag.
Note: The value of the cookie is automatically URLencoded when sending the
cookie, and automatically decoded when received (to prevent URLencoding,
use setrawcookie() instead).
Example
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>
<html>
<body>
<?php
if(!isset($_COOKIE[$cookie_name])) {
echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
echo "Cookie '" . $cookie_name . "' is set!<br>";
echo "Value is: " . $_COOKIE[$cookie_name];
}
?>
</body>
</html>
Delete a Cookie
To delete a cookie, use the setcookie() function with an expiration date in the
past:
Example
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
PHP Sessions
A session is a way to store information (in variables) to be used across
multiple pages.
So; Session variables hold information about one single user, and are available
to all pages in one application.
Tip: If you need a permanent storage, you may want to store the data in
a database.
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();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Set session variables
$_SESSION["favcolor"] = "green";
$_SESSION["favanimal"] = "cat";
echo "Session variables are set.";
?>
</body>
</html>
Note: The session_start() function must be the very first thing in your
document. Before any HTML tags.
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();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// Echo session variables that were set on previous page
echo "Favorite color is " . $_SESSION["favcolor"] . ".<br>";
echo "Favorite animal is " . $_SESSION["favanimal"] . ".";
?>
</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();
?>
<!DOCTYPE html>
<html>
<body>
<?php
print_r($_SESSION);
?>
</body>
</html>
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>
Example
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<body>
<?php
// remove all session variables
session_unset();
</body>
</html>
SENDING EMAILS:
<?php
// the message
$msg = "First line of text\nSecond line of text";
// send email
mail("[email protected]","My subject",$msg);
?>
Syntax
mail(to,subject,message,headers,parameters);
Parameter Values
Parameter Description
headers Optional. Specifies additional headers, like From, Cc, and Bcc.
The additional headers should be separated with a CRLF (\r\n).