Drupal 8  8.0.2
PHP wrapper functions

Functions

drupal_register_shutdown_function ($callback=NULL)
 
 drupal_set_time_limit ($time_limit)
 
 drupal_xml_parser_create (&$data)
 
static lcfirst ($text)
 
static ucwords ($text)
 
static buildQuery (array $query, $parent= '')
 
static parse ($url)
 
 moveUploadedFile ($filename, $uri)
 
 chmod ($uri, $mode=NULL)
 
 unlink ($uri, $context=NULL)
 
 realpath ($uri)
 
 dirname ($uri)
 
 basename ($uri, $suffix=NULL)
 
 mkdir ($uri, $mode=NULL, $recursive=FALSE, $context=NULL)
 
 rmdir ($uri, $context=NULL)
 
 tempnam ($directory, $prefix)
 

Detailed Description

Functions that are wrappers or custom implementations of PHP functions.

Certain PHP functions should not be used in Drupal. Instead, Drupal's replacement functions should be used.

For example, for improved or more secure UTF8-handling, or RFC-compliant handling of URLs in Drupal.

For ease of use and memorizing, all these wrapper functions use the same name as the original PHP function, but prefixed with "drupal_". Beware, however, that not all wrapper functions support the same arguments as the original functions.

You should always use these wrapper functions in your code.

Wrong:

$my_substring = substr($original_string, 0, 5);

Correct:

$my_substring = Unicode::substr($original_string, 0, 5);

Function Documentation

basename (   $uri,
  $suffix = NULL 
)

Gets the filename from a given path.

PHP's basename() does not properly support streams or filenames beginning with a non-US-ASCII character.

See Also
http://bugs.php.net/bug.php?id=37738
basename()

Implemented in FileSystem.

static buildQuery ( array  $query,
  $parent = '' 
)
static

Parses an array into a valid, rawurlencoded query string.

rawurlencode() is RFC3986 compliant, and as a consequence RFC3987 compliant. The latter defines the required format of "URLs" in HTML5. urlencode() is almost the same as rawurlencode(), except that it encodes spaces as "+" instead of "%20". This makes its result non compliant to RFC3986 and as a consequence non compliant to RFC3987 and as a consequence not valid as a "URL" in HTML5.

Todo:
Remove this function once PHP 5.4 is required as we can use just http_build_query() directly.
Parameters
array$queryThe query parameter array to be processed; for instance, ::request()->query->all().
string$parent(optional) Internal use only. Used to build the $query array key for nested items. Defaults to an empty string.
Returns
string A rawurlencoded string which can be used as or appended to the URL query string.

Referenced by ViewAjaxController\ajaxView(), UnroutedUrlAssembler\buildExternalUrl(), FormBuilder\buildFormAction(), UnroutedUrlAssembler\buildLocalUrl(), ImageStyle\buildUrl(), PlaceholderGenerator\createPlaceholder(), FilterProcessResult\createPlaceholder(), RedirectDestination\get(), MenuTreeStorage\loadByRoute(), MenuTreeStorage\preSave(), LanguageNegotiationContentEntity\processOutbound(), UrlHelperTest\testBuildQuery(), CustomPageExceptionHtmlSubscriberTest\testHandleWithGetRequest(), CustomPageExceptionHtmlSubscriberTest\testHandleWithPostRequest(), and Url\toUriString().

Here is the caller graph for this function:

chmod (   $uri,
  $mode = NULL 
)

Sets the permissions on a file or directory.

This function will use the file_chmod_directory and file_chmod_file settings for the default modes for directories and uploaded/generated files. By default these will give everyone read access so that users accessing the files with a user account without the webserver group (e.g. via FTP) can read these files, and give group write permissions so webserver group members (e.g. a vhost account) can alter files uploaded and owned by the webserver.

PHP's chmod does not support stream wrappers so we use our wrapper implementation which interfaces with chmod() by default. Contrib wrappers may override this behavior in their implementations as needed.

Parameters
string$uriA string containing a URI file, or directory path.
int$modeInteger value for the permissions. Consult PHP chmod() documentation for more information.
Returns
bool TRUE for success, FALSE in the event of an error.

Implemented in FileSystem.

dirname (   $uri)

Gets the name of the directory from a given path.

PHP's dirname() does not properly pass streams, so this function fills that gap. It is backwards compatible with normal paths and will use PHP's dirname() as a fallback.

Compatibility: normal paths and stream wrappers.

Parameters
string$uriA URI or path.
Returns
string A string containing the directory name.
See Also
dirname()
https://www.drupal.org/node/515192

Implemented in FileSystem.

& drupal_register_shutdown_function (   $callback = NULL)

Registers a function for execution on shutdown.

Wrapper for register_shutdown_function() that catches thrown exceptions to avoid "Exception thrown without a stack frame in Unknown".

Parameters
$callbackThe shutdown function to register.
...Additional arguments to pass to the shutdown function.
Returns
Array of shutdown functions to be executed.
See Also
register_shutdown_function()

Referenced by DatabaseLockBackend\__construct(), and SystemTestController\shutdownFunctions().

Here is the caller graph for this function:

drupal_set_time_limit (   $time_limit)

Attempts to set the PHP maximum execution time.

This function is a wrapper around the PHP function set_time_limit(). When called, set_time_limit() restarts the timeout counter from zero. In other words, if the timeout is the default 30 seconds, and 25 seconds into script execution a call such as set_time_limit(20) is made, the script will run for a total of 45 seconds before timing out.

If the current time limit is not unlimited it is possible to decrease the total time limit if the sum of the new time limit and the current time spent running the script is inferior to the original time limit. It is inherent to the way set_time_limit() works, it should rather be called with an appropriate value every time you need to allocate a certain amount of time to execute a task than only once at the beginning of the script.

Before calling set_time_limit(), we check if this function is available because it could be disabled by the server administrator. We also hide all the errors that could occur when calling set_time_limit(), because it is not possible to reliably ensure that PHP or a security extension will not issue a warning/error if they prevent the use of this function.

Parameters
$time_limitAn integer specifying the new time limit, in seconds. A value of 0 indicates unlimited execution time.

Referenced by BrowserTestBase\prepareEnvironment(), and Cron\run().

Here is the caller graph for this function:

drupal_xml_parser_create ( $data)

Prepares a new XML parser.

This is a wrapper around xml_parser_create() which extracts the encoding from the XML data first and sets the output encoding to UTF-8. This function should be used instead of xml_parser_create(), because PHP 4's XML parser doesn't check the input encoding itself. "Starting from PHP 5, the input encoding is automatically detected, so that the encoding parameter specifies only the output encoding."

This is also where unsupported encodings will be converted. Callers should take this into account: $data might have been changed after the call.

Parameters
$dataThe XML data which will be parsed later.
Returns
An XML parser object or FALSE on error.

References Drupal\logger().

Referenced by OpmlFeedAdd\parseOpml().

Here is the call graph for this function:

Here is the caller graph for this function:

static lcfirst (   $text)
static

Converts the first character of a UTF-8 string to lowercase.

Parameters
string$textThe string that will be converted.
Returns
string The string with the first character as lowercase.

Referenced by UnicodeTest\testLcfirst().

Here is the caller graph for this function:

mkdir (   $uri,
  $mode = NULL,
  $recursive = FALSE,
  $context = NULL 
)

Creates a directory, optionally creating missing components in the path to the directory.

When PHP's mkdir() creates a directory, the requested mode is affected by the process's umask. This function overrides the umask and sets the mode explicitly for all directory components created.

Parameters
string$uriA URI or pathname.
int$modeMode given to created directories. Defaults to the directory mode configured in the Drupal installation. It must have a leading zero.
bool$recursiveCreate directories recursively, defaults to FALSE. Cannot work with a mode which denies writing or execution to the owner of the process.
resource$contextRefer to http://php.net/manual/ref.stream.php
Returns
bool Boolean TRUE on success, or FALSE on failure.
See Also
mkdir()
https://www.drupal.org/node/515192
Todo:
Update with open_basedir compatible recursion logic from ::ensureDirectory().

Implemented in FileSystem.

moveUploadedFile (   $filename,
  $uri 
)

Moves an uploaded file to a new location.

PHP's move_uploaded_file() does not properly support streams if open_basedir is enabled, so this function fills that gap.

Compatibility: normal paths and stream wrappers.

Parameters
string$filenameThe filename of the uploaded file.
string$uriA string containing the destination URI of the file.
Returns
bool TRUE on success, or FALSE on failure.
See Also
move_uploaded_file()
https://www.drupal.org/node/515192

Implemented in FileSystem.

static parse (   $url)
static

Parses a URL string into its path, query, and fragment components.

This function splits both internal paths like

node?b=c#d

and external URLs like

https://example.com/a?b=c#d

into their component parts. See RFC 3986 for an explanation of what the component parts are.

Note that, unlike the RFC, when passed an external URL, this function groups the scheme, authority, and path together into the path component.

Parameters
string$urlThe internal path or external URL string to parse.
Returns
array An associative array containing:
  • path: The path component of $url. If $url is an external URL, this includes the scheme, authority, and path.
  • query: An array of query parameters from $url, if they exist.
  • fragment: The fragment component from $url, if it exists.
See Also
http://tools.ietf.org/html/rfc3986

Referenced by ConfirmFormHelper\buildCancelLink(), FormBuilder\buildFormAction(), WebTestBase\drupalPostAjaxForm(), GotoAction\execute(), RedirectResponseSubscriber\getDestinationAsAbsoluteUrl(), FieldUI\getNextDestination(), PathValidator\getUrl(), UrlTest\testDrupalParseUrl(), UrlTest\testFromUserInput(), LinkItemTest\testLinkItem(), UrlHelperTest\testParse(), and PathPluginBase\validatePath().

Here is the caller graph for this function:

realpath (   $uri)

Resolves the absolute filepath of a local URI or filepath.

The use of this method is discouraged, because it does not work for remote URIs. Except in rare cases, URIs should not be manually resolved.

Only use this function if you know that the stream wrapper in the URI uses the local file system, and you need to pass an absolute path to a function that is incompatible with stream URIs.

Parameters
string$uriA stream wrapper URI or a filepath, possibly including one or more symbolic links.
Returns
string|false The absolute local filepath (with no symbolic links) or FALSE on failure.
See Also
::realpath()
http://php.net/manual/function.realpath.php

Implemented in FileSystem.

rmdir (   $uri,
  $context = NULL 
)

Removes a directory.

PHP's rmdir() is broken on Windows, as it can fail to remove a directory when it has a read-only flag set.

Parameters
string$uriA URI or pathname.
resource$contextRefer to http://php.net/manual/ref.stream.php
Returns
bool Boolean TRUE on success, or FALSE on failure.
See Also
rmdir()

Implemented in FileSystem.

tempnam (   $directory,
  $prefix 
)

Creates a file with a unique filename in the specified directory.

PHP's tempnam() does not return a URI like we want. This function will return a URI if given a URI, or it will return a filepath if given a filepath.

Compatibility: normal paths and stream wrappers.

Parameters
string$directoryThe directory where the temporary filename will be created.
string$prefixThe prefix of the generated temporary filename. Note: Windows uses only the first three characters of prefix.
Returns
string|bool The new temporary filename, or FALSE on failure.
See Also
tempnam()
https://www.drupal.org/node/515192

Implemented in FileSystem.

static ucwords (   $text)
static

Capitalizes the first character of each word in a UTF-8 string.

Parameters
string$textThe text that will be converted.
Returns
string The input $text with each word capitalized.

References Unicode\strtoupper().

Referenced by HandlerBase\caseTransform(), and UnicodeTest\testUcwords().

Here is the call graph for this function:

Here is the caller graph for this function:

unlink (   $uri,
  $context = NULL 
)

Deletes a file.

PHP's unlink() is broken on Windows, as it can fail to remove a file when it has a read-only flag set.

Parameters
string$uriA URI or pathname.
resource$contextRefer to http://php.net/manual/ref.stream.php
Returns
bool Boolean TRUE on success, or FALSE on failure.
See Also
unlink()

Implemented in FileSystem.