Php define include once

PHP include_once

Summary: in this tutorial, you will learn how to use the PHP include_once construct to include a file once.

Introduction to the PHP include_once construct

In the include tutorial, you learned how to load the code from another file using the include construct.

Sometimes, you may have a file that is included more than once.

If the included file has a function, you’ll get a fatal error because the function is already redeclared in the first load. For example:

Suppose that you have the following project directory:

. ├── inc │ └── functions.php └── index.phpCode language: plaintext (plaintext)

The functions.php has the dd() function definition:

 function dd($data) < echo '
'; var_dump($data); echo '

'; die(); >Code language: HTML, XML (xml)

And in the index.php file , you include the functions.php file twice:

 include 'inc/functions.php'; include 'inc/functions.php';Code language: HTML, XML (xml)

PHP will issue the following error if you run the index.php file:

Fatal error: Cannot redeclare dd() (previously declared in .\inc\functions.php:3) in .\inc\functions.php on line 3Code language: plaintext (plaintext)

Likewise, if the included file outputs some HTML elements, you’ll see them more once on the page. To see how it happens, let’s create two new files header.php and footer.php in the inc directory:

html> html lang="en"> head> meta charset="UTF-8" /> meta name="viewport" content="width=device-width, initial-scale=1.0" /> title>PHP include_once title> head> body>Code language: HTML, XML (xml)
 body> html>Code language: HTML, XML (xml)

In the index.php file, if you include the header.php file twice, you’ll see that the page will have two headers:

 include 'inc/header.php' ?>  include 'inc/header.php' ?> h1>PHP include_once Demo h1>  include 'inc/footer.php' ?>Code language: HTML, XML (xml)

To avoid including a file more than once, you can use the include_once statement:

include_once 'path_to_file';Code language: PHP (php)

The include_once behaves like the include statement except that if the file is included again, the include_once won’t load the file and returns true .

Simply put, the include_once loads the file just once regardless of how many times the file is included.

In the example above, if you use the include_once construct, the script will work properly:

 include_once 'inc/header.php' ?>  include_once 'inc/header.php' ?> h1>PHP include_once Demo h1>  include_once 'inc/footer.php' ?>Code language: HTML, XML (xml)

Why use the PHP include_once construct

Image that you have a file called index.php that loads two other files:

The Database.php file also loads the Logger.php file. In this case, the Logger.php file is used twice, once in the Database.php file and another in the index.php .

In this case, you need to use the include_once construct to load the Logger.php file to make it work properly.

Summary

Источник

PHP require_once(), include_once()

require_once() statement can be used to include a php file in another one, when you may need to include the called file more than once. If it is found that the file has already been included, calling script is going to ignore further inclusions.

If a.php is a php script calling b.php with require_once() statement, and does not find b.php, a.php stops executes causing a fatal error.

require_once('name of the calling file with path');

The above file x.php, is included twice with require_once() statement in the following file y.php. But from the output you will get that the second instance of inclusion is ignored, since require_once() statement ignores all the similar inclusions after the first one.

If a calling script does not find a called script with the require_once statement, it halts the execution of the calling script.

PHP include_once()

Description

The include_once() statement can be used to include a php file in another one, when you may need to include the called file more than once. If it is found that the file has already been included, calling script is going to ignore further inclusions.

If a.php is a php script calling b.php with include_once() statement, and does not find b.php, a.php executes with a warning, excluding the part of the code written within b.php.

include_once('name of the called file with path');

The above file x.php, is included twice with include_once() statement in the following file y.php. But from the output you will get that the second instance of inclusion is ignored, since include_once() statement ignores all the similar inclusions after the first one.

If a calling script does not find a called script with the include_once statement, it halts the execution of the calling script.

Follow us on Facebook and Twitter for latest update.

PHP: Tips of the Day

How do I expire a PHP session after 30 minutes?

You should implement a session timeout of your own. Both options mentioned by others (session.gc_maxlifetime and session.cookie_lifetime) are not reliable. I’ll explain the reasons for that.

session.gc_maxlifetime

session.gc_maxlifetime specifies the number of seconds after which data will be seen as ‘garbage’ and cleaned up. Garbage collection occurs during session start.

But the garbage collector is only started with a probability of session.gc_probability divided by session.gc_divisor. And using the default values for those options (1 and 100 respectively), the chance is only at 1%.

Well, you could simply adjust these values so that the garbage collector is started more often. But when the garbage collector is started, it will check the validity for every registered session. And that is cost-intensive.

Furthermore, when using PHP’s default session.save_handler files, the session data is stored in files in a path specified in session.save_path. With that session handler, the age of the session data is calculated on the file’s last modification date and not the last access date:

Note: If you are using the default file-based session handler, your filesystem must keep track of access times (atime). Windows FAT does not so you will have to come up with another way to handle garbage collecting your session if you are stuck with a FAT filesystem or any other filesystem where atime tracking is not available. Since PHP 4.2.3 it has used mtime (modified date) instead of atime. So, you won’t have problems with filesystems where atime tracking is not available.

So it additionally might occur that a session data file is deleted while the session itself is still considered as valid because the session data was not updated recently.

session.cookie_lifetime

session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. [�]

Yes, that’s right. This only affects the cookie lifetime and the session itself may still be valid. But it’s the server’s task to invalidate a session, not the client. So this doesn’t help anything. In fact, having session.cookie_lifetime set to 0 would make the session�s cookie a real session cookie that is only valid until the browser is closed.

Conclusion / best solution:

The best solution is to implement a session timeout of your own. Use a simple time stamp that denotes the time of the last activity (i.e. request) and update it with every request:

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) < // last request was more than 30 minutes ago session_unset(); // unset $_SESSION variable for the run-time session_destroy(); // destroy session data in storage >$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp

Updating the session data with every request also changes the session file’s modification date so that the session is not removed by the garbage collector prematurely.

You can also use an additional time stamp to regenerate the session ID periodically to avoid attacks on sessions like session fixation:

if (!isset($_SESSION['CREATED'])) < $_SESSION['CREATED'] = time(); >else if (time() - $_SESSION['CREATED'] > 1800) < // session started more than 30 minutes ago session_regenerate_id(true); // change session ID for the current session and invalidate old session ID $_SESSION['CREATED'] = time(); // update creation time >
  • session.gc_maxlifetime should be at least equal to the lifetime of this custom expiration handler (1800 in this example);
  • if you want to expire the session after 30 minutes of activity instead of after 30 minutes since start, you’ll also need to use setcookie with an expire of time()+60*30 to keep the session cookie active.
  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

Читайте также:  Закрепить объект в css
Оцените статью