wheresrhys
wheresrhys

Reputation: 23500

Why are these relative paths not working in php

My app structure is as follows

application -> views -> templates
                             // some more files
                     page.php
            -> controllers 
                     home.php        
            -> models 
                     items.php
            router.php
index.php

First case:

Index.php

include 'application/routes.php';

Routes.php

require "controllers/home.php";

controllers/home.php

require '/application/models/clusters.php'; //works
require 'application/models/clusters.php'; //works
require '../models/clusters.php'; //doesn't work

Why do the first lines work but not the last?

Second case:

Index.php

include 'application/views/page.php';

Page.php

glob("application/views/templates/*.php") // array of files
glob("templates/*.php") // empty array

I think there's something wrong with my understanding of how paths work in php, but I can't figure out what it is. Sometimes paths seem to be relative to the current script, adn other times relative to index.php, but not necessarily tied to when I start the path with /

Upvotes: 4

Views: 21604

Answers (3)

jribeiro
jribeiro

Reputation: 3463

Please try this:

require 'application/controllers/home.php';

require 'application/models/clusters.php';

The problem is that paths in PHP are always relative to the first file path, in this case index.php. So you have to include the directory 'application'.

The alternative is to use set_include_path: http://php.net/manual/pt_BR/function.set-include-path.php

EDIT

To view your include_path:

echo ini_get('include_path');

Upvotes: 8

Adeel Mughal
Adeel Mughal

Reputation: 736

try this one

require '/../models/clusters.php'; //doesn't work

Upvotes: -6

Mark Baker
Mark Baker

Reputation: 212402

It always amazes me how many people don't understand the significance of include_path.

Unless you have specified an absolute path for your include/require, (i.e. a path that begins with a /) then PHP uses include_path to try and locate the file by processing each include path entry in turn. Typically, the first entry in the include path is . meaning the current directory (as returned by getcwd() if it were executed at that point in the script.

Upvotes: 0

Related Questions