PHP 7.0.6 Released

chdir

(PHP 4, PHP 5, PHP 7)

chdirChange directory

Description

bool chdir ( string $directory )

Changes PHP's current directory to directory.

Parameters

directory

The new current directory

Return Values

Returns TRUE on success or FALSE on failure.

Errors/Exceptions

Throws an error of level E_WARNING on failure.

Examples

Example #1 chdir() example

<?php

// current directory
echo getcwd() . "\n";

chdir('public_html');

// current directory
echo getcwd() . "\n";

?>

The above example will output something similar to:

/home/vincent
/home/vincent/public_html

Notes

Note: When safe mode is enabled, PHP checks whether the directory in which the script is operating has the same UID (owner) as the script that is being executed.

See Also

  • getcwd() - Gets the current working directory

User Contributed Notes

herwin at snt dot utwente dot nl
9 years ago
When using PHP safe mode and trying to change to a dir that is not accessible due to the safe mode restrictions, the function simply fails without generating any kind of error message.

(Tested in PHP 4.3.10-16, Debian Sarge default)
php dot duke at qik dot nl
7 years ago
When changing dir's under windows environments:

<?php
$path
="c:\temp"';
chdir($path);
/* getcwd() gives you back "c:\temp" */

$path="c:\temp\"'
;
chdir($path);
/* getcwd() gives you back "c:\temp\" */
?>

to work around this inconsistency
doing a chdir('.') after the chdir always gives back "c:\temp"
andy dot clark at dial dot pipex dot com
9 years ago
This only changes the directory for PHP, the output directory stays the same. If you are trying to access images from a relative path and you use the following then it will fail to render the image:

chdir ('images');
if (file_exists('php.gif'))
{
echo '<html>';
echo '<body>';
echo '<img src="php.gif">';
echo '</body></html>';
}

//However, it is possible to use the <base> tag in the header to change the directory for the resulting HTML, as you can see however this requires you to put the full path in place.

chdir ('images');
if (file_exists('php.gif'))
{
echo '<html>';
echo '<head><base href = "http://uk.php.net/images/"></head>';
echo '<body>';
echo '<img src="php.gif">';
echo '</body></html>';
}
To Top