I want to write a drupal module that serves static files, but I want it to serve them from the address http://www.mydomain.com/moduleName/fileName Where FileName could be anything (e.g. javascript/app.js or photos/imageA.jpg). I don’t want to copy the files to that actual location if possible, ideally I want the module to just hotlink the two locations.
I tried using a menu with a callback that looks like
$numargs = func_num_args();
$arg_list = func_get_args();
$fileName = drupal_get_path('module', 'moduleName') . "/files";
for ($i = 0; $i < $numargs; $i++) {
$fileName = $fileName . "/" . $arg_list[$i];
}
if ($numargs == 0) {
$fileName = drupal_get_path('module', 'moduleName') . "/files/index.html";
}
if (file_exists($fileName)) {
header('Content-Type: ' . getFileMimeType($fileName));
$handle = fopen($fileName, "r");
$contents = fread($handle, filesize($fileName));
fclose($handle);
echo $contents;
} else {
drupal_json_output(array('exists' => file_exists($fileName), 'fileName' => $fileName));
}
drupal_exit();
Where getFileMimeType looks like
function rcsarooms_getFileMimeType($file) {
$extension = pathinfo($file, PATHINFO_EXTENSION);
if ($extension == "html" || $extension == "md") {
$type = "text/html; charset=utf-8";
} else if ($extension == "css") {
$type = "text/css";
} else if ($extension == "js") {
$type = "application/x-javascript";
} else if ($extension == "json") {
$type = "application/json";
} else if ($extension == "ico") {
$type = "image/x-icon";
} else if ($extension == "png") {
$type = "image/png";
} else {
$type = "charset=UTF-8";
echo $extension;
drupal_exit();
return;
}
return $type;
}
but while this works fine for any text files it fails completely for any binary files (e.g. png, ico etc.) I also don’t like having to specify the mime-type like that.
The question is, can custom_url_rewrite do what I need to do and if so what should the custom url rewrite function have in it and where should it go?
I’ve tried this, but it doesn’t seem to work:
function custom_url_rewrite($op, $result, $path) {
if (strpos($result, "data") === false) {
if ($op == 'alias') {
if (preg_match('|^' . drupal_get_path('module', 'myModule') . '/files/(.*)|', $path, $matches)) {
return 'myModule/' . $matches[1];
}
}
if ($op == 'source') {
if (preg_match('|^myModule/(.*)|', $path, $matches)) {
return drupal_get_path('module', 'myModule') . '/files/'.$matches[1];
}
}
}
return $result;
}
I just found this function on php.net which does work (although I’m still interested to know if anyone else has a better way of doing this)