欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

d7 drupal7 drupal 7 得到 Public file system path 公共路径 AG chatgpt 有大用 有大大用 有大大大用

在 Drupal 7 中获取公共文件系统路径

在 Drupal 7 中,您可以通过以下几种方式获取公共文件系统路径(通常是 sites/default/files):

方法1:使用 variable_get() 函数

php
$public_path = variable_get('file_public_path', 'sites/default/files');

方法2:使用 file_stream_wrapper 类

php
$wrapper = file_stream_wrapper_get_instance_by_uri('public://'); $public_path = $wrapper->realpath();

方法3:使用 drupal_realpath() 函数

php
$public_path = drupal_realpath('public://');

方法4:获取绝对 URL

php
$public_url = file_create_url('public:/');

注意事项:

  1. 文件路径是在 Drupal 设置中配置的,所以不要直接硬编码 'sites/default/files'

  2. 如果要获取私有文件系统路径,使用 'private://' 代替 'public://'

  3. 在进行文件操作前,应该先检查目录是否存在且可写

使用示例:

php
$public_path = variable_get('file_public_path', 'sites/default/files'); if (!file_prepare_directory($public_path, FILE_CREATE_DIRECTORY)) {  drupal_set_message(t('公共文件目录不可写'), 'error'); }

这些方法都能可靠地获取 Drupal 7 中配置的公共文件系统路径。选择哪种方法取决于您的具体需求场景


普通分类: