LoginSignup
0
0

More than 1 year has passed since last update.

外部ファイルを読み込む

Last updated at Posted at 2023-04-28

概要

PHPで外部のファイルを読み込む。

手順

下記のようなディレクトリを想定。html配下のmain.phpから、template配下のtemplate.phpを読み込む。

html
└ main.php
template
└ template.php

ターミナルからrootディレクトリにhtmlフォルダを指定し、main.phpを読み込む。
例えば、Localhostであれば、ブラウザで 「http://localhost:8080/main.php」を叩く。

main.php
<?php
    include __DIR__.'/../template/template.php';
?>

include('ファイル名')で読み込みたいファイルを指定。__DIR__そのファイルがあるディレクトリを示し、/../でその一つ上の階層、その階層のtemplateフォルダ以下の「template.php」を読み込んでいる。

例えば、template.phpに下記のようなhtmlを記載。

template.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    "Hi!"
</body>
</html>

ブラウザで 「http://localhost:8080/main.php」を叩くと、

スクリーンショット 2023-04-28 22.20.04.png

表示されました。

ちなみに似たようなことができるrequireというのがあるが、違いは下記。

require = エラーが出てもその後の処理を継続
include = エラーが出たら処理を中止

エラー発生時に後続処理に影響するかしないかで使い分けるようです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0