note 129069 added to function.strtok
| From: | bohwaz at main dot php dot net | Date: | Sun, 26 Nov 2023 16:00:48 +0000 |
| Subject: | note 129069 added to function.strtok | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-221023@lists.php.net to get a copy of this message | ||
Please note that strtok memory is shared between all PHP code currently executed, even included
files. This can bite you in unexpected ways if you are not careful.
For example:
<?php
$path = 'dir/file.ext';
$dir_name = strtok($path, '/');
if ($dir_name !== (new Module)->getAllowedDirName()) {
throw new \Exception('Invalid directory name');
}
$file_name = strtok('');
?>
Seems easy enough, but if your Module class is not loaded, this triggers the autoloader. The
autoloader *MAY* use strtok inside its loading code.
Or your Module class *MAY* use strtok inside its constructor.
This means you will never get your $file_name correctly.
So: you should *always* group strtok calls, without any external code between two strtok calls.
This would be OK:
<?php
$path = 'dir/file.ext';
$dir_name = strtok($path, '/');
$file_name = strtok('');
if ($dir_name !== (new Module)->getAllowedDirName()) {
throw new \Exception('Invalid directory name');
}
?>
This might cause issues:
<?php
$path = 'one/two#three';
$a = strtok($path, '/');
$b = strtok(Module::NAME_SEPARATOR);
$c = strtok('');
?>
Because your autoloader might be using strtok.
This would be avoided by fetching all parameters used in strtok *before* the calls:
<?php
$path = 'one/two#three';
$separator = Module::NAME_SEPARATOR;
$a = strtok($path, '/');
$b = strtok($separator);
$c = strtok('');
?>
----
Server IP: 45.112.84.4
Probable Submitter: 45.91.157.134 (proxied: 2a02:8429:27d2:9a01:de71:96ff:feb9:774c)
----
Manual Page -- https://php.net/manual/en/function.strtok.php
Edit -- https://main.php.net/note/edit/129069
Del: integrated -- https://main.php.net/note/delete/129069/integrated
Del: useless -- https://main.php.net/note/delete/129069/useless
Del: bad code -- https://main.php.net/note/delete/129069/bad+code
Del: spam -- https://main.php.net/note/delete/129069/spam
Del: non-english -- https://main.php.net/note/delete/129069/non-english
Del: in docs -- https://main.php.net/note/delete/129069/in+docs
Del: other reasons-- https://main.php.net/note/delete/129069
Reject -- https://main.php.net/note/reject/129069
Search -- https://main.php.net/manage/user-notes.php