Drupal: Check to see if a file or directory exists
Sometimes you want to see if a file or directory in the managed file system exists and base your logic off its existence.
Example: wanting to know if the directory /sites/web-dev.swirt.us/files/jqueryui_theme/redmond/ exists before including it
Use is_dir() http://php.net/manual/en/function.is-dir.php
The trick is to add the public:// stream wrapper
<?php
$bDirectoryExists = is_dir('public://jqueryui_theme/redmond/');
if (
$bDirectoryExists) {
// It exists so do something with it.
} else {
// It does not exists so go whine about it.
}
?>
Example: wanting to know if the file /sites/web-dev.swirt.us/files/jqueryui_theme/redmond/jquery.ui.base.css exists before including it
Use file_exists() http://www.php.net/manual/en/function.file-exists.php
<?php
$bFileExists = file_exists('public://jqueryui_theme/redmond/jquery.ui.base.css');
if (
$bFileExists ) {
// It exists so do something with it.
} else {
// It does not exists so go whine about it.
}
?>
Check to see if a file exists in the Theme
Checking for the existence of a file in the Theme requires a little bit of work to get the pathing. It would look like this
<?php
global $theme_path;
// Path to file must be like this (no initial slash)
// sites/web-dev.swirt.us/themes/ssnresponsive/css/global.css
$bFileExists = file_exists($theme_path.'/css/global.css');
if ($bFileExists ) {
// It exists so do something with it.
} else {
// It does not exists so go whine about it.
}
?>