Php 在drupal中为静态文件使用自定义url重写
我想编写一个drupal模块来服务静态文件,但我想让它从地址www.mydomain.com/moduleName/fileName来服务静态文件,其中文件名可以是任何内容(例如javascript/app.js或photos/imageA.jpg)。如果可能的话,我不想将文件复制到实际位置,理想情况下,我希望模块只是将这两个位置热链接起来 我试着使用一个带有回调的菜单 $numargs=func_num_args(); $arg_list=func_get_args() 但是,尽管这对任何文本文件都很好,但对于任何二进制文件(例如png、ico等),它完全失败。我也不喜欢这样指定mime类型 问题是,custom_url_rewrite能做我需要做的事情吗?如果是,custom_url rewrite函数应该包含什么,应该放在哪里 我试过这个,但似乎不起作用:Php 在drupal中为静态文件使用自定义url重写,php,drupal,Php,Drupal,我想编写一个drupal模块来服务静态文件,但我想让它从地址www.mydomain.com/moduleName/fileName来服务静态文件,其中文件名可以是任何内容(例如javascript/app.js或photos/imageA.jpg)。如果可能的话,我不想将文件复制到实际位置,理想情况下,我希望模块只是将这两个位置热链接起来 我试着使用一个带有回调的菜单 $numargs=func_num_args(); $arg_list=func_get_args() 但是,尽管这对任何文本
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;
}
我刚刚在php.net上找到了这个函数,它确实可以工作(尽管我仍然有兴趣知道是否有其他人有更好的方法来实现这个功能)
你可以尝试一个更简洁的解决方案,它总是适合我。我知道这是一篇非常古老的文章,但我只是想让其他读者知道,上面的代码有点混乱/重复。这里有一个清理过的版本:谢谢,总是喜欢一个好的重构:)这是一篇旧文章,但代码仍在使用中。
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;
}
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;
}
function readfile_chunked( $filename) {
$chunksize = 1 * (1024 * 1024); // how many bytes per chunk
$buffer = '';
$cnt = 0;
$handle = fopen( $filename, 'rb' );
if ( $handle === false ) {
return false;
}
ob_end_clean(); //added to fix ZIP file corruption
ob_start(); //added to fix ZIP file corruption
header( 'Content-Type:' ); //added to fix file corruption
header('Cache-Control: max-age=7200'); //time in seconds. so cache for 2 hours
while ( !feof( $handle ) ) {
$buffer = fread( $handle, $chunksize );
echo $buffer;
ob_flush();
flush();
}
fclose( $handle );
}