Attention

TYPO3 v7 has reached its end-of-life November 30th, 2018 and is not maintained by the community anymore. Looking for a stable version? Use the version switch on the top left.

There is no further ELTS support. It is recommended that you upgrade your project and use a supported version of TYPO3.

Functions typically used and nice to know

These functions are generally just nice to know. They provide functionality which you will often need in TYPO3 applications and therefore they will save you time and make your applications easier for others to understand as well since you use commonly known functions.

Please take time to learn these functions!

\TYPO3\CMS\Core\Utility\GeneralUtility

Function

Comments

inList

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

if (\TYPO3\CMS\Core\Utility\GeneralUtility::inList('gif,jpg,png', $ext)) {//...}

isFirstPartOfStr

Returns true if the first part of input string matches the second argument.

\TYPO3\CMS\Core\Utility\GeneralUtility::isFirstPartOfStr($path, PATH_site);

formatSize

Formats a number of bytes as Kb/Mb/Gb for visual output.

Size formatting supports two keywords additionally to the list of labels:

  • iec: uses the Ki, Mi, etc prefixes and binary base (power of two, 1024)

  • si: uses the k, M, etc prefixes and decimal base (power of ten, 1000)

The default formatting is set to "iec" base size calculations on the same base as before. The fractional part, when present, will be two numbers.

The list of labels is still supported and defaults to using binary base. It is also possible to explicitly choose between binary or decimal base when it is used.

$size = \TYPO3\CMS\Core\Utility\GeneralUtility::formatSize(85123) . 'B';
echo $size; // output:  83.13 KiB

$size = \TYPO3\CMS\Core\Utility\GeneralUtility::formatSize(85123, 'si') . 'B';
echo $size; // output:  85.12 kB

$size = \TYPO3\CMS\Core\Utility\GeneralUtility::formatSize(85123, '| kB| MB| GB| TB| PB| EB| ZB| YB');
echo $size; // output:  83.13 kB

$size = \TYPO3\CMS\Core\Utility\GeneralUtility::formatSize(85123, '| kB| MB| GB| TB| PB| EB| ZB| YB', 1000);
echo $size; // output:  85.12 kB

validEmail

Evaluates a string as an email address.

if ($email && \TYPO3\CMS\Core\Utility\GeneralUtility::validEmail($email)) {

trimExplode

intExplode

revExplode

Various flavors of exploding a string by a token.

\TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode() - Explodes a string by a token and trims the whitespace away around each item. Optionally any zero-length elements are removed. Very often used to explode strings from configuration, user input etc. where whitespace can be expected between values but is insignificant.

array_unique(\TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(',', $rawExtList, 1));
\TYPO3\CMS\Core\Utility\GeneralUtility::trimExplode(chr(10), $content);

\TYPO3\CMS\Core\Utility\GeneralUtility::intExplode() - Explodes a by a token and converts each item to an integer value. Very useful to force integer values out of a value list, for instance for an SQL query.

// Make integer list
implode(\TYPO3\CMS\Core\Utility\GeneralUtility::intExplode(',', $row['subgroup']), ',');

\TYPO3\CMS\Core\Utility\GeneralUtility::revExplode() - Reverse explode() which allows you to explode a string into X parts but from the back of the string instead.

$p = \TYPO3\CMS\Core\Utility\GeneralUtility::revExplode('/', $path, 2);

array_merge_recursive_overrule

array_merge

Merging arrays with fixes for "PHP-bugs"

\TYPO3\CMS\Core\Utility\GeneralUtility::array_merge_recursive_overrule() - Merges two arrays recursively and "binary safe" (integer keys are overridden as well), overruling similar the values in the first array ($arr0) with the values of the second array ($arr1). In case of identical keys, i.e. keeping the values of the second.

\TYPO3\CMS\Core\Utility\GeneralUtility::array_merge() - An array_merge function where the keys are NOT renumbered as they happen to be with the real php- array_merge function. It is "binary safe" in the sense that integer keys are overridden as well.

array2xml_cs

xml2array

Serialization of PHP variables into XML.

These functions are made to serialize and unserialize PHParrays to XML files. They are used for the FlexForms content in TYPO3, Data Structure definitions etc. The XML output is optimized for readability since associative keys are used as tagnames. This also means that only alphanumeric characters are allowed in the tag names andonly 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 tagname "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.

\TYPO3\CMS\Core\Utility\GeneralUtility::array2xml_cs() - Converts a PHP array into an XML string:

\TYPO3\CMS\Core\Utility\GeneralUtility::array2xml_cs($this->FORMCFG['c'],'T3FormWizard');

\TYPO3\CMS\Core\Utility\GeneralUtility::xml2array() - Converts an XML string to a PHP array. This is the reverse function of array2xml_cs():

if ($this->xmlStorage)    {
    $cfgArr = \TYPO3\CMS\Core\Utility\GeneralUtility::xml2array($row[$this->P['field']]);
}

getURL

writeFile

Reading / Writing files

\TYPO3\CMS\Core\Utility\GeneralUtility::getURL() - Reads the full content of a file or URL. Used throughout the TYPO3 sources. Transparently takes care of Curl configuration, proxy setup, etc.

$templateCode = \TYPO3\CMS\Core\Utility\GeneralUtility::getURL($templateFile);

\TYPO3\CMS\Core\Utility\GeneralUtility::writeFile() - Writes a string into an absolute filename:

\TYPO3\CMS\Core\Utility\GeneralUtility::writeFile($extDirPath . $theFile, $fileData['content']);

split_fileref

Splits a reference to a file in 5 parts. Alternative to "path_info" and fixes some "PHP-bugs" which makes page_info() unattractive at times.

get_dirs

getFilesInDir

getAllFilesAndFoldersInPath

removePrefixPathFromList

Read content of file system directories.

\TYPO3\CMS\Core\Utility\GeneralUtility::get_dirs() - Returns an array with the names of folders in a specific path

if (@is_dir($path))    {
    $directories = \TYPO3\CMS\Core\Utility\GeneralUtility::get_dirs($path);
    if (is_array($directories))    {
        foreach($directories as $dirName)    {
            ...
        }
    }
}

\TYPO3\CMS\Core\Utility\GeneralUtility::getFilesInDir() - Returns an array with the names of files in a specific path

$sFiles = \TYPO3\CMS\Core\Utility\GeneralUtility::getFilesInDir(PATH_typo3conf ,'', 1, 1);
$files = \TYPO3\CMS\Core\Utility\GeneralUtility::getFilesInDir($dir, 'png,jpg,gif');

\TYPO3\CMS\Core\Utility\GeneralUtility::getAllFilesAndFoldersInPath() - Recursively gather all files and folders of a path.

\TYPO3\CMS\Core\Utility\GeneralUtility::removePrefixPathFromList() - Removes the absolute part of all files/folders in fileArr (useful for post processing of content from \TYPO3\CMS\Core\Utility\GeneralUtility::getAllFilesAndFoldersInPath())

    // Get all files with absolute paths prefixed:
$fileList_abs =
    \TYPO3\CMS\Core\Utility\GeneralUtility::getAllFilesAndFoldersInPath(array(), $absPath, 'php,inc');

    // Traverse files and remove abs path from each (becomes relative)
$fileList_rel =
    \TYPO3\CMS\Core\Utility\GeneralUtility::removePrefixPathFromList($fileList_abs, $absPath);

implodeArrayForUrl

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

$pString = \TYPO3\CMS\Core\Utility\GeneralUtility::implodeArrayForUrl('', $params);

get_tag_attributes

implodeAttributes

Works on HTML tag attributes

\TYPO3\CMS\Core\Utility\GeneralUtility::get_tag_attributes() - Returns an array with all attributes of the input HTML tag as key/value pairs. Attributes are only lowercase a-z

$attribs = \TYPO3\CMS\Core\Utility\GeneralUtility::get_tag_attributes('<' . $subparts[0] . '>');

\TYPO3\CMS\Core\Utility\GeneralUtility::implodeAttributes() - Implodes attributes in the array $arr for an attribute list in e.g. and HTML tag (with quotes)

$tag = '<img ' . \TYPO3\CMS\Core\Utility\GeneralUtility::implodeAttributes($attribs, 1) . ' />';

resolveBackPath

Resolves ../ sections in the input path string. For example fileadmin/directory/../other_directory/ will be resolved to fileadmin/other_directory/

callUserFunction

getUserObj

General purpose functions for calling user functions (creating hooks).

See the chapter about Creating hooks in this document for detailed description of these functions.

\TYPO3\CMS\Core\Utility\GeneralUtility::callUserFunction() - Calls a user-defined function/method in class. Such a function/method should look like this: function proc(&$params, &$ref) {...}

function procItems($items,$iArray,$config,$table,$row,$field) {
    global $TCA;
    $params=array();
    $params['items'] = &$items;
    $params['config'] = $config;
    $params['TSconfig'] = $iArray;
    $params['table'] = $table;
    $params['row'] = $row;
    $params['field'] = $field;

    \TYPO3\CMS\Core\Utility\GeneralUtility::callUserFunction(
        $config['itemsProcFunc'],
        $params,
        $this
    );
    return $items;
}

\TYPO3\CMS\Core\Utility\GeneralUtility::getUserObj() - Creates and returns reference to a user defined object:

$_procObj = &\TYPO3\CMS\Core\Utility\GeneralUtility::getUserObj($_classRef);
$_procObj->pObj = &$this;
$value = $_procObj->transform_rte($value,$this);

linkThisScript

Returns the URL to the current script. You can pass an array with 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.

\TYPO3\CMS\Core\Utility\MathUtility

Function

Comments

forceIntegerInRange

Forces the input variable (integer) into the boundaries of $min and $max:

\TYPO3\CMS\Core\Utility\MathUtility::forceIntegerInRange($row['priority'], 1, 5);

canBeInterpretedAsInteger

Tests if the input is an integer.

\TYPO3\CMS\Backend\Utility\BackendUtility

Function

Comments

getRecord

getRecordsByField

Functions for selecting records by uid or field value.

\TYPO3\CMS\Backend\Utility\BackendUtility::getRecord() - Gets record with uid=$uid from $table

  // Getting array with title field from a page:
            \TYPO3\CMS\Backend\Utility\BackendUtility::getRecord('pages', intval($row['shortcut']), 'title');

  // Getting a full record with permission WHERE clause
$pageinfo = \TYPO3\CMS\Backend\Utility\BackendUtility::getRecord(
        'pages',
        $id,
        '*',
        ($perms_clause ? ' AND ' . $perms_clause : '')
    );

\TYPO3\CMS\Backend\Utility\BackendUtility::getRecordsByField() - Returns records from table, $theTable, where a field ($theField) equals the value, $theValue

    // Checking if the id-parameter is an alias.
if (!\TYPO3\CMS\Core\Utility\MathUtility::canBeInterpretedAsInteger($id))    {
    list($idPartR) =
        \TYPO3\CMS\Backend\Utility\BackendUtility::getRecordsByField('pages', 'alias', $id);
    $id = intval($idPartR['uid']);
}

getRecordPath

Returns the path (visually) of a page $uid, fx. "/First page/Second page/Another subpage"

$label = \TYPO3\CMS\Backend\Utility\BackendUtility::getRecordPath(
        intval($row['shortcut']),
        $perms_clause,
        20
    );

readPageAccess

Returns a page record (of page with $id) with an extra field _thePath set to the record path if the WHERE clause, $perms_clause, selects the record. Thus is works as an access check that returns a page record if access was granted, otherwise not.

$perms_clause = $GLOBALS['BE_USER']->getPagePermsClause(1);
$pageinfo = \TYPO3\CMS\Backend\Utility\BackendUtility::readPageAccess($id, $perms_clause);

date

datetime

calcAge

Date/Time formatting functions using date/time format from $TYPO3_CONF_VARS.

\TYPO3\CMS\Backend\Utility\BackendUtility::date() - Returns $tstamp formatted as "ddmmyy" (According to $TYPO3_CONF_VARS['SYS']['ddmmyy'])

\TYPO3\CMS\Backend\Utility\BackendUtility::datetime($row['crdate'])

\TYPO3\CMS\Backend\Utility\BackendUtility::datetime() - Returns $tstamp formatted as "ddmmyy hhmm" (According to $TYPO3_CONF_VARS['SYS']['ddmmyy'] and $TYPO3_CONF_VARS['SYS']['hhmm'])

\TYPO3\CMS\Backend\Utility\BackendUtility::datetime($row['item_mtime'])

\TYPO3\CMS\Backend\Utility\BackendUtility::calcAge() - Returns the "age" in minutes / hours / days / years of the number of $seconds given as input.

$agePrefixes = ' min| hrs| days| yrs';
\TYPO3\CMS\Backend\Utility\BackendUtility::calcAge(time()-$row['crdate'], $agePrefixes);

titleAttribForPages

Returns title attribute information for a page-record informing about id, alias, doktype, hidden, starttime, endtime, fe_group etc.

$out = \TYPO3\CMS\Backend\Utility\BackendUtility::titleAttribForPages($row, '', 0);
$out = \TYPO3\CMS\Backend\Utility\BackendUtility::titleAttribForPages($row, '1=1 ' . $this->clause, 0);

thumbCode

getThumbNail

Returns image tags for thumbnails

\TYPO3\CMS\Backend\Utility\BackendUtility::thumbCode() - Returns a linked image-tag for thumbnail(s)/fileicons/truetype-font-previews from a database row with a list of image files in a field. Slightly advanced. It's more likely you will need \TYPO3\CMS\Backend\Utility\BackendUtility::getThumbNail() to do the job.

\TYPO3\CMS\Backend\Utility\BackendUtility::getThumbNail() - Returns single image tag to thumbnail using a thumbnail script (like thumbs.php)

\TYPO3\CMS\Backend\Utility\BackendUtility::getThumbNail(
    $this->doc->backPath . 'thumbs.php',
    $filepath,
    'hspace="5" vspace="5" border="1"'
);

storeHash

getHash

Get/Set cache values.

\TYPO3\CMS\Backend\Utility\BackendUtility::storeHash() - Stores the string value $data in the "cache hash" table with the hash key, $hash, and visual/symbolic identification, $ident.

\TYPO3\CMS\Backend\Utility\BackendUtility::getHash() - Retrieves the string content stored with hash key, $hash, in "cache hash".

Example of how both functions are used together; first getHash() to fetch any possible content and if nothing was found how the content is generated and stored in the cache:

    // Parsing the user TS (or getting from cache)
$userTS = implode($TSdataArray,chr(10) . '[GLOBAL]' . chr(10));
$hash = md5('pageTS:' . $userTS);
$cachedContent = \TYPO3\CMS\Backend\Utility\BackendUtility::getHash($hash, 0);
$TSconfig = array();
if (isset($cachedContent))    {
    $TSconfig = unserialize($cachedContent);
} else {
    $parseObj = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\TypoScript\\Parser\\TypoScriptParser');
    $parseObj->parse($userTS);
    $TSconfig = $parseObj->setup;
    \TYPO3\CMS\Backend\Utility\BackendUtility::storeHash($hash,serialize($TSconfig), 'IDENT');
}

getRecordTitle

getProcessedValue

\TYPO3\CMS\Backend\Utility\BackendUtility::getRecordTitle() - Returns the "title" value from the input records field content.

$line.= \TYPO3\CMS\Backend\Utility\BackendUtility::getRecordTitle('tt_content', $row, 1);

\TYPO3\CMS\Backend\Utility\BackendUtility::getProcessedValue() - Returns a human readable output of a value from a record. For instance a database record relation would be looked up to display the title-value of that record. A checkbox with a "1" value would be "Yes", etc.

$outputValue = nl2br(
    htmlspecialchars(
        trim(
            \TYPO3\CMS\Core\Utility\GeneralUtility::fixed_lgd_cs(
                \TYPO3\CMS\Backend\Utility\BackendUtility::getProcessedValue(
                    $table,
                    $fieldName,
                    $row[$fieldName]
                ),
                250
            )
        )
    )
);

getPagesTSconfig

Returns the Page TSconfig for page with id, $id.

This example shows how an object path, mod.web_list is extracted from the Page TSconfig for page $id:

$modTSconfig = $GLOBALS['BE_USER']->getTSConfig(
    'mod.web_list',
    \TYPO3\CMS\Backend\Utility\BackendUtility::getPagesTSconfig($id)
);

\TYPO3\CMS\Core\Utility\ExtensionManagementUtility

Function

Comments

addTCAcolumns

Adding fields to an existing table definition in $TCA

For usage in ext_tables.php or Configuration/TCA/Overrides files.

// tt_address modified
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addTCAcolumns(
        'tt_address',
        array(
                'module_sys_dmail_category' => array('config' => array('type' => 'passthrough')),
                'module_sys_dmail_html' => array('config' => array('type' => 'passthrough'))
        )
);

addToAllTCAtypes

Makes fields visible in the TCEforms by adding them to all or selected "types"-configurations

For usage in ext_tables.php or Configuration/TCA/Overrides files.

\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addToAllTCAtypes(
        'fe_users',
        'tx_myext_newfield;;;;1-1-1, tx_myext_another_field'
);

allowTableOnStandardPages

Add table name to default list of allowed tables on pages (in $PAGES_TYPES)

For usage in ext_tables.php files.

\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::allowTableOnStandardPages('tt_board');

addModule

Adds a module (main or sub) to the backend interface.

Note

Extbase-based modules use a different registration API.

For usage in ext_tables.php files.

\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addModule(
        'user',
        'setup',
        'after:task',
        \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath($_EXTKEY) . 'mod/'
);

\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addModule(
        'tools',
        'txcoreunittestM1',
        '',
        \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath($_EXTKEY) . 'mod1/'
);

insertModuleFunction

Adds a "Function menu module" ("third level module") to an existing function menu for some other backend module

For usage in ext_tables.php files.

\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::insertModuleFunction(
        'web_func',
        'tx_cmsplaintextimport_webfunc',
        \TYPO3\CMS\Core\Utility\ExtensionManagementUtility::extPath($_EXTKEY) .
                'class.tx_cmsplaintextimport_webfunc.php',
        'LLL:EXT:cms_plaintext_import/locallang.xlf:menu_1'
);

addPlugin

Adds an entry to the list of plugins in content elements of type "Insert plugin"

Note

Extbase-based plug-ins use a different registration API.

For usage in ext_tables.php files.

\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addPlugin(
        array(
                'LLL:EXT:examples/Resources/Private/Language/locallang_db.xlf:tt_content.list_type_pi1',
                $_EXTKEY . '_pi1'
        ),
        'list_type'
);

addPItoST43

Add PlugIn to Static Template #43

When adding a frontend plugin you will have to add both an entry to the TCA definition of tt_content table AND to the TypoScript template which must initiate the rendering. Since the static template with uid 43 is the "content.default" and practically always used for rendering the content elements it's very useful to have this function automatically adding the necessary TypoScript for calling your plugin. It will also work for the extension "css_styled_content"

For usage in ext_localconf.php files.

\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addPItoST43($_EXTKEY);

registerPageTSConfigFile

Adds an option in the page properties to include a page TSconfig file (the same way as TypoScript static templates are included).

Register PageTS config files in Configuration/TCA/Overrides/pages.php of any extension, which will be shown afterwards at the newly introduced field.

Note

The included files from the pages in the rootline are included after the default page TSconfig and before the normal TSconfig from the pages in the rootline.

\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::registerPageTSConfigFile('extension_name', 'Configuration/PageTS/myPageTSconfigFile.txt', 'My special config');