1
2

More than 1 year has passed since last update.

【備忘録】.phpから別の.phpを実行する

Last updated at Posted at 2022-04-12

web開発初心者の備忘録です。
ガラパゴスでも自家消費用だからへーきへーき。

ポイント

include関数とrequire関数を使用することで、外部の.phpを参照する事ができる。(.phpに限らずファイルなら何でも読み込める?未検証。)
それぞれの違いは以下の通り。

  • include関数 → ファイルを読み込めなかった際、E_WARNINGを発生させるが、処理は強行する。
  • require関数 → ファイルを読み込めなかった際、E_COMPILE_ERRORを発生させて、処理も止まる。

ファイル構成

IISでルートに設定しているフォルダ
 └ test
   ├ main.html
   ├ main.php
   ├ lib.php
   ├ main.js
   └ jquery-3.6.0.js

ソースコード

main.html
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8"/>
    <title>test</title>

    <script type="text/javascript" src="jquery-3.6.0.js"></script>
    <script type="text/javascript" src="main.js"></script>
</head>

<body>
    <button onclick="hoge()">実行</button>
</body>

<script type="text/javascript" src="main.js"></script>

</html>
main.js
function hoge() {
    $.ajax({
        type: "GET",
        url: "../test/main.php",
        timeout: 5000
    }).done(($data) => {
        console.log("done");
        console.log($data);
    }).fail(($data) => {
        console.log("fail");
        console.log($data);
    }).always(() => {
        console.log("always");
    });
}
main.php
<?php    
    require('lib.php');
    sleep(3);

    echo sample();
?>
lib.php
<?php    
    function sample() {
        return "関数呼び出し成功!!";
    }
?>

結果

スクリーンショット 2022-04-12 230050.jpg
いいね

最後に

ヘッダファイルっぽく書けるようになり、遺伝子に刻み込まれたC言語も喜んでいます。

  • 初学者の備忘録です。
  • 片手間でやっているので、記述が曖昧&雑です。
  • 動作したコードをそのまま載せていますが、摩訶不思議な力によりほかの環境では動かないかもしれません。
1
2
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
1
2