<?php
// PHP script prelude irrelevant section
echo "This is some pre-output content unrelated to the article.\n";
$foo = 123;
$bar = ["a", "b", "c"];
?>
<hr>
<?php
/**
* How to use the chdir() function to change the current working directory in PHP? A Complete Example Interpretation
*
* In PHP, the chdir() function is used to change the current working directory (CWD).
* The current working directory is the default path when PHP scripts operate on files. If no absolute path is provided,
* file operations are based on the current working directory.
*
* Function prototype:
* bool chdir(string $directory)
*
* Parameters:
* $directory - The target directory path, which can be either a relative or absolute path.
*
* Return value:
* Returns true on success, false on failure.
*
* Notes:
* 1. If the specified directory does not exist, it will return false.
* 2. If PHP does not have permission to access the directory, it will also fail.
*/
// Example 1: Switch to a specified directory
echo "Example 1: Switch to a specified directory\n";
$targetDir = "/tmp"; // A directory that exists on your system
if (chdir($targetDir)) {
echo "The current working directory has been changed to: " . getcwd() . "\n";
} else {
echo "Directory change failed. Please check if the path exists or if there are permission issues.\n";
}
// Example 2: Use relative path
echo "\nExample 2: Use relative path\n";
$currentDir = getcwd();
echo "Current directory: $currentDir\n";
$relativePath = "../"; // Parent directory
if (chdir($relativePath)) {
echo "After switching to the parent directory: " . getcwd() . "\n";
} else {
echo "Relative path switch failed.\n";
}
// Example 3: Combine with file operations
echo "\nExample 3: Combine with file operations\n";
$newDir = __DIR__ . "/testdir"; // Assume there is a directory named testdir
if (!file_exists($newDir)) {
mkdir($newDir, 0777, true);
}
if (chdir($newDir)) {
file_put_contents("example.txt", "This is a sample file placed in the new working directory.\n");
echo "File created at: " . getcwd() . "/example.txt\n";
} else {
echo "Failed to switch to the new directory to create a file.\n";
}
// Summary
echo "\nSummary:\n";
echo "1. chdir() is used to modify the current working directory of a PHP script.\n";
echo "2. You can use getcwd() to get the current working directory.\n";
echo "3. When performing file read/write operations, you can combine chdir() with relative paths for easier file management.\n";
?>
<p data-is-last-node="" data-is-only-node="">