Hướng dẫn dùng current directory trong PHP

I'll set the scene...

  1. I've got a file example.php
  2. That particular file is in a folder called test
  3. The full file path is /root/user/website/htdocs/test/example.php

What I'd like is to echo the directory the file is in ie. test

I've managed to do this by reading the functions and creating the script below, is this a bad way of going about this? is there an easier way?

<?php $dir_array = explode('/', getcwd()); $dir_current = end($dir_array); echo $dir_current; ?>

outputs test

Thanks in advance.

hek2mgl

145k25 gold badges229 silver badges255 bronze badges

asked Feb 13, 2013 at 17:04

1

PHP has a constant for this:

echo __DIR__;

if you just want to have the last part of the path - test - in your case, then use basename()

echo basename(__DIR__);

cryptic ツ

15k9 gold badges53 silver badges80 bronze badges

answered Feb 13, 2013 at 17:08

hek2mglhek2mgl

145k25 gold badges229 silver badges255 bronze badges

1

I'd suggest you the following code:

echo array_pop(explode('/', dirname(__FILE__)));

If your PHP version is above 5.3.0, you can replace dirname(__FILE__) with __DIR__

For the problems with getcwd() you can read here

answered Feb 13, 2013 at 17:08

RantyRanty

3,2933 gold badges21 silver badges24 bronze badges

Considering this path store.com/products/electronics/index.php

This also works with include()

The 3rd combination should work for the OP.

$_SERVER['PHP_SELF'];

/products/electronics/index.php

dirname($_SERVER['PHP_SELF']);

/products/electronics

basename(dirname($_SERVER['PHP_SELF']));

electronics

basename($_SERVER['PHP_SELF']);

index.php

answered Nov 19, 2013 at 16:12

Vitim.usVitim.us

19k15 gold badges88 silver badges102 bronze badges

Almost:

<?php $dir_current = $dir_array[count($dir_array)-1]; ?>

answered Feb 13, 2013 at 17:08

DanManDanMan

11k4 gold badges39 silver badges58 bronze badges

Chủ đề