2

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
  • 152,036
  • 28
  • 249
  • 266

4 Answers4

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__);
kittycat
  • 14,983
  • 9
  • 55
  • 80
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • Exactly what I was looking for, it does the same job but a bit cleaner. Many Thanks. `` –  Feb 14 '13 at 09:17
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

Ranty
  • 3,333
  • 3
  • 22
  • 24
0

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


Vitim.us
  • 20,746
  • 15
  • 92
  • 109
-1

Almost:

<?php
$dir_current = $dir_array[count($dir_array)-1];
?>
DanMan
  • 11,323
  • 4
  • 40
  • 61