2009-02-06-what-does-dirname__file__-and-basenamedirname__file__-do.md 1.54 KB
Newer Older
Danesh Manoharan's avatar
Danesh Manoharan committed
1
2
---
title: What does dirname(__FILE__) and basename(dirname(__FILE__)) do?
3
author: Danesh Manoharan
Danesh Manoharan's avatar
Danesh Manoharan committed
4
5
6
7
8
9
10
11
12
date: 2009-02-06T09:44:06+00:00
pvc_views:
  - 32501
robotsmeta:
  - index,follow
dsq_thread_id:
  - 889774814

---
13
Was helping a friend fix his php script today. He was not too sure about what "dirname(\_\_FILE\_\_)" did.
Danesh Manoharan's avatar
Danesh Manoharan committed
14

15
dirname() is a PHP function which returns the directory name of a file. For example if file abc.txt was in "/tmp/abc.txt" then the dirname() function would return "/tmp" .
Danesh Manoharan's avatar
Danesh Manoharan committed
16
17
18
19
20

Example Usage;

`<?php`

21
$file = "/tmp/abc.txt";
Danesh Manoharan's avatar
Danesh Manoharan committed
22
23
24
25
26
27
28

$path = dirname($file); // $path will now contain /tmp

?>

What does dirname(\_\_FILE\_\_) and basename(dirname(\_\_FILE\_\_)) do then?

29
The \_\_FILE\_\_ constant  represents the running script. It will return the full path and file name of the running script. For example, the  \_\_FILE\_\_ constant  on my server would return "/var/www/html/index.php" for my index.php file which is in the "/var/www/html/" directory.
Danesh Manoharan's avatar
Danesh Manoharan committed
30

31
The basename() command is normally used in conjunction with the dirname() function to strip the parent directory from a full file name. For example "/var/www/html/abc.txt" when passed through basename() would return abc.txt. basename() also works on directories. So, basename() on "/var/www/html" would return "html" since in Linux directories are files.
Danesh Manoharan's avatar
Danesh Manoharan committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45

Example Usage;

Imagine \_\_FILE\_\_ represents /var/www/html/index.php

`<?php`

echo dirname(\_\_FILE\_\_); // returns /var/www/html

echo basename(\_\_FILE\_\_); //returns index.php

echo basename(dirname(\_\_FILE\_\_)); //returns html

?>