Php include read file

PHP Include

Summary: in this tutorial, you will learn how to include code from a file using the PHP include construct.

Introduction to the PHP include construct

The include construct allows you to load the code from another file into a file. Here’s the syntax of the include construct:

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

In this syntax, you place the path to the file after the include keyword. For example, to load the code from the functions.php file into the index.php file, you can use the following include statement:

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

If PHP cannot find the ‘functions.php’ file in the src directory, it’ll issue a warning. For example:

Warning: include(functions.php): failed to open stream: No such file or directory in . on line 4 Warning: include(): Failed opening 'functions.php' for inclusion (include_path='\xampp\php\PEAR') in . on line 4Code language: PHP (php)

When loading the functions.php file, PHP first looks for the functions.php file in the directory specified by the include_path . In this example, it’s ‘\xampp\php\PEAR’ . If PHP can find the functions.php file there, it loads the code from the file.

Otherwise, PHP searches the functions.php file in the directory of the calling script and the current working directory. If PHP can find the functions.php file there, it loads the code. Otherwise, it issues a warning if the file doesn’t exist.

When PHP loads the functions.php file, it actually executes the code inside the functions.php file. For example, if you place the following code in the functions.php file:

 // functions.php function get_copyright() < return 'Copyright © ' . date('Y') . ' by phptutorial.net. All Rights Reserved!'; > echo get_copyright(); Code language: HTML, XML (xml)

and include the functions.php in the index.php file, you’ll see the following output when you run the index.php file:

Copyright © 2021 by phptutorial.net. All Rights Reserved!Code language: CSS (css)

This demonstrated that the include construct does make PHP executes code in the functions.php file.

PHP include example

In practice, you’ll often use the include construct to the page elements from a general site design. For example, all pages in your website may have the same header and footer.

To avoid repeating these elements on multiple pages, you can place the code of the header and footer in separate files such as header.php and footer.php and include them on the pages.

Typically, you place the template files like header.php and footer.php in a separate directory. By convention, the name of the include directory is inc :

. ├── index.php ├── functions.php ├── inc │ ├── footer.php │ └── header.php └── public ├── css │ └── style.css └── js └── app.jsCode language: CSS (css)

The header.php file contains the code of the header of the page. It has a link to the style.css file located in the public/css directory:

html> html lang="en"> head> meta charset="UTF-8" /> meta name="viewport" content="width=device-width, initial-scale=1.0" /> link rel="stylesheet" href="public/css/style.css"> title>PHP include Example title> head> body>Code language: HTML, XML (xml)

The footer.php file contains the code related to the footer of the page:

script src="js/app.js"> script> body> html>Code language: HTML, XML (xml)

In the index.php file, you can include the header.php and footer.php file like this:

 include 'inc/header.php'; ?> h1>PHP include h1> p>This shows how the PHP include construct works. p>  include 'inc/footer.php'; ?>Code language: HTML, XML (xml)

If you run the index.php file and view the source code of the page, you’ll also see the code from the header.php and footer.php files:

html> html lang="en"> head> meta charset="UTF-8" /> meta name="viewport" content="width=device-width, initial-scale=1.0" /> link rel="stylesheet" href="public/css/style.css" /> title>PHP include Example title> head> body> h1>PHP include h1> p>This shows how the PHP include construct works. p> script src="public/js/app.js"> script> body> html>Code language: HTML, XML (xml)

PHP include & variable scopes

When you include a file, all the variables defined in that file inherit the variable scope of the line on which the include occurs.

1) Including outside a function example

For example, the following defines the $title and $content variables in the functions.php :

 // functions.php $title = 'PHP include'; $content = 'This shows how the PHP include construct works.';Code language: HTML, XML (xml)

When you include the functions.php in the index.php file, the $title and $content variables become the global variables in the index.php file. And you can use them as follows:

 include 'inc/header.php'; ?>  include_once 'functions.php'; ?> h1> echo $title; ?> h1> p> echo $content; ?> p>  include 'inc/footer.php'; ?>Code language: HTML, XML (xml)

2) Including within a function example

However, if you include a file in a function, the variables from the included file are local to that function. See the following example:

 include 'inc/header.php'; ?>  include_once 'functions.php'; ?>  function render_article() < include 'functions.php'; return " 

$title

$content
"
; > echo render_article(); ?>
include 'inc/footer.php'; ?>
Code language: HTML, XML (xml)

In this example, we include the functions.php inside the render_article() function. Therefore, the $title and $content variables from the functions.php are local to the render_function() .

It’s important to note that all functions, classes, interfaces, and traits defined in the included file will have a global scope.

Summary

Источник

Полезные мелочи программирования на PHP

Язык программирования PHP очень и очень свободный. Из-за этого, к сожалению, есть много способов написать тоже самое и не знать, что можно лучше. В этом топике я опишу несколько мелочей, полезных начинающим и немного продвинутым PHP программистам.

Функциональность

php.net предлагает небольшую статейку о разнице между ними, но она не очень информативна

Функциональная разница между ними только та, что

 ($success) ? echo 'Ура!': echo 'Увы. '; 

Разница не в счёт, поэтому будем говорить о них как об одинаковых конструктах.

Скорость

ничего не возвращает и поэтому чуть-чуть быстрее. Разница в парсинге смешная, но вот что интереснее: «echo» — четыре буквы, лежащие очень удобно под рукой, а «print» — пять, и чуть похуже расположенных.
В скорости

Вывод

Можно много говорить о том, что разница в скорости очень мизерная, но если разницы в функциональности никакой, то зачем использовать

Постройка текста для вывода

Выясняем отношения с кавычками

). Разница между ними очень большая.
В простых кавычках парсер ищет только простую кавычку (как символ конца) и обратный слэш (для ввода простой кавычки). В двойных же парсер умеет многое другое. Например — видеть переменные (

).
Очевидно, что простые кавычки побыстрее, парсеру почти не надо думать. Но самое главное — это читабельность кода. Конструкции в двойных кавычках не только тяжелее воспринимать взглядом, многие редакторы с подсветкой кода их не могут разглядеть (разумеется, такие монстры, как ZDE справляются с этим без проблем, но ведь человек, редактирующий код после Вас может его и не иметь).

Точка или запятая?

В первом случае мы передаём два параметра, во втором один: склееный оператором склейки. Используя точку мы заставляем парсер на время всё схватить в память и склеить, как указывает Wouter Demuynck, поэтому запятые оказываются побыстрее (разумеется, проверено тестами).

heredoc?

В PHP есть конструкция «HEREDOC». Выглядит она так:

 echo Hello, 
world,
I love you!
HEREDOC;

Здесь вместо «HEREDOC» может быть что угодно.

Правда, знать про эту конструкцию нужно только то, что она в десять раз медленее своих коллег, не очень читабельна и поэтому её лучше не использовать.

Конец строки

 define('N',PHP_EOL); echo 'foo' . N;

но это сугубо моё мнение и здесь я не уверен.

Смысл ?>

Мало кто знает, что ставить эту конструкцию в конец файла не надо. Мало того, гораздо лучше, когда его там нет, тогда нету опасности, что там проскочит пробел и разрушит далее посылаемые

 functions.php: 
function foo()
.
>
function bar()
.
>

require, include, readfile

readfile

просто выбрасывает содержимое файла в output. Если вам надо показать меню или баннер, то эта функция — как раз.

include и require

же относится к ошибке спокойно и просто даёт warning, не прерывая выполнения. Вывод — require нужна гораздо чаще.

. _once?

 include_once; require_once 

В таком случае парсер проверит, может он уже эти файлы добавил? Удобно для подключения библиотек в больших проектах. Можно не боясь добавлять

в каждый модуль, где нужна библиотека.

Запись в файл

 file_put_contents('filename','data'); 
 // File put contents if (!defined('FILE_APPEND')) define('FILE_APPEND',1); if (!function_exists('file_put_contents')) < function file_put_contents($n, $d, $flag = false) < $mode = ($flag == FILE_APPEND || strtoupper($flag) == 'FILE_APPEND') ? 'a' : 'w'; $f = @fopen($n, $mode); if ($f === false) < return 0; >else < if (is_array($d)) $d = implode($d); $bytes_written = fwrite($f, $d); fclose($f); return $bytes_written; >> > 

Источник

Читайте также:  This is my page
Оцените статью