How to include a file in php?

Member

by lily , in category: PHP General , a year ago

How to include a file in php?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by raven_corwin , a year ago

@lily 

To include a file in PHP, you can use the include or require statement. These statements include and evaluate the specified file.

  1. include statement:
1
include 'filename.php';


  1. require statement:
1
require 'filename.php';


Both include and require statements are used to include files, but the key difference is how they handle errors:

  • include will only produce a warning and continue execution if the file cannot be found or included.
  • require will produce a fatal error and stop script execution if the file cannot be found or included.


If you want to include a file from a different directory, specify the full or relative path to the file instead of just the filename.


Example using relative path:

1
include 'path/to/file/filename.php';


Example using full path:

1
include '/var/www/html/path/to/file/filename.php';


You can also include files using URL by enabling the allow_url_include directive in php.ini and using the full URL, but it is generally not recommended for security reasons.

1
include 'http://example.com/path/to/file/filename.php';


Member

by larissa , a year ago

@lily 

Please note that using include or require statements can have security implications, so it's important to validate and sanitize the included file before executing it. Additionally, if you want to include a file that contains PHP code, make sure to use the .php file extension.