DEV Community

Zen
Zen

Posted on

Mengatasi Path Include PHP yang Dianggap Salah Path

Untuk menggunakan include di PHP, kita biasanya menggunakan kode seperti ini:

<?php include "./footer.php" ?>
Enter fullscreen mode Exit fullscreen mode

Misalnya aja file PHP tersebut kita panggil dari index.php. Jadi, posisi filenya seperti ini:

index.php
footer.php
Enter fullscreen mode Exit fullscreen mode

Tapi, akan menjadi masalah jika file yang kita include, melakukan include lagi pada lokasi lainnya. Contohnya seperti ini:

index.php (include) komponen/footer.php
komponen/footer.php (include) keterangan.php
Enter fullscreen mode Exit fullscreen mode

Nah, kita pasti di komponen/footer.php menuliskannya seperti ini:

<?php include "../keterangan.php" ?>
Enter fullscreen mode Exit fullscreen mode

Ketika kita membuka localhost/komponen/footer.php, dia works. Tapi, ketika membuka localhost, dia akan error pada bagian footer tadi karena kita memanggil seperti ini yang dibaca oleh server: localhost/../keterangan.php, bukan localhost/keterangan.php.

Solusinya adalah menambahkan dirname(__FILE__) . "/". Jadinya seperti ini:

<?php include dirname(__FILE__) . "/" . "../keterangan.php" ?>
Enter fullscreen mode Exit fullscreen mode

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay