GeneralUtility

The legendary "t3lib_div" class - Miscellaneous functions for general purpose.

Most of the functions do not relate specifically to TYPO3 However a section of functions requires certain TYPO3 features available See comments in the source. You are encouraged to use this library in your own scripts!

USE: All methods in this class are meant to be called statically. So use \TYPO3\CMS\Core\Utility\GeneralUtility::[method-name] to refer to the functions, eg. '\TYPO3\CMS\Core\Utility\GeneralUtility::milliseconds()'

Table of Contents

Properties

$container  : ContainerInterface|null
$finalClassNameCache  : array<class-string, class-string>
Cache for `makeInstance` with given class name and final class names to reduce number of `self::getClassName()` calls
$indpEnvCache  : array<string, string|bool|array<string, string|bool|null>|null>
$nonSingletonInstances  : array<class-string, array<int, object>>
Instances returned by `makeInstance`, using the class names as array keys
$singletonInstances  : array<class-string, SingletonInterface>
Singleton instances returned by `makeInstance`, using the class names as array keys

Methods

_GET()  : mixed
Returns the global $_GET array (or value from) normalized to contain un-escaped values.
_GP()  : mixed
Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST, which is equivalent to 'GP' order In case you already know by which method your data is arriving consider using GeneralUtility::_GET or GeneralUtility::_POST.
_GPmerged()  : array<string|int, mixed>
Returns the global arrays $_GET and $_POST merged with $_POST taking precedence.
_POST()  : mixed
Returns the global $_POST array (or value from) normalized to contain un-escaped values.
addInstance()  : mixed
Sets the instance of a non-singleton class to be returned by `makeInstance`.
array2xml()  : string
Converts a PHP array into an XML string.
callUserFunction()  : mixed
Calls a user-defined function/method in class Such a function/method should look like this: "function proc(&$params, &$ref) {...}"
camelCaseToLowerCaseUnderscored()  : string
Returns a given CamelCasedString as a lowercase string with underscores.
cmpFQDN()  : bool
Match fully qualified domain name with list of strings with wildcard
cmpIP()  : bool
Match IP number with list of numbers with wildcard Dispatcher method for switching into specialised IPv4 and IPv6 methods.
cmpIPv4()  : bool
Match IPv4 number with list of numbers with wildcard
cmpIPv6()  : bool
Match IPv6 address with a list of IPv6 prefixes
copyDirectory()  : mixed
Low level utility function to copy directories and content recursive
createVersionNumberedFilename()  : string
Function for static version numbers on files, based on the filemtime
dirname()  : string
Returns the directory part of a path without trailing slash If there is no dir-part, then an empty string is returned.
expandList()  : string
Expand a comma-separated list of integers with ranges (eg 1,3-5,7 becomes 1,3,4,5,7).
explodeUrl2Array()  : array<string|int, string>
Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array.
fixed_lgd_cs()  : string
Truncates a string with appended/prepended "..." and takes current character set into consideration.
fixPermissions()  : mixed
Sets the file system mode and group ownership of a file or a folder.
fixWindowsFilePath()  : string
Fixes a path for windows-backslashes and reduces double-slashes to single slashes
flushInternalRuntimeCaches()  : mixed
Flushes some internal runtime caches: - the class-name mapping used by `makeInstance()` - the cache for `getIndpEnv()`
formatSize()  : string
Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M)
get_dirs()  : array<string|int, string>|string|null
Returns an array with the names of folders in a specific path Will return 'error' (string) if there were an error with reading directory content.
get_tag_attributes()  : array<string, string>
Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameter list (ex ' OPTION ATTRIB=VALUE>') If an attribute is empty, then the value for the key is empty. You can check if it existed with isset()
getAllFilesAndFoldersInPath()  : array<string, string>
Recursively gather all files and folders of a path.
getBytesFromSizeMeasurement()  : int
Gets the bytes value from a measurement string like "100k".
getClassName()  : class-string
Returns the class name for a new instance, taking into account registered implementations for this class
getContainer()  : ContainerInterface
getFileAbsFileName()  : string
Returns the absolute filename of a relative reference, resolves the "EXT:" prefix (way of referring to files inside extensions) and checks that the file is inside the TYPO3's base folder and implies a check with \TYPO3\CMS\Core\Utility\GeneralUtility::validPathStr().
getFilesInDir()  : array<string, string>|string
Finds all files in a given path and returns them as an array. Each array key is a md5 hash of the full path to the file. This is done because 'some' extensions like the import/export extension depend on this.
getIndpEnv()  : string|bool|array<string, string|bool|null>|null
Abstraction method which returns System Environment Variables regardless of server OS, CGI/MODULE version etc. Basically this is SERVER variables for most of them.
getInstances()  : array<class-string, array<string|int, object>>
Get all currently registered non singleton instances
getMaxUploadFileSize()  : int
Returns the maximum upload size for a file that is allowed. Measured in KB.
getSingletonInstances()  : array<class-string, SingletonInterface>
Get all currently registered singletons
getUrl()  : string|false
Reads the file or url $url and returns the content If you are having trouble with proxies when reading URLs you can configure your way out of that with settings within $GLOBALS['TYPO3_CONF_VARS']['HTTP'].
hmac()  : string
Returns a proper HMAC on a given input string and secret TYPO3 encryption key.
implodeArrayForUrl()  : string
Implodes a multidim-array into GET-parameters (eg. &param[key][key2]=value2&param[key][key3]=value3)
implodeAttributes()  : string
Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)
inList()  : bool
Check for item in list Check if an item exists in a comma-separated list of items.
intExplode()  : array<string|int, int>
Explodes a $string delimited by $delimiter and casts each item in the array to (int).
isAllowedAbsPath()  : bool
Returns TRUE if the path is absolute, without backpath '..' and within TYPO3s project or public folder OR within the lockRootPath
isOnCurrentHost()  : bool
Checks if a given URL matches the host that currently handles this HTTP request.
isValidUrl()  : bool
Checks if a given string is a Uniform Resource Locator (URL).
jsonEncodeForHtmlAttribute()  : string
Serializes data to JSON, to be used in HTML attribute, e.g.
jsonEncodeForJavaScript()  : string
Serializes data to JSON, to be used in JavaScript instructions, e.g.
linkThisScript()  : string
Returns the link-url to the current script.
locationHeaderUrl()  : mixed
Prefixes a URL used with 'header-location' with 'http://...' depending on whether it has it already.
makeInstance()  : T
Creates an instance of a class taking into account the class-extensions API of TYPO3. USE THIS method instead of the PHP `new` keyword.
makeInstanceForDi()  : T
Creates a class taking implementation settings and class aliases into account.
makeInstanceService()  : object|array<string|int, string>|false
Find the best service and check if it works.
md5int()  : int
Makes a positive integer hash out of the first 7 chars from the md5 hash of the input
mkdir()  : bool
Wrapper function for mkdir.
mkdir_deep()  : mixed
Creates a directory - including parent directories if necessary and sets permissions on newly created directories.
normalizeIPv6()  : string
Normalize an IPv6 address to full length
purgeInstances()  : mixed
Purge all instances returned by makeInstance.
quoteJSvalue()  : string
Quotes a string for usage as JS parameter.
removeDotsFromTS()  : array<string|int, mixed>
Removes dots "." from end of a key identifier of TypoScript styled array.
removePrefixPathFromList()  : array<string|int, string>|string
Removes the absolute part of all files/folders in fileArr
removeSingletonInstance()  : mixed
Removes the instance of a singleton class to be returned by `makeInstance`.
resetSingletonInstances()  : mixed
Set a group of singleton instances. Similar to `setSingletonInstance()`, but multiple instances can be set.
resolveBackPath()  : string
Resolves "../" sections in the input path string.
revExplode()  : array<int, string>
Reverse explode which explodes the string counting from behind.
rmdir()  : bool
Wrapper function for rmdir, allowing recursive deletion of folders and files
sanitizeCssVariableValue()  : string
Very, very, very basic CSS sanitizer which removes `{`, `}`, `\n`, `\r` from CSS variable values and encodes potential HTML entities `<`+`>`.
sanitizeLocalUrl()  : string
Checks if a given string is a valid frame URL to be loaded in the backend.
setContainer()  : void
setIndpEnv()  : mixed
This method is only for testing and should never be used outside tests.
setSingletonInstance()  : mixed
Sets the instance of a singleton class to be returned by `makeInstance`.
split_fileref()  : array<string, string>
Splits a reference to a file in 5 parts
split_tag_attributes()  : array<string|int, string>
Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes Removes tag-name if found
splitCalc()  : array<int, array<int, string>>
This splits a string by the chars in $operators (typical /+-*) and returns an array with them in
tempnam()  : non-empty-string
Create temporary filename (Create file with unique file name) This function should be used for getting temporary file names - will make your applications safe for open_basedir = on REMEMBER to delete the temporary files after use! This is done by \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile()
trimExplode()  : array<int, string>
Explodes a string and removes whitespace-only values.
underscoredToLowerCamelCase()  : string
Returns a given string with underscores as lowerCamelCase.
underscoredToUpperCamelCase()  : string
Returns a given string with underscores as UpperCamelCase.
unlink_tempfile()  : bool|null
Deletes (unlink) a temporary filename in the var/ or typo3temp folder given as input.
upload_copy_move()  : bool
Moves $source file to $destination if uploaded, otherwise try to make a copy
upload_to_tempfile()  : string
Will move an uploaded file (normally in "/tmp/xxxxx") to a temporary filename in Environment::getProjectPath() . "var/" from where TYPO3 can use it.
validEmail()  : bool
Checking syntax of input email address
validIP()  : bool
Validate a given IP address.
validIPv4()  : bool
Validate a given IP address to the IPv4 address format.
validIPv6()  : bool
Validate a given IP address to the IPv6 address format.
validPathStr()  : bool
Checks for malicious file paths.
wrapJS()  : string
Wraps JavaScript code XHTML ready with <script>-tags Automatic re-indenting of the JS code is done by using the first line as indent reference.
writeFile()  : bool
Writes $content to the file $file
writeFileToTypo3tempDir()  : string|null
Writes $content to a filename in the typo3temp/ folder (and possibly one or two subfolders...) Accepts an additional subdirectory in the file path!
writeJavaScriptContentToTemporaryFile()  : string
Writes string to a temporary file named after the md5-hash of the string Quite useful for extensions adding their custom built JavaScript during runtime.
writeStyleSheetContentToTemporaryFile()  : string
Writes string to a temporary file named after the md5-hash of the string Quite useful for extensions adding their custom built StyleSheet during runtime.
xml2array()  : mixed
Converts an XML string to a PHP array.
xml2arrayProcess()  : mixed
Converts an XML string to a PHP array.
xml2tree()  : mixed
Parses XML input into a PHP array with associative keys
xmlRecompileFromStructValArray()  : string
This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again.
checkInstanceClassName()  : mixed
Checks that `$className` is non-empty and that `$instance` is an instance of `$className`.
classHasImplementation()  : bool
Checks if a class has a configured implementation
createDirectoryPath()  : string
Creates directories for the specified paths if they do not exist. This functions sets proper permission mask but does not set proper user and group.
encodeFileSystemPathComponentForUrlPath()  : string
getImplementationForClass()  : class-string
Returns the configured implementation of the class
getLogger()  : LoggerInterface
webserverUsesHttps()  : bool
Determine if the webserver uses HTTPS.

Properties

$container

protected static ContainerInterface|null $container = null

$finalClassNameCache

Cache for `makeInstance` with given class name and final class names to reduce number of `self::getClassName()` calls

protected static array<class-string, class-string> $finalClassNameCache = []

Given class name => final class name

$indpEnvCache

protected static array<string, string|bool|array<string, string|bool|null>|null> $indpEnvCache = []

$nonSingletonInstances

Instances returned by `makeInstance`, using the class names as array keys

protected static array<class-string, array<int, object>> $nonSingletonInstances = []

$singletonInstances

Singleton instances returned by `makeInstance`, using the class names as array keys

protected static array<class-string, SingletonInterface> $singletonInstances = []

Methods

_GET()

Returns the global $_GET array (or value from) normalized to contain un-escaped values.

public static _GET([string $var = null ]) : mixed
Deprecated

since TYPO3 v12.4. will be removed in TYPO3 v13.0.

This function was previously used to normalize between magic quotes logic, which was removed from PHP 5.5

Parameters
$var : string = null

Optional pointer to value in GET array (basically name of GET var)

Return values
mixed

If $var is set it returns the value of $_GET[$var]. If $var is NULL (default), returns $_GET itself.

_GP()

Returns the 'GLOBAL' value of incoming data from POST or GET, with priority to POST, which is equivalent to 'GP' order In case you already know by which method your data is arriving consider using GeneralUtility::_GET or GeneralUtility::_POST.

public static _GP(string $var) : mixed
Deprecated

since TYPO3 v12.3. will be removed in TYPO3 v13.0.

Parameters
$var : string

GET/POST var to return

Return values
mixed

POST var named $var, if not set, the GET var of the same name and if also not set, NULL.

_GPmerged()

Returns the global arrays $_GET and $_POST merged with $_POST taking precedence.

public static _GPmerged(string $parameter) : array<string|int, mixed>
Deprecated

since TYPO3 v12.2. will be removed in TYPO3 v13.0.

Parameters
$parameter : string

Key (variable name) from GET or POST vars

Return values
array<string|int, mixed>

Returns the GET vars merged recursively onto the POST vars.

_POST()

Returns the global $_POST array (or value from) normalized to contain un-escaped values.

public static _POST([string $var = null ]) : mixed
Deprecated

since TYPO3 v12.2. will be removed in TYPO3 v13.0.

Parameters
$var : string = null

Optional pointer to value in POST array (basically name of POST var)

Return values
mixed

If $var is set it returns the value of $_POST[$var]. If $var is NULL (default), returns $_POST itself.

addInstance()

Sets the instance of a non-singleton class to be returned by `makeInstance`.

public static addInstance(class-string $className, object $instance) : mixed

If this function is called multiple times for the same $className, makeInstance will return the instances in the order in which they have been added (FIFO).

Warning: This is a helper method for unit tests. Do not call this directly in production code!

Parameters
$className : class-string
$instance : object
Tags
see
makeInstance
throws
InvalidArgumentException

if class extends \TYPO3\CMS\Core\SingletonInterface

array2xml()

Converts a PHP array into an XML string.

public static array2xml(array<string|int, mixed> $array[, string $NSprefix = '' ][, int $level = 0 ][, string $docTag = 'phparray' ][, int $spaceInd = 0 ][, array<string|int, mixed> $options = [] ][, array<string|int, mixed> $stackData = [] ]) : string

The XML output is optimized for readability since associative keys are used as tag names. This also means that only alphanumeric characters are allowed in the tag names AND only keys NOT starting with numbers (so watch your usage of keys!). However there are options you can set to avoid this problem. Numeric keys are stored with the default tag name "numIndex" but can be overridden to other formats) The function handles input values from the PHP array in a binary-safe way; All characters below 32 (except 9,10,13) will trigger the content to be converted to a base64-string The PHP variable type of the data IS preserved as long as the types are strings, arrays, integers and booleans. Strings are the default type unless the "type" attribute is set. The output XML has been tested with the PHP XML-parser and parses OK under all tested circumstances with 4.x versions. However, with PHP5 there seems to be the need to add an XML prologue a la - otherwise UTF-8 is assumed! Unfortunately, many times the output from this function is used without adding that prologue meaning that non-ASCII characters will break the parsing!! This sucks of course! Effectively it means that the prologue should always be prepended setting the right characterset, alternatively the system should always run as utf-8! However using MSIE to read the XML output didn't always go well: One reason could be that the character encoding is not observed in the PHP data. The other reason may be if the tag-names are invalid in the eyes of MSIE. Also using the namespace feature will make MSIE break parsing. There might be more reasons...

Parameters
$array : array<string|int, mixed>

The input PHP array with any kind of data; text, binary, integers. Not objects though.

$NSprefix : string = ''

tag-prefix, eg. a namespace prefix like "T3:"

$level : int = 0

Current recursion level. Don't change, stay at zero!

$docTag : string = 'phparray'

Alternative document tag. Default is "phparray".

$spaceInd : int = 0

If greater than zero, then the number of spaces corresponding to this number is used for indenting, if less than zero - no indentation, if zero - a single TAB is used

$options : array<string|int, mixed> = []

Options for the compilation. Key "useNindex" => 0/1 (boolean: whether to use "n0, n1, n2" for num. indexes); Key "useIndexTagForNum" => "[tag for numerical indexes]"; Key "useIndexTagForAssoc" => "[tag for associative indexes"; Key "parentTagMap" => array('parentTag' => 'thisLevelTag')

$stackData : array<string|int, mixed> = []

Stack data. Don't touch.

Tags
see
xml2array()
Return values
string

An XML string made from the input content in the array.

callUserFunction()

Calls a user-defined function/method in class Such a function/method should look like this: "function proc(&$params, &$ref) {...}"

public static callUserFunction(non-empty-string|Closure $funcName, mixed &$params[, object|null $ref = null ]) : mixed
Parameters
$funcName : non-empty-string|Closure

Function/Method reference or Closure.

$params : mixed

Parameters to be pass along (typically an array) (REFERENCE!)

$ref : object|null = null

Reference to be passed along (typically "$this" - being a reference to the calling object)

Tags
throws
InvalidArgumentException
Return values
mixed

Content from method/function call

camelCaseToLowerCaseUnderscored()

Returns a given CamelCasedString as a lowercase string with underscores.

public static camelCaseToLowerCaseUnderscored(string $string) : string

Example: Converts BlogExample to blog_example, and minimalValue to minimal_value

Parameters
$string : string

String to be converted to lowercase underscore

Return values
string

lowercase_and_underscored_string

cmpFQDN()

Match fully qualified domain name with list of strings with wildcard

public static cmpFQDN(string $baseHost, string $list) : bool
Parameters
$baseHost : string

A hostname or an IPv4/IPv6-address (will by reverse-resolved; typically REMOTE_ADDR)

$list : string

A comma-list of domain names to match with. -wildcard allowed but cannot be part of a string, so it must match the full host name (eg. myhost..com => correct, myhost.*domain.com => wrong)

Return values
bool

TRUE if a domain name mask from $list matches $baseIP

cmpIP()

Match IP number with list of numbers with wildcard Dispatcher method for switching into specialised IPv4 and IPv6 methods.

public static cmpIP(string $baseIP, string $list) : bool
Parameters
$baseIP : string

Is the current remote IP address for instance, typ. REMOTE_ADDR

$list : string

Is a comma-list of IP-addresses to match with. CIDR-notation should be used. For IPv4 addresses only, the -wildcard is also allowed instead of number, plus leaving out parts in the IP number is accepted as wildcard (eg. 192.168..* equals 192.168). If list is "*" no check is done and the function returns TRUE immediately. An empty list always returns FALSE.

Return values
bool

TRUE if an IP-mask from $list matches $baseIP

cmpIPv4()

Match IPv4 number with list of numbers with wildcard

public static cmpIPv4(string $baseIP, string $list) : bool
Parameters
$baseIP : string

Is the current remote IP address for instance, typ. REMOTE_ADDR

$list : string

Is a comma-list of IP-addresses to match with. CIDR-notation, -wildcard allowed instead of number, plus leaving out parts in the IP number is accepted as wildcard (eg. 192.168.0.0/16 equals 192.168..* equals 192.168), could also contain IPv6 addresses

Return values
bool

TRUE if an IP-mask from $list matches $baseIP

cmpIPv6()

Match IPv6 address with a list of IPv6 prefixes

public static cmpIPv6(string $baseIP, string $list) : bool
Parameters
$baseIP : string

Is the current remote IP address for instance

$list : string

Is a comma-list of IPv6 prefixes, could also contain IPv4 addresses. IPv6 addresses must be specified in CIDR-notation, not with * wildcard, otherwise self::validIPv6() will fail.

Return values
bool

TRUE If a baseIP matches any prefix

copyDirectory()

Low level utility function to copy directories and content recursive

public static copyDirectory(string $source, string $destination) : mixed
Parameters
$source : string

Path to source directory, relative to document root or absolute

$destination : string

Path to destination directory, relative to document root or absolute

createVersionNumberedFilename()

Function for static version numbers on files, based on the filemtime

public static createVersionNumberedFilename(string $file) : string

This will make the filename automatically change when a file is changed, and by that re-cached by the browser. If the file does not exist physically the original file passed to the function is returned without the timestamp.

Behaviour is influenced by the setting TYPO3_CONF_VARS['BE' and 'FE'][versionNumberInFilename] = TRUE : modify filename ("embed" is also allowed until TYPO3 v13 in FE for legacy reasons) = FALSE : add timestamp as query parameter

Parameters
$file : string

Relative path to file including all potential query parameters (not htmlspecialchared yet)

Return values
string

Relative path with version filename including the timestamp

dirname()

Returns the directory part of a path without trailing slash If there is no dir-part, then an empty string is returned.

public static dirname(string $path) : string

Behaviour:

'/dir1/dir2/script.php' => '/dir1/dir2' '/dir1/' => '/dir1' 'dir1/script.php' => 'dir1' 'd/script.php' => 'd' '/script.php' => '' '' => ''

Parameters
$path : string

Directory name / path

Return values
string

Processed input value. See function description.

expandList()

Expand a comma-separated list of integers with ranges (eg 1,3-5,7 becomes 1,3,4,5,7).

public static expandList(string $list) : string

Ranges are limited to 1000 values per range.

Parameters
$list : string

Comma-separated list of integers with ranges (string)

Return values
string

New comma-separated list of items

explodeUrl2Array()

Explodes a string with GETvars (eg. "&id=1&type=2&ext[mykey]=3") into an array.

public static explodeUrl2Array(string $string) : array<string|int, string>

Note! If you want to use a multi-dimensional string, consider this plain simple PHP code instead:

$result = []; parse_str($queryParametersAsString, $result);

However, if you do magic with a flat structure (e.g. keeping "ext[mykey]" as flat key in a one-dimensional array) then this method is for you.

Parameters
$string : string

GETvars string

Tags
see
implodeArrayForUrl()
Return values
array<string|int, string>

Array of values. All values AND keys are rawurldecoded() as they properly should be. But this means that any implosion of the array again must rawurlencode it!

fixed_lgd_cs()

Truncates a string with appended/prepended "..." and takes current character set into consideration.

public static fixed_lgd_cs(string $string, int $chars[, string $appendString = '...' ]) : string
Parameters
$string : string

String to truncate

$chars : int

Must be an integer with an absolute value of at least 4. if negative the string is cropped from the right end.

$appendString : string = '...'

Appendix to the truncated string

Return values
string

Cropped string

fixPermissions()

Sets the file system mode and group ownership of a file or a folder.

public static fixPermissions(string $path[, bool $recursive = false ]) : mixed
Parameters
$path : string

Path of file or folder, must not be escaped. Path can be absolute or relative

$recursive : bool = false

If set, also fixes permissions of files and folders in the folder (if $path is a folder)

Return values
mixed

TRUE on success, FALSE on error, always TRUE on Windows OS

fixWindowsFilePath()

Fixes a path for windows-backslashes and reduces double-slashes to single slashes

public static fixWindowsFilePath(string $theFile) : string
Parameters
$theFile : string
Return values
string

flushInternalRuntimeCaches()

Flushes some internal runtime caches: - the class-name mapping used by `makeInstance()` - the cache for `getIndpEnv()`

public static flushInternalRuntimeCaches() : mixed

This function is intended to be used in unit tests to keep environment changes from spilling into the next test.

Internal

formatSize()

Formats the input integer $sizeInBytes as bytes/kilobytes/megabytes (-/K/M)

public static formatSize(int $sizeInBytes[, string $labels = '' ][, int $base = 0 ]) : string
Parameters
$sizeInBytes : int

Number of bytes to format.

$labels : string = ''

Binary unit name "iec", decimal unit name "si" or labels for bytes, kilo, mega, giga, and so on separated by vertical bar (|) and possibly encapsulated in "". Eg: " | K| M| G". Defaults to "iec".

$base : int = 0

The unit base if not using a unit name. Defaults to 1024.

Return values
string

Formatted representation of the byte number, for output.

get_dirs()

Returns an array with the names of folders in a specific path Will return 'error' (string) if there were an error with reading directory content.

public static get_dirs(string $path) : array<string|int, string>|string|null

Will return null if provided path is false.

Parameters
$path : string

Path to list directories from

Return values
array<string|int, string>|string|null

Returns an array with the directory entries as values. If no path is provided, the return value will be null.

get_tag_attributes()

Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z $tag is either a whole tag (eg '<TAG OPTION ATTRIB=VALUE>') or the parameter list (ex ' OPTION ATTRIB=VALUE>') If an attribute is empty, then the value for the key is empty. You can check if it existed with isset()

public static get_tag_attributes(string $tag[, bool $decodeEntities = false ]) : array<string, string>
Parameters
$tag : string

HTML-tag string (or attributes only)

$decodeEntities : bool = false

Whether to decode HTML entities

Return values
array<string, string>

Array with the attribute values.

getAllFilesAndFoldersInPath()

Recursively gather all files and folders of a path.

public static getAllFilesAndFoldersInPath(array<string|int, string> $fileArr, string $path[, string $extList = '' ][, bool $regDirs = false ][, int $recursivityLevels = 99 ][, string $excludePattern = '' ]) : array<string, string>
Parameters
$fileArr : array<string|int, string>

Empty input array (will have files added to it)

$path : string

The path to read recursively from (absolute) (include trailing slash!)

$extList : string = ''

Comma list of file extensions: Only files with extensions in this list (if applicable) will be selected.

$regDirs : bool = false

If set, directories are also included in output.

$recursivityLevels : int = 99

The number of levels to dig down...

$excludePattern : string = ''

regex pattern of files/directories to exclude

Return values
array<string, string>

An array with the found files/directories.

getBytesFromSizeMeasurement()

Gets the bytes value from a measurement string like "100k".

public static getBytesFromSizeMeasurement(string $measurement) : int
Parameters
$measurement : string

The measurement (e.g. "100k")

Return values
int

The bytes value (e.g. 102400)

getClassName()

Returns the class name for a new instance, taking into account registered implementations for this class

public static getClassName(class-string $className) : class-string
Parameters
$className : class-string

Base class name to evaluate

Internal

This is not a public API method, do not use in own extensions. Public to be accessible by extbase hydration.

Return values
class-string

Final class name to instantiate with new [classname]

getContainer()

public static getContainer() : ContainerInterface
Internal
Return values
ContainerInterface

getFileAbsFileName()

Returns the absolute filename of a relative reference, resolves the "EXT:" prefix (way of referring to files inside extensions) and checks that the file is inside the TYPO3's base folder and implies a check with \TYPO3\CMS\Core\Utility\GeneralUtility::validPathStr().

public static getFileAbsFileName(string $filename) : string
Parameters
$filename : string

The input filename/filepath to evaluate

Return values
string

Returns the absolute filename of $filename if valid, otherwise blank string.

getFilesInDir()

Finds all files in a given path and returns them as an array. Each array key is a md5 hash of the full path to the file. This is done because 'some' extensions like the import/export extension depend on this.

public static getFilesInDir(string $path[, string $extensionList = '' ][, bool $prependPath = false ][, string $order = '' ][, string $excludePattern = '' ]) : array<string, string>|string
Parameters
$path : string

The path to retrieve the files from.

$extensionList : string = ''

A comma-separated list of file extensions. Only files of the specified types will be retrieved. When left blank, files of any type will be retrieved.

$prependPath : bool = false

If TRUE, the full path to the file is returned. If FALSE only the file name is returned.

$order : string = ''

The sorting order. The default sorting order is alphabetical. Setting $order to 'mtime' will sort the files by modification time.

$excludePattern : string = ''

A regular expression pattern of file names to exclude. For example: 'clear.gif' or '(clear.gif|.htaccess)'. The pattern will be wrapped with: '/^' and '$/'.

Return values
array<string, string>|string

Array of the files found, or an error message in case the path could not be opened.

getIndpEnv()

Abstraction method which returns System Environment Variables regardless of server OS, CGI/MODULE version etc. Basically this is SERVER variables for most of them.

public static getIndpEnv(string $getEnvName) : string|bool|array<string, string|bool|null>|null

This should be used instead of getEnv() and $_SERVER/ENV_VARS to get reliable values for all situations.

Parameters
$getEnvName : string

Name of the "environment variable"/"server variable" you wish to use. Valid values are SCRIPT_NAME, SCRIPT_FILENAME, REQUEST_URI, PATH_INFO, REMOTE_ADDR, REMOTE_HOST, HTTP_REFERER, HTTP_HOST, HTTP_USER_AGENT, HTTP_ACCEPT_LANGUAGE, QUERY_STRING, TYPO3_DOCUMENT_ROOT, TYPO3_HOST_ONLY, TYPO3_HOST_ONLY, TYPO3_REQUEST_HOST, TYPO3_REQUEST_URL, TYPO3_REQUEST_SCRIPT, TYPO3_REQUEST_DIR, TYPO3_SITE_URL, _ARRAY

Tags
throws
UnexpectedValueException
Return values
string|bool|array<string, string|bool|null>|null

Value based on the input key, independent of server/OS environment.

getInstances()

Get all currently registered non singleton instances

public static getInstances() : array<class-string, array<string|int, object>>

Warning: This is NOT a public API method and must not be used in own extensions! This method is only used in UnitTestCase base test tearDown() to verify tests have no left-over instances that were previously added using addInstance().

Internal
Return values
array<class-string, array<string|int, object>>

getMaxUploadFileSize()

Returns the maximum upload size for a file that is allowed. Measured in KB.

public static getMaxUploadFileSize() : int

This might be handy to find out the real upload limit that is possible for this TYPO3 installation.

Return values
int

Maximum size of uploads that are allowed in KiB (divider 1024)

getSingletonInstances()

Get all currently registered singletons

public static getSingletonInstances() : array<class-string, SingletonInterface>

Warning: This is NOT a public API method and must not be used in own extensions! This method is usually only used in tests in setUp() to fetch the list of currently registered singletons, if this list is manipulated with setSingletonInstance() in tests.

Internal
Return values
array<class-string, SingletonInterface>

getUrl()

Reads the file or url $url and returns the content If you are having trouble with proxies when reading URLs you can configure your way out of that with settings within $GLOBALS['TYPO3_CONF_VARS']['HTTP'].

public static getUrl(string $url) : string|false
Parameters
$url : string

File/URL to read

Return values
string|false

The content from the resource given as input. FALSE if an error has occurred.

hmac()

Returns a proper HMAC on a given input string and secret TYPO3 encryption key.

public static hmac(string $input[, string $additionalSecret = '' ]) : string
Parameters
$input : string

Input string to create HMAC from

$additionalSecret : string = ''

additionalSecret to prevent hmac being used in a different context

Return values
string

resulting (hexadecimal) HMAC currently with a length of 40 (HMAC-SHA-1)

implodeArrayForUrl()

Implodes a multidim-array into GET-parameters (eg. &param[key][key2]=value2&param[key][key3]=value3)

public static implodeArrayForUrl(string $name, array<string|int, mixed> $theArray[, string $str = '' ][, bool $skipBlank = false ][, bool $rawurlencodeParamName = false ]) : string
Parameters
$name : string

Name prefix for entries. Set to blank if you wish none.

$theArray : array<string|int, mixed>

The (multidimensional) array to implode

$str : string = ''

(keep blank)

$skipBlank : bool = false

If set, parameters which were blank strings would be removed.

$rawurlencodeParamName : bool = false

If set, the param name itself (for example "param[key][key2]") would be rawurlencoded as well.

Tags
see
explodeUrl2Array()
Return values
string

Imploded result, fx. &param[key][key2]=value2&param[key][key3]=value3

implodeAttributes()

Implodes attributes in the array $arr for an attribute list in eg. and HTML tag (with quotes)

public static implodeAttributes(array<string, string|int> $arr[, bool $xhtmlSafe = false ][, bool $keepBlankAttributes = false ]) : string
Parameters
$arr : array<string, string|int>

Array with attribute key/value pairs, eg. "bgcolor" => "red", "border" => 0

$xhtmlSafe : bool = false

If set the resulting attribute list will have a) all attributes in lowercase (and duplicates weeded out, first entry taking precedence) and b) all values htmlspecialchar()'ed. It is recommended to use this switch!

$keepBlankAttributes : bool = false

If TRUE, don't check if values are blank. Default is to omit attributes with blank values.

Return values
string

Imploded attributes, eg. 'bgcolor="red" border="0"'

inList()

Check for item in list Check if an item exists in a comma-separated list of items.

public static inList(string $list, string $item) : bool
Parameters
$list : string

Comma-separated list of items (string)

$item : string

Item to check for

Return values
bool

TRUE if $item is in $list

intExplode()

Explodes a $string delimited by $delimiter and casts each item in the array to (int).

public static intExplode(string $delimiter, string $string[, bool $removeEmptyValues = false ][, int $limit = 0 ]) : array<string|int, int>

Corresponds to \TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(), but with conversion to integers for all values.

Parameters
$delimiter : string

Delimiter string to explode with

$string : string

The string to explode

$removeEmptyValues : bool = false

If set, all empty values (='') will NOT be set in output

$limit : int = 0

@deprecated will be removed in TYPO3 v13.0 without replacement. If positive, the result will contain a maximum of $limit elements.

Return values
array<string|int, int>

Exploded values, all converted to integers

isAllowedAbsPath()

Returns TRUE if the path is absolute, without backpath '..' and within TYPO3s project or public folder OR within the lockRootPath

public static isAllowedAbsPath(string $path) : bool
Parameters
$path : string

File path to evaluate

Return values
bool

isOnCurrentHost()

Checks if a given URL matches the host that currently handles this HTTP request.

public static isOnCurrentHost(string $url) : bool

Scheme, hostname and (optional) port of the given URL are compared.

Parameters
$url : string

URL to compare with the TYPO3 request host

Return values
bool

Whether the URL matches the TYPO3 request host

isValidUrl()

Checks if a given string is a Uniform Resource Locator (URL).

public static isValidUrl(string $url) : bool

On seriously malformed URLs, parse_url may return FALSE and emit an E_WARNING.

filter_var() requires a scheme to be present.

http://www.faqs.org/rfcs/rfc2396.html Scheme names consist of a sequence of characters beginning with a lower case letter and followed by any combination of lower case letters, digits, plus ("+"), period ("."), or hyphen ("-"). For resiliency, programs interpreting URI should treat upper case letters as equivalent to lower case in scheme names (e.g., allow "HTTP" as well as "http"). scheme = alpha *( alpha | digit | "+" | "-" | "." )

Convert the domain part to punicode if it does not look like a regular domain name. Only the domain part because RFC3986 specifies the the rest of the url may not contain special characters: https://tools.ietf.org/html/rfc3986#appendix-A

Parameters
$url : string

The URL to be validated

Return values
bool

Whether the given URL is valid

jsonEncodeForHtmlAttribute()

Serializes data to JSON, to be used in HTML attribute, e.g.

public static jsonEncodeForHtmlAttribute(mixed $value[, bool $useHtmlEntities = true ]) : string

<div data-value="[[JSON]]">...</div> ([[JSON]] represents return value of this function)

Parameters
$value : mixed
$useHtmlEntities : bool = true
Return values
string

jsonEncodeForJavaScript()

Serializes data to JSON, to be used in JavaScript instructions, e.g.

public static jsonEncodeForJavaScript(mixed $value) : string

<script>const value = JSON.parse('[[JSON]]');</script> ([[JSON]] represents return value of this function)

Parameters
$value : mixed
Return values
string

linkThisScript()

Returns the link-url to the current script.

public static linkThisScript([array<string|int, mixed> $getParams = [] ]) : string
Deprecated

since TYPO3 v12.4. will be removed in TYPO3 v13.0.

In $getParams you can set associative keys corresponding to the GET-vars you wish to add to the URL. If you set them empty, they will remove existing GET-vars from the current URL. REMEMBER to always use htmlspecialchars() for content in href-properties to get ampersands converted to entities (XHTML requirement and XSS precaution)

Parameters
$getParams : array<string|int, mixed> = []

Array of GET parameters to include

Return values
string

locationHeaderUrl()

Prefixes a URL used with 'header-location' with 'http://...' depending on whether it has it already.

public static locationHeaderUrl(string $path) : mixed
  • If already having a scheme, nothing is prepended
  • If having REQUEST_URI slash '/', then prefixing 'http://[host]' (relative to host)
  • Otherwise prefixed with TYPO3_REQUEST_DIR (relative to current dir / TYPO3_REQUEST_DIR)
Parameters
$path : string

URL / path to prepend full URL addressing to.

makeInstance()

Creates an instance of a class taking into account the class-extensions API of TYPO3. USE THIS method instead of the PHP `new` keyword.

public static makeInstance(T> $className, mixed ...$constructorArguments) : T

For example, $obj = new myclass; should be $obj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance("myclass") instead.

You can also pass arguments for a constructor: GeneralUtility::makeInstance(\myClass::class, $arg1, $arg2, ..., $argN)

Parameters
$className : T>

name of the class to instantiate, must not be empty and not start with a backslash

$constructorArguments : mixed
Tags
template

T of object

throws
InvalidArgumentException

if $className is empty or starts with a backslash

Return values
T

the created instance

makeInstanceForDi()

Creates a class taking implementation settings and class aliases into account.

public static makeInstanceForDi(T> $className, array<int, mixed> ...$constructorArguments) : T

Intended to be used to create objects by the dependency injection container.

Parameters
$className : T>

name of the class to instantiate

$constructorArguments : array<int, mixed>

Arguments for the constructor

Internal
Tags
template

T of object

Return values
T

the created instance

makeInstanceService()

Find the best service and check if it works.

public static makeInstanceService(string $serviceType[, string $serviceSubType = '' ][, array<string|int, mixed> $excludeServiceKeys = [] ]) : object|array<string|int, string>|false

Returns object of the service class.

This method is used for the legacy ExtensionManager:addService() mechanism, not with Dependency-Injected services. In practice, all remaining core uses of this mechanism are authentication services, which all have an info property.

Parameters
$serviceType : string

Type of service (service key).

$serviceSubType : string = ''

Sub type like file extensions or similar. Defined by the service.

$excludeServiceKeys : array<string|int, mixed> = []

List of service keys which should be excluded in the search for a service

Tags
throws
RuntimeException
Return values
object|array<string|int, string>|false

The service object or an array with error infos, or false if no service was found.

md5int()

Makes a positive integer hash out of the first 7 chars from the md5 hash of the input

public static md5int(string $str) : int
Parameters
$str : string

String to md5-hash

Return values
int

Returns 28bit integer-hash

mkdir()

Wrapper function for mkdir.

public static mkdir(string $newFolder) : bool

Sets folder permissions according to $GLOBALS['TYPO3_CONF_VARS']['SYS']['folderCreateMask'] and group ownership according to $GLOBALS['TYPO3_CONF_VARS']['SYS']['createGroup']

Parameters
$newFolder : string

Absolute path to folder, see PHP mkdir() function. Removes trailing slash internally.

Return values
bool

TRUE if operation was successful

mkdir_deep()

Creates a directory - including parent directories if necessary and sets permissions on newly created directories.

public static mkdir_deep(string $directory) : mixed
Parameters
$directory : string

Target directory to create

Tags
throws
InvalidArgumentException

If $directory is not a string

throws
RuntimeException

If directory could not be created

normalizeIPv6()

Normalize an IPv6 address to full length

public static normalizeIPv6(string $address) : string
Parameters
$address : string

Given IPv6 address

Return values
string

Normalized address

purgeInstances()

Purge all instances returned by makeInstance.

public static purgeInstances() : mixed

This function is most useful when called from tearDown in a test case to drop any instances that have been created by the tests.

Warning: This is a helper method for unit tests. Do not call this directly in production code!

Tags
see
makeInstance

quoteJSvalue()

Quotes a string for usage as JS parameter.

public static quoteJSvalue(string $value) : string
Parameters
$value : string

the string to encode, may be empty

Return values
string

the encoded value already quoted (with single quotes),

removeDotsFromTS()

Removes dots "." from end of a key identifier of TypoScript styled array.

public static removeDotsFromTS(array<string|int, mixed> $ts) : array<string|int, mixed>

array('key.' => array('property.' => 'value')) --> array('key' => array('property' => 'value'))

Parameters
$ts : array<string|int, mixed>

TypoScript configuration array

Return values
array<string|int, mixed>

TypoScript configuration array without dots at the end of all keys

removePrefixPathFromList()

Removes the absolute part of all files/folders in fileArr

public static removePrefixPathFromList(array<string|int, string> $fileArr, string $prefixToRemove) : array<string|int, string>|string
Parameters
$fileArr : array<string|int, string>

The file array to remove the prefix from

$prefixToRemove : string

The prefix path to remove (if found as first part of string!)

Return values
array<string|int, string>|string

The input $fileArr processed, or a string with an error message, when an error occurred.

removeSingletonInstance()

Removes the instance of a singleton class to be returned by `makeInstance`.

public static removeSingletonInstance(class-string $className, SingletonInterface $instance) : mixed

Warning: This is NOT a public API method and must not be used in own extensions! This method exists mostly for unit tests to inject a mock of a singleton class. If you use this, make sure to always combine this with getSingletonInstances() and resetSingletonInstances() in setUp() and tearDown() of the test class.

Parameters
$className : class-string
$instance : SingletonInterface
Internal
Tags
see
makeInstance
throws
InvalidArgumentException

resetSingletonInstances()

Set a group of singleton instances. Similar to `setSingletonInstance()`, but multiple instances can be set.

public static resetSingletonInstances(array<class-string, SingletonInterface$newSingletonInstances) : mixed

Warning: This is NOT a public API method and must not be used in own extensions! This method is usually only used in tests to restore the list of singletons in tearDown() that was backed up with getSingletonInstances() in setUp() and manipulated in tests with setSingletonInstance().

Parameters
$newSingletonInstances : array<class-string, SingletonInterface>
Internal

resolveBackPath()

Resolves "../" sections in the input path string.

public static resolveBackPath(string $pathStr) : string

For example "fileadmin/directory/../other_directory/" will be resolved to "fileadmin/other_directory/"

Parameters
$pathStr : string

File path in which "/../" is resolved

Return values
string

revExplode()

Reverse explode which explodes the string counting from behind.

public static revExplode(string $delimiter, string $string[, int $limit = 0 ]) : array<int, string>

Note: The delimiter has to given in the reverse order as it is occurring within the string.

GeneralUtility::revExplode('[]', '[my][words][here]', 2) ==> array('[my][words', 'here]')

Parameters
$delimiter : string

Delimiter string to explode with

$string : string

The string to explode

$limit : int = 0

Number of array entries

Return values
array<int, string>

Exploded values

rmdir()

Wrapper function for rmdir, allowing recursive deletion of folders and files

public static rmdir(string $path[, bool $removeNonEmpty = false ]) : bool
Parameters
$path : string

Absolute path to folder, see PHP rmdir() function. Removes trailing slash internally.

$removeNonEmpty : bool = false

Allow deletion of non-empty directories

Return values
bool

TRUE if operation was successful

sanitizeCssVariableValue()

Very, very, very basic CSS sanitizer which removes `{`, `}`, `\n`, `\r` from CSS variable values and encodes potential HTML entities `<`+`>`.

public static sanitizeCssVariableValue(string $value) : string
Parameters
$value : string
Return values
string

sanitizeLocalUrl()

Checks if a given string is a valid frame URL to be loaded in the backend.

public static sanitizeLocalUrl([string $url = '' ]) : string

If the given url is empty or considered to be harmless, it is returned as is, else the event is logged and an empty string is returned.

Parameters
$url : string = ''

potential URL to check

Return values
string

$url or empty string

setContainer()

public static setContainer(ContainerInterface $container) : void
Parameters
$container : ContainerInterface
Internal

setIndpEnv()

This method is only for testing and should never be used outside tests.

public static setIndpEnv(non-empty-string $envName, string|bool|array<string, string|bool|null>|null $value) : mixed
Parameters
$envName : non-empty-string
$value : string|bool|array<string, string|bool|null>|null
Internal

setSingletonInstance()

Sets the instance of a singleton class to be returned by `makeInstance`.

public static setSingletonInstance(class-string $className, SingletonInterface $instance) : mixed

If this function is called multiple times for the same $className, makeInstance will return the last set instance.

Warning: This is NOT a public API method and must not be used in own extensions! This method exists mostly for unit tests to inject a mock of a singleton class. If you use this, make sure to always combine this with getSingletonInstances() and resetSingletonInstances() in setUp() and tearDown() of the test class.

Parameters
$className : class-string
$instance : SingletonInterface
Internal
Tags
see
makeInstance

split_fileref()

Splits a reference to a file in 5 parts

public static split_fileref(string $fileNameWithPath) : array<string, string>
Parameters
$fileNameWithPath : string

File name with path to be analyzed (must exist if open_basedir is set)

Return values
array<string, string>

Contains keys [path], [file], [filebody], [fileext], [realFileext]

split_tag_attributes()

Returns an array with the 'components' from an attribute list from an HTML tag. The result is normally analyzed by get_tag_attributes Removes tag-name if found

public static split_tag_attributes(string $tag) : array<string|int, string>
Parameters
$tag : string

HTML-tag string (or attributes only)

Return values
array<string|int, string>

Array with the attribute values.

splitCalc()

This splits a string by the chars in $operators (typical /+-*) and returns an array with them in

public static splitCalc(string $string, string $operators) : array<int, array<int, string>>
Parameters
$string : string

Input string, eg "123 + 456 / 789 - 4

$operators : string

Operators to split by, typically "/+-*

Tags
see
ContentObjectRenderer::calc()
see
GifBuilder::calcOffset()
Return values
array<int, array<int, string>>

Array with operators and operands separated.

tempnam()

Create temporary filename (Create file with unique file name) This function should be used for getting temporary file names - will make your applications safe for open_basedir = on REMEMBER to delete the temporary files after use! This is done by \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile()

public static tempnam(string $filePrefix[, string $fileSuffix = '' ]) : non-empty-string
Parameters
$filePrefix : string

Prefix for temporary file

$fileSuffix : string = ''

Suffix for temporary file, for example a special file extension

Tags
see
unlink_tempfile()
see
upload_to_tempfile()
Return values
non-empty-string

result from PHP function tempnam() with the temp/var folder prefixed.

trimExplode()

Explodes a string and removes whitespace-only values.

public static trimExplode(string $delim, string $string[, bool $removeEmptyValues = false ][, int $limit = 0 ]) : array<int, string>

If $removeEmptyValues is set, then all values that contain only whitespace are removed.

Each item will have leading and trailing whitespace removed. However, if the tail items are returned as a single array item, their internal whitespace will not be modified.

Parameters
$delim : string

Delimiter string to explode with

$string : string

The string to explode

$removeEmptyValues : bool = false

If set, all empty values will be removed in output

$limit : int = 0

If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string. If the limit parameter is negative, all components except the last -limit are returned.

Tags
phpstan-return

($removeEmptyValues is true ? list : list) Exploded values

Return values
array<int, string>

Exploded values

underscoredToLowerCamelCase()

Returns a given string with underscores as lowerCamelCase.

public static underscoredToLowerCamelCase(string $string) : string

Example: Converts minimal_value to minimalValue

Parameters
$string : string

String to be converted to camel case

Return values
string

lowerCamelCasedWord

underscoredToUpperCamelCase()

Returns a given string with underscores as UpperCamelCase.

public static underscoredToUpperCamelCase(string $string) : string

Example: Converts blog_example to BlogExample

Parameters
$string : string

String to be converted to camel case

Return values
string

UpperCamelCasedWord

Deletes (unlink) a temporary filename in the var/ or typo3temp folder given as input.

public static unlink_tempfile(string $uploadedTempFileName) : bool|null

The function will check that the file exists, is within TYPO3's var/ or typo3temp/ folder and does not contain back-spaces ("../") so it should be pretty safe. Use this after upload_to_tempfile() or tempnam() from this class!

Parameters
$uploadedTempFileName : string

absolute file path - must reside within var/ or typo3temp/ folder.

Tags
see
upload_to_tempfile()
see
tempnam()
Return values
bool|null

Returns TRUE if the file was unlink()'ed

upload_copy_move()

Moves $source file to $destination if uploaded, otherwise try to make a copy

public static upload_copy_move(string $source, string $destination) : bool
Parameters
$source : string

Source file, absolute path

$destination : string

Destination file, absolute path

Tags
see
upload_to_tempfile()
Return values
bool

Returns TRUE if the file was moved.

upload_to_tempfile()

Will move an uploaded file (normally in "/tmp/xxxxx") to a temporary filename in Environment::getProjectPath() . "var/" from where TYPO3 can use it.

public static upload_to_tempfile(string $uploadedFileName) : string

Use this function to move uploaded files to where you can work on them. REMEMBER to use \TYPO3\CMS\Core\Utility\GeneralUtility::unlink_tempfile() afterwards - otherwise temp-files will build up! They are NOT automatically deleted in the temporary folder!

Parameters
$uploadedFileName : string

The temporary uploaded filename, eg. $_FILES['[upload field name here]']['tmp_name']

Tags
see
unlink_tempfile()
see
upload_copy_move()
Return values
string

If a new file was successfully created, return its filename, otherwise blank string.

validEmail()

Checking syntax of input email address

public static validEmail(string $email) : bool
Parameters
$email : string

Input string to evaluate

Return values
bool

Returns TRUE if the $email address (input string) is valid

validIP()

Validate a given IP address.

public static validIP(string $ip) : bool

Possible format are IPv4 and IPv6.

Parameters
$ip : string

IP address to be tested

Return values
bool

TRUE if $ip is either of IPv4 or IPv6 format.

validIPv4()

Validate a given IP address to the IPv4 address format.

public static validIPv4(string $ip) : bool

Example for possible format: 10.0.45.99

Parameters
$ip : string

IP address to be tested

Return values
bool

TRUE if $ip is of IPv4 format.

validIPv6()

Validate a given IP address to the IPv6 address format.

public static validIPv6(string $ip) : bool

Example for possible format: 43FB::BB3F:A0A0:0 | ::1

Parameters
$ip : string

IP address to be tested

Return values
bool

TRUE if $ip is of IPv6 format.

validPathStr()

Checks for malicious file paths.

public static validPathStr(string $theFile) : bool

Returns TRUE if no '//', '..', '' or control characters are found in the $theFile. This should make sure that the path is not pointing 'backwards' and further doesn't contain double/back slashes. So it's compatible with the UNIX style path strings valid for TYPO3 internally.

Parameters
$theFile : string

File path to evaluate

Tags
see
https://php.net/manual/en/security.filesystem.nullbytes.php
Return values
bool

TRUE, $theFile is allowed path string, FALSE otherwise

wrapJS()

Wraps JavaScript code XHTML ready with <script>-tags Automatic re-indenting of the JS code is done by using the first line as indent reference.

public static wrapJS(string $string[, array<string, string> $attributes = [] ]) : string

This is nice for indenting JS code with PHP code on the same level.

Parameters
$string : string

JavaScript code

$attributes : array<string, string> = []

(optional) script tag HTML attributes

Return values
string

The wrapped JS code, ready to put into a XHTML page

writeFile()

Writes $content to the file $file

public static writeFile(string $file, string $content[, bool $changePermissions = false ]) : bool
Parameters
$file : string

Filepath to write to

$content : string

Content to write

$changePermissions : bool = false

If TRUE, permissions are forced to be set

Return values
bool

TRUE if the file was successfully opened and written to.

writeFileToTypo3tempDir()

Writes $content to a filename in the typo3temp/ folder (and possibly one or two subfolders...) Accepts an additional subdirectory in the file path!

public static writeFileToTypo3tempDir(string $filepath, string $content) : string|null
Parameters
$filepath : string

Absolute file path to write within the typo3temp/ or Environment::getVarPath() folder - the file path must be prefixed with this path

$content : string

Content string to write

Return values
string|null

Returns NULL on success, otherwise an error string telling about the problem.

writeJavaScriptContentToTemporaryFile()

Writes string to a temporary file named after the md5-hash of the string Quite useful for extensions adding their custom built JavaScript during runtime.

public static writeJavaScriptContentToTemporaryFile(string $content) : string
Parameters
$content : string

JavaScript to write to file.

Return values
string

filename to include in the <script> tag

writeStyleSheetContentToTemporaryFile()

Writes string to a temporary file named after the md5-hash of the string Quite useful for extensions adding their custom built StyleSheet during runtime.

public static writeStyleSheetContentToTemporaryFile(string $content) : string
Parameters
$content : string

CSS styles to write to file.

Return values
string

filename to include in the tag

xml2array()

Converts an XML string to a PHP array.

public static xml2array(string $string[, string $NSprefix = '' ][, bool $reportDocTag = false ]) : mixed

This is the reverse function of array2xml() This is a wrapper for xml2arrayProcess that adds a two-level cache

Parameters
$string : string

XML content to convert into an array

$NSprefix : string = ''

The tag-prefix resolve, eg. a namespace like "T3:"

$reportDocTag : bool = false

If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array

Tags
see
array2xml()
see
xml2arrayProcess()
Return values
mixed

If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.

xml2arrayProcess()

Converts an XML string to a PHP array.

public static xml2arrayProcess(string $string[, string $NSprefix = '' ][, bool $reportDocTag = false ]) : mixed

This is the reverse function of array2xml()

Parameters
$string : string

XML content to convert into an array

$NSprefix : string = ''

The tag-prefix resolve, eg. a namespace like "T3:"

$reportDocTag : bool = false

If set, the document tag will be set in the key "_DOCUMENT_TAG" of the output array

Tags
see
array2xml()
Return values
mixed

If the parsing had errors, a string with the error message is returned. Otherwise an array with the content.

xml2tree()

Parses XML input into a PHP array with associative keys

public static xml2tree(string $string[, int $depth = 999 ][, array<string|int, mixed> $parserOptions = [] ]) : mixed
Parameters
$string : string

XML data input

$depth : int = 999

Number of element levels to resolve the XML into an array. Any further structure will be set as XML.

$parserOptions : array<string|int, mixed> = []

Options that will be passed to PHP's xml_parser_set_option()

Return values
mixed

The array with the parsed structure unless the XML parser returns with an error in which case the error message string is returned.

xmlRecompileFromStructValArray()

This implodes an array of XML parts (made with xml_parse_into_struct()) into XML again.

public static xmlRecompileFromStructValArray(array<int, array<string, mixed>> $vals) : string
Parameters
$vals : array<int, array<string, mixed>>

An array of XML parts, see xml2tree

Return values
string

Re-compiled XML data.

checkInstanceClassName()

Checks that `$className` is non-empty and that `$instance` is an instance of `$className`.

protected static checkInstanceClassName(string $className, object $instance) : mixed
Parameters
$className : string
$instance : object
Tags
throws
InvalidArgumentException

if $className is empty or if $instance is no instance of $className

classHasImplementation()

Checks if a class has a configured implementation

protected static classHasImplementation(class-string $className) : bool
Parameters
$className : class-string
Return values
bool

createDirectoryPath()

Creates directories for the specified paths if they do not exist. This functions sets proper permission mask but does not set proper user and group.

protected static createDirectoryPath(string $fullDirectoryPath) : string
Parameters
$fullDirectoryPath : string
Tags
static
see
GeneralUtility::mkdir_deep
throws
RuntimeException

If directory could not be created

Return values
string

Path to the the first created directory in the hierarchy

encodeFileSystemPathComponentForUrlPath()

protected static encodeFileSystemPathComponentForUrlPath(string $path) : string
Parameters
$path : string
Return values
string

getImplementationForClass()

Returns the configured implementation of the class

protected static getImplementationForClass(class-string $className) : class-string
Parameters
$className : class-string
Return values
class-string

getLogger()

protected static getLogger() : LoggerInterface
Return values
LoggerInterface

webserverUsesHttps()

Determine if the webserver uses HTTPS.

protected static webserverUsesHttps() : bool

HEADS UP: This does not check if the client performed a HTTPS request, as possible proxies are not taken into account. It provides raw information about the current webservers configuration only.

Return values
bool

        
On this page

Search results