PHP e Avancuar

The PHP date() function is used to format a time and/or date.


The PHP Date() Function

The PHP date() function formats a timestamp to a more readable date and time.

A timestamp is a sequence of characters, denoting the date and/or time at which a certain event occurred.

Syntax

date(format,timestamp)

 

Parameter Description
format Required. Specifies the format of the timestamp
timestamp Optional. Specifies a timestamp. Default is the current date and time

 


PHP Date() – Format the Date

The required format parameter in the date() function specifies how to format the date/time.

Here are some characters that can be used:

  • d – Represents the day of the month (01 to 31)
  • m – Represents a month (01 to 12)
  • Y – Represents a year (in four digits)

A list of all the characters that can be used in the format parameter, can be found in our PHP Date reference.

Other characters, like”/”, “.”, or “-” can also be inserted between the letters to add additional formatting:

<?php
echo date(“Y/m/d”) . “<br />”;
echo date(“Y.m.d”) . “<br />”;
echo date(“Y-m-d”);
?>

The output of the code above could be something like this:

2009/05/11
2009.05.11
2009-05-11

 


PHP Date() – Adding a Timestamp

The optional timestamp parameter in the date() function specifies a timestamp. If you do not specify a timestamp, the current date and time will be used.

The mktime() function returns the Unix timestamp for a date.

The Unix timestamp contains the number of seconds between the Unix Epoch (January 1 1970 00:00:00 GMT) and the time specified.

Syntax for mktime()

mktime(hour,minute,second,month,day,year,is_dst)

To go one day in the future we simply add one to the day argument of mktime():

<?php
$tomorrow = mktime(0,0,0,date(“m”),date(“d”)+1,date(“Y”));
echo “Tomorrow is “.date(“Y/m/d”, $tomorrow);
?>

The output of the code above could be something like this:

Tomorrow is 2009/05/12

 

Server Side Includes (SSI)

You can insert the content of one PHP file into another PHP file before the server executes it, with the include() or require() function.

The two functions are identical in every way, except how they handle errors:

  • include() generates a warning, but the script will continue execution
  • require() generates a fatal error, and the script will stop

These two functions are used to create functions, headers, footers, or elements that will be reused on multiple pages.

Server side includes saves a lot of work. This means that you can create a standard header, footer, or menu file for all your web pages. When the header needs to be updated, you can only update the include file, or when you add a new page to your site, you can simply change the menu file (instead of updating the links on all your web pages).


PHP include() Function

The include() function takes all the content in a specified file and includes it in the current file.

If an error occurs, the include() function generates a warning, but the script will continue execution.

Example 1

Assume that you have a standard header file, called “header.php”. To include the header file in a page, use the include() function:

<html>
<body>

<?php include(“header.php”); ?>
<h1>Welcome to my home page!</h1>
<p>Some text.</p>

</body>
</html>

Example 2

Assume we have a standard menu file, called “menu.php”, that should be used on all pages:

<a href=”/default.php”>Home</a>
<a href=”/tutorials.php”>Tutorials</a>
<a href=”/references.php”>References</a>
<a href=”/examples.php”>Examples</a>
<a href=”/about.php”>About Us</a>
<a href=”/contact.php”>Contact Us</a>

All pages in the Web site should include this menu file. Here is how it can be done:

<html>
<body>

<div>
<?php include(“menu.php”); ?>
</div>

<h1>Welcome to my home page.</h1>
<p>Some text.</p>

</body>
</html>

If you look at the source code of the page above (in a browser), it will look like this:

<html>
<body>

<div>
<a href=”/default.php”>Home</a>
<a href=”/tutorials.php”>Tutorials</a>
<a href=”/references.php”>References</a>
<a href=”/examples.php”>Examples</a>
<a href=”/about.php”>About Us</a>
<a href=”/contact.php”>Contact Us</a>
</div>

<h1>Welcome to my home page!</h1>
<p>Some text.</p>

</body>
</html>

 


PHP require() Function

The require() function is identical to include(), except that it handles errors differently.

If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.

Error Example include() Function

<html>
<body>

<?php
include(“wrongFile.php”);
echo “Hello World!”;
?>

</body>
</html>

Error message:

Warning: include(wrongFile.php) [function.include]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5

Warning: include() [function.include]:
Failed opening ‘wrongFile.php’ for inclusion
(include_path=’.;C:\php5\pear’)
in C:\home\website\test.php on line 5

Hello World!

Notice that the echo statement is executed! This is because a Warning does not stop the script execution.

Error Example require() Function

Now, let’s run the same example with the require() function.

<html>
<body>

<?php
require(“wrongFile.php”);
echo “Hello World!”;
?>

</body>
</html>

Error message:

Warning: require(wrongFile.php) [function.require]:
failed to open stream:
No such file or directory in C:\home\website\test.php on line 5

Fatal error: require() [function.require]:
Failed opening required ‘wrongFile.php’
(include_path=’.;C:\php5\pear’)
in C:\home\website\test.php on line 5

The echo statement is not executed, because the script execution stopped after the fatal error.

It is recommended to use the require() function instead of include(), because scripts should not continue after an error.

The fopen() function is used to open files in PHP.


Opening a File

The fopen() function is used to open files in PHP.

The first parameter of this function contains the name of the file to be opened and the second parameter specifies in which mode the file should be opened:

<html>
<body>

<?php
$file=fopen(“welcome.txt”,”r”);
?>

</body>
</html>

The file may be opened in one of the following modes:

Modes Description
r Read only. Starts at the beginning of the file
r+ Read/Write. Starts at the beginning of the file
w Write only. Opens and clears the contents of file; or creates a new file if it doesn’t exist
w+ Read/Write. Opens and clears the contents of file; or creates a new file if it doesn’t exist
a Append. Opens and writes to the end of the file or creates a new file if it doesn’t exist
a+ Read/Append. Preserves file content by writing to the end of the file
x Write only. Creates a new file. Returns FALSE and an error if file already exists
x+ Read/Write. Creates a new file. Returns FALSE and an error if file already exists

Note: If the fopen() function is unable to open the specified file, it returns 0 (false).

Example

The following example generates a message if the fopen() function is unable to open the specified file:

<html>
<body>

<?php
$file=fopen(“welcome.txt”,”r”) or exit(“Unable to open file!”);
?>

</body>
</html>

 


Closing a File

The fclose() function is used to close an open file:

<?php
$file = fopen(“test.txt”,”r”);

//some code to be executed

fclose($file);
?>

 


Check End-of-file

The feof() function checks if the “end-of-file” (EOF) has been reached.

The feof() function is useful for looping through data of unknown length.

Note: You cannot read from files opened in w, a, and x mode!

if (feof($file)) echo “End of file”;

 


Reading a File Line by Line

The fgets() function is used to read a single line from a file.

Note: After a call to this function the file pointer has moved to the next line.

Example

The example below reads a file line by line, until the end of file is reached:

<?php
$file = fopen(“welcome.txt”, “r”) or exit(“Unable to open file!”);
//Output a line of the file until the end is reached
while(!feof($file))
{
echo fgets($file). “<br />”;
}
fclose($file);
?>

 


Reading a File Character by Character

The fgetc() function is used to read a single character from a file.

Note: After a call to this function the file pointer moves to the next character.

Example

The example below reads a file character by character, until the end of file is reached:

<?php
$file=fopen(“welcome.txt”,”r”) or exit(“Unable to open file!”);
while (!feof($file))
{
echo fgetc($file);
}
fclose($file);
?>

 

With PHP, it is possible to upload files to the server.


Create an Upload-File Form

To allow users to upload files from a form can be very useful.

Look at the following HTML form for uploading files:

<html>
<body>

<form action=”upload_file.php” method=”post”
enctype=”multipart/form-data”>
<label for=”file”>Filename:</label>
<input type=”file” name=”file” id=”file” />
<br />
<input type=”submit” name=”submit” value=”Submit” />
</form>

</body>
</html>

Notice the following about the HTML form above:

  • The enctype attribute of the <form> tag specifies which content-type to use when submitting the form. “multipart/form-data” is used when a form requires binary data, like the contents of a file, to be uploaded
  • The type=”file” attribute of the <input> tag specifies that the input should be processed as a file. For example, when viewed in a browser, there will be a browse-button next to the input field

Note: Allowing users to upload files is a big security risk. Only permit trusted users to perform file uploads.


Create The Upload Script

The “upload_file.php” file contains the code for uploading a file:

<?php
if ($_FILES[“file”][“error”] > 0)
{
echo “Error: ” . $_FILES[“file”][“error”] . “<br />”;
}
else
{
echo “Upload: ” . $_FILES[“file”][“name”] . “<br />”;
echo “Type: ” . $_FILES[“file”][“type”] . “<br />”;
echo “Size: ” . ($_FILES[“file”][“size”] / 1024) . ” Kb<br />”;
echo “Stored in: ” . $_FILES[“file”][“tmp_name”];
}
?>

By using the global PHP $_FILES array you can upload files from a client computer to the remote server.

The first parameter is the form’s input name and the second index can be either “name”, “type”, “size”, “tmp_name” or “error”. Like this:

  • $_FILES[“file”][“name”] – the name of the uploaded file
  • $_FILES[“file”][“type”] – the type of the uploaded file
  • $_FILES[“file”][“size”] – the size in bytes of the uploaded file
  • $_FILES[“file”][“tmp_name”] – the name of the temporary copy of the file stored on the server
  • $_FILES[“file”][“error”] – the error code resulting from the file upload

This is a very simple way of uploading files. For security reasons, you should add restrictions on what the user is allowed to upload.


Restrictions on Upload

In this script we add some restrictions to the file upload. The user may only upload .gif or .jpeg files and the file size must be under 20 kb:

<?php
if ((($_FILES[“file”][“type”] == “image/gif”)
|| ($_FILES[“file”][“type”] == “image/jpeg”)
|| ($_FILES[“file”][“type”] == “image/pjpeg”))
&& ($_FILES[“file”][“size”] < 20000))
{
if ($_FILES[“file”][“error”] > 0)
{
echo “Error: ” . $_FILES[“file”][“error”] . “<br />”;
}
else
{
echo “Upload: ” . $_FILES[“file”][“name”] . “<br />”;
echo “Type: ” . $_FILES[“file”][“type”] . “<br />”;
echo “Size: ” . ($_FILES[“file”][“size”] / 1024) . ” Kb<br />”;
echo “Stored in: ” . $_FILES[“file”][“tmp_name”];
}
}
else
{
echo “Invalid file”;
}
?>

Note: For IE to recognize jpg files the type must be pjpeg, for FireFox it must be jpeg.


Saving the Uploaded File

The examples above create a temporary copy of the uploaded files in the PHP temp folder on the server.

The temporary copied files disappears when the script ends. To store the uploaded file we need to copy it to a different location:

<?php
if ((($_FILES[“file”][“type”] == “image/gif”)
|| ($_FILES[“file”][“type”] == “image/jpeg”)
|| ($_FILES[“file”][“type”] == “image/pjpeg”))
&& ($_FILES[“file”][“size”] < 20000))
{
if ($_FILES[“file”][“error”] > 0)
{
echo “Return Code: ” . $_FILES[“file”][“error”] . “<br />”;
}
else
{
echo “Upload: ” . $_FILES[“file”][“name”] . “<br />”;
echo “Type: ” . $_FILES[“file”][“type”] . “<br />”;
echo “Size: ” . ($_FILES[“file”][“size”] / 1024) . ” Kb<br />”;
echo “Temp file: ” . $_FILES[“file”][“tmp_name”] . “<br />”;

if (file_exists(“upload/” . $_FILES[“file”][“name”]))
{
echo $_FILES[“file”][“name”] . ” already exists. “;
}
else
{
move_uploaded_file($_FILES[“file”][“tmp_name”],
“upload/” . $_FILES[“file”][“name”]);
echo “Stored in: ” . “upload/” . $_FILES[“file”][“name”];
}
}
}
else
{
echo “Invalid file”;
}
?>

The script above checks if the file already exists, if it does not, it copies the file to the specified folder.

Note: This example saves the file to a new folder called “upload”

A cookie is often used to identify a user.


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.


How to Create a Cookie?

The setcookie() function is used to set a cookie.

Note: The setcookie() function must appear BEFORE the <html> tag.

Syntax

setcookie(name, value, expire, path, domain);

Example 1

In the example below, we will create a cookie named “user” and assign the value “Alex Porter” to it. We also specify that the cookie should expire after one hour:

<?php
setcookie(“user”, “Alex Porter”, time()+3600);
?>

<html>
…..

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 2

You can also set the expiration time of the cookie in another way. It may be easier than using seconds.

<?php
$expire=time()+60*60*24*30;
setcookie(“user”, “Alex Porter”, $expire);
?>

<html>
…..

In the example above the expiration time is set to a month (60 sec * 60 min * 24 hours * 30 days).


How to Retrieve a Cookie Value?

The PHP $_COOKIE variable is used to retrieve a cookie value.

In the example below, we retrieve the value of the cookie named “user” and display it on a page:

<?php
// Print a cookie
echo $_COOKIE[“user”];

// A way to view all cookies
print_r($_COOKIE);
?>

In the following example we use the isset() function to find out if a cookie has been set:

<html>
<body>

<?php
if (isset($_COOKIE[“user”]))
echo “Welcome ” . $_COOKIE[“user”] . “!<br />”;
else
echo “Welcome guest!<br />”;
?>

</body>
</html>

 


How to Delete a Cookie?

When deleting a cookie you should assure that the expiration date is in the past.

Delete example:

<?php
// set the expiration date to one hour ago
setcookie(“user”, “”, time()-3600);
?>

 


What if a Browser Does NOT Support Cookies?

If your application deals with browsers that do not support cookies, you will have to use other methods to pass information from one page to another in your application. One method is to pass the data through forms (forms and user input are described earlier in this tutorial).

The form below passes the user input to “welcome.php” when the user clicks on the “Submit” button:

<html>
<body>

<form action=”welcome.php” method=”post”>
Name: <input type=”text” name=”name” />
Age: <input type=”text” name=”age” />
<input type=”submit” />
</form>

</body>
</html>

Retrieve the values in the “welcome.php” file like this:

<html>
<body>

Welcome <?php echo $_POST[“name”]; ?>.<br />
You are <?php echo $_POST[“age”]; ?> years old.

</body>
</html>

 

A PHP session variable is used to store information about, or change settings for a user session. Session variables hold information about one single user, and are available to all pages in one application.


PHP Session Variables

When you are working 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 and what you do because the HTTP address doesn’t maintain state.

A PHP session solves this problem by allowing you to store user information on the server for later use (i.e. username, shopping items, etc). However, session information is temporary and will be deleted after the user has left the website. If you need a permanent storage you may want to store the data in a database.

Sessions work by creating a unique id (UID) for each visitor and store variables based on this UID. The UID is either stored in a cookie or is propagated in the URL.


Starting a PHP Session

Before you can store user information in your PHP session, you must first start up the session.

Note: The session_start() function must appear BEFORE the <html> tag:

<?php session_start(); ?>

<html>
<body>

</body>
</html>

The code above will register the user’s session with the server, allow you to start saving user information, and assign a UID for that user’s session.


Storing a Session Variable

The correct way to store and retrieve session variables is to use the PHP $_SESSION variable:

<?php
session_start();
// store session data
$_SESSION[‘views’]=1;
?>

<html>
<body>

<?php
//retrieve session data
echo “Pageviews=”. $_SESSION[‘views’];
?>

</body>
</html>

Output:

Pageviews=1

In the example below, we create a simple page-views counter. The isset() function checks if the “views” variable has already been set. If “views” has been set, we can increment our counter. If “views” doesn’t exist, we create a “views” variable, and set it to 1:

<?php
session_start();

if(isset($_SESSION[‘views’]))
$_SESSION[‘views’]=$_SESSION[‘views’]+1;
else
$_SESSION[‘views’]=1;
echo “Views=”. $_SESSION[‘views’];
?>

 


Destroying a Session

If you wish to delete some session data, you can use the unset() or the session_destroy() function.

The unset() function is used to free the specified session variable:

<?php
unset($_SESSION[‘views’]);
?>

You can also completely destroy the session by calling the session_destroy() function:

<?php
session_destroy();
?>

Note: session_destroy() will reset your session and you will lose all your stored session data.

 

  1. Leave a comment

Leave a comment