-
[PHP] include / requirePHP 2024. 1. 11. 20:06
include /require
스프링부트에서 header 등 여러 곳에서 동시에 사용할 경우 타임리프로 넘겨주듯이 사용.
대부분은 includ를 사용하지만 require 은 반드시 포함되어야 할 경우 사용.
include_once / require_once
한번만 삽입 시킬 경우에만 사용.
(예제)
우선 index 파일에 폼을 메뉴를 생성해보겠습니다.
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>index</title></head><body><nav>메뉴 1 | 메뉴 2 | 메뉴 3 | 메뉴 4</nav>
인덱스 페이지입니다.<!-- if문 예제--><?php$true = 1;if($true){require 'aaa.php'; // requrie 은 조건이 안 맞더라고 삽입 후 실행/ include 는 조건 먼저 검증 후 실행}?></body></html>그러고 나서 about 이라는 php 파일을 생성합니다.
<!DOCTYPE html><html lang="ko"><head><meta charset="UTF-8"><title>About</title></head><body><nav>메뉴 1 | 메뉴 2 | 메뉴 3</nav>About 페이지입니다.</body></html>여기서 index 파일과 about 파일에 동일한 메뉴를 이용해 한번에 변경/ 적용하고 싶을 경우
include 와 require 을 사용합니다.
- 변경된 index
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>index</title></head><body><!--include : 스프링부트에서 header 등 여러 곳에서 동시에 사용할 경우 타임리프로 넘겨주듯이 사용대부분은 includ를 사용하지만 require 은 반드시 포함되어야 할 경우 사용
include_once 한번만 삽입 시킬 경우에만 사용.i--><?php include 'menu.php'; ?>
인덱스 페이지입니다.<!-- if문 예제--><?php$true = 1;if($true){require 'aaa.php'; // requrie 은 조건이 안 맞더라고 삽입 후 실행/ include 는 조건 먼저 검증 후 실행}?></body></html>- 변경된 about
<!DOCTYPE html><html lang="ko"><head><meta charset="UTF-8"><title>About</title></head><body><?php include 'menu.php'; ?>About 페이지입니다.</body></html>그 후 menu.php 를 만듭니다.
- menu.php
<nav>메뉴 1 | 메뉴 2 | 메뉴 3 | 메뉴 4</nav>이렇게 하고 서버 접속하면 동일하게 변경/적용 되는 것을 확인 할 수 있습니다.
include 와 require 차이
에러 발생 시
include : 경고(Warining)만 표시하고 계속
require : 스크립트 실행 오류(Fatal error)를 발생시키고 스크립트를 중단시킴
'PHP' 카테고리의 다른 글
[PHP] 파일의 절대위치 감출 때 유용한 readfile 함수 (0) 2024.01.11 [PHP] 파일 업로드 (1) 2024.01.11 [PHP] date (0) 2024.01.11 [PHP] 정규표현식 2 (0) 2024.01.11 [PHP] 정규표현식 (1) 2024.01.05