公共函数

CodeIgniter 定义了一些全局的函数,你可以在任何地方使用它们,并且不需要加载任何 类库或辅助函数。

 
is_php($version)
参数:
  • $version (string) -- Version number
返回:

TRUE if the running PHP version is at least the one specified or FALSE if not

返回类型:

bool

判断当前运行的 PHP 版本是否高于或等于你提供的版本号。

例如:

if (is_php('5.3'))
{
    $str = quoted_printable_encode($str);
}

如果当前运行的 PHP 版本等于或高于提供的版本号,该函数返回布尔值 TRUE ,反之则返回 FALSE 。

is_really_writable($file)
参数:
  • $file (string) -- File path
返回:

TRUE if the path is writable, FALSE if not

返回类型:

bool

在 Windows 服务器上只有当文件标志了只读属性时,PHP 的 is_writable() 函数才返回 FALSE , 其他情况都是返回 TRUE ,即使文件不是真的可写也返回 TRUE 。

这个函数首先尝试写入该文件,以此来判断该文件是不是真的可写。通常只在 is_writable() 函数 返回的结果不准确的平台下才推荐使用该函数。

例如:

if (is_really_writable('file.txt'))
{
    echo "I could write to this if I wanted to";
}
else
{
    echo "File is not writable";
}

注解

更多信息,参看 PHP bug #54709 。

config_item($key)
参数:
  • $key (string) -- Config item key
返回:

Configuration key value or NULL if not found

返回类型:

mixed

访问配置信息最好的方式是使用 配置类 ,但是,你也可以通过 config_item() 函数来访问单个配置项,更多信息,参看 配置类

set_status_header($code[$text = ''])
参数:
  • $code (int) -- HTTP Reponse status code
  • $text (string) -- A custom message to set with the status code
返回类型:

void

用于手动设置服务器的 HTTP 状态码,例如:

set_status_header(401);
// Sets the header as:  Unauthorized

查看这里 有一份状态码的完整清单。

remove_invisible_characters($str[$url_encoded = TRUE])
参数:
  • $str (string) -- Input string
  • $url_encoded (bool) -- Whether to remove URL-encoded characters as well
返回:

Sanitized string

返回类型:

string

这个函数防止在 ASCII 字符串中插入空字符,例如:Java\0script 。

举例:

remove_invisible_characters('Java\\0script');
// Returns: 'Javascript'
html_escape($var)
参数:
  • $var (mixed) -- Variable to escape (string or array)
返回:

HTML escaped string(s)

返回类型:

mixed

这个函数类似于 PHP 原生的 htmlspecialchars() 函数,只是它除了可以接受字符串参数外,还可以接受数组参数。

它在防止 XSS 攻击时很有用。

get_mimes()
返回:An associative array of file types
返回类型:array

这个函数返回 application/config/mimes.php 文件中定义的 MIME 数组的 引用 。

is_https()
返回:TRUE if currently using HTTP-over-SSL, FALSE if not
返回类型:bool

该函数在使用 HTTPS 安全连接时返回 TRUE ,没有使用 HTTPS(包括非 HTTP 的请求)则返回 FALSE 。

is_cli()
返回:TRUE if currently running under CLI, FALSE otherwise
返回类型:bool

当程序在命令行下运行时返回 TRUE ,反之返回 FALSE 。

注解

该函数会检查 PHP_SAPI 的值是否是 'cli' ,或者是否定义了 STDIN 常量。

function_usable($function_name)
参数:
  • $function_name (string) -- Function name
返回:

TRUE if the function can be used, FALSE if not

返回类型:

bool

检查一个函数是否可用,可用返回 TRUE ,否则返回 FALSE 。

该函数直接调用 function_exists() 函数,并检查当前是否加载了 Suhosin 扩展 <http://www.hardened-php.net/suhosin/> ,如果加载了 Suhosin ,检查函数有没有被它禁用。

这个函数在你需要检查某些函数的可用性时非常有用,例如 eval() 和 exec() 函数是非常危险的,可能会由于服务器的安全策略被禁用。

注解

之所以引入这个函数,是由于 Suhosin 的某个 bug 可能会终止脚本的执行, 虽然这个 bug 已经被修复了(版本 0.9.34),但可惜的是还没发布。