Programmers who have done PHP development should know that there are many built-in functions in PHP. Mastering them can help you become more comfortable in PHP development. This article will share 8 essential PHP functions for development, each of which They are all very practical and I hope all PHP developers can master them.
1. Pass any number of function parameters
In .NET or JAVA programming, the number of function parameters is generally fixed, but PHP allows you to use any number of parameters.The following example shows you the default parameters of a PHP function:
Php code
-
// Function with two default parameters
-
function foo($arg1 = ”, $arg2 = ”) {
-
echo “arg1: $arg1n”;
-
echo “arg2: $arg2n”;
-
}
-
foo(‘hello’,’world’);
-
/* Output:
-
arg1: hello
-
arg2: world
-
*/
-
foo();
-
/* Output:
-
arg1:
-
arg2:
-
*/
-
The following example is the usage of variable parameters in PHP, which uses the [url=http://us2.php.net/manual/en/function.func-get-args.php]func_get_args()[/url] method:
-
// Yes, the parameter list is empty
-
function foo() {
-
// Get the array of all incoming parameters
-
$args = func_get_args();
-
foreach ($args as $k => $v) {
-
echo “arg”.($k+1).”: $vn”;
-
}
-
}
-
foo();
-
/* Nothing will be output */
-
foo(‘hello’);
-
/* Output
-
arg1: hello
-
*/
-
foo(‘hello’, ‘world’, ‘again’);
-
/* Output
-
arg1: hello
-
arg2: world
-
arg3: again
-
*/
2. Use glob() to find files
The function names of most PHP functions can understand their purpose literally, but when you see glob(), you may not know what it is used for. In fact, glob() is the same as scandir(). It can be used to find files, please see the usage below:
Php code
-
// Get all files with the suffix PHP
-
$files = glob(‘*.php’);
-
print_r($files);
-
/* Output:
-
Array
-
(
-
[0] => phptest.php
-
[1] => pi.php
-
[2] => post_output.php
-
[3] => test.php
-
)
-
*/
You can also search for various suffixes:
Php code
-
// Get PHP files and TXT files
-
$files = glob(‘*.{php,txt}’, GLOB_BRACE);
-
print_r($files);
-
/* Output:
-
Array
-
(
-
[0] => phptest.php
-
[1] => pi.php
-
[2] => post_output.php
-
[3] => test.php
-
[4] => log.txt
-
[5] => test.txt
-
)
-
*/
You can also add the path:
Php code
-
$files = glob(‘../images/a*.jpg’);
-
print_r($files);
-
/* Output:
-
Array
-
(
-
[0] => ../images/apple.jpg
-
[1] => ../images/art.jpg
-
)
-
*/
If you want to get the absolute path, you can call the realpath() function:
Php code
-
$files = glob(‘../images/a*.jpg’);
-
//applies the function to each array element
-
$files = array_map(‘realpath’,$files);
-
print_r($files);
-
/* output looks like:
-
Array
-
(
-
[0] => C:wampwwwimagesapple.jpg
-
[1] => C:wampwwwimagesart.jpg
-
)
-
*/
3. Obtain memory usage information
PHP's memory recycling mechanism is already very powerful. You can also use PHP scripts to obtain the current memory usage, call the memory_get_usage() function to obtain the current memory usage, and call the memory_get_peak_usage() function to obtain the peak memory usage. The reference code is as follows:
Php code
-
echo “Initial: “.memory_get_usage().” bytes n”;
-
/* Output
-
Initial: 361400 bytes
-
*/
-
//Use memory
-
for ($i = 0; $i < 100000; $i++) {
-
$array []= md5($i);
-
}
-
// Delete half of the memory
-
for ($i = 0; $i < 100000; $i++) {
-
unset($array[$i]);
-
}
-
echo “Final: “.memory_get_usage().” bytes n”;
-
/* prints
-
Final: 885912 bytes
-
*/
-
echo “Peak: “.memory_get_peak_usage().” bytes n”;
-
/* Output peak value
-
Peak: 13687072 bytes
-
*/
4. Get CPU usage information
After obtaining the memory usage, you can also use PHP's getrusage() to obtain the CPU usage. This method is not available under Windows.
Php代码
-
print_r(getrusage());
-
/* 输出
-
Array
-
(
-
[ru_oublock] => 0
-
[ru_inblock] => 0
-
[ru_msgsnd] => 2
-
[ru_msgrcv] => 3
-
[ru_maxrss] => 12692
-
[ru_ixrss] => 764
-
[ru_idrss] => 3864
-
[ru_minflt] => 94
-
[ru_majflt] => 0
-
[ru_nsignals] => 1
-
[ru_nvcsw] => 67
-
[ru_nivcsw] => 4
-
[ru_nswap] => 0
-
[ru_utime.tv_usec] => 0
-
[ru_utime.tv_sec] => 0
-
[ru_stime.tv_usec] => 6269
-
[ru_stime.tv_sec] => 0
-
)
-
*/
这个结构看上出很晦涩,除非你对CPU很了解。下面一些解释:
-
ru_oublock: 块输出操作
-
ru_inblock: 块输入操作
-
ru_msgsnd: 发送的message
-
ru_msgrcv: 收到的message
-
ru_maxrss: 最大驻留集大小
-
ru_ixrss: 全部共享内存大小
-
ru_idrss:全部非共享内存大小
-
ru_minflt: 页回收
-
ru_majflt: 页失效
-
ru_nsignals: 收到的信号
-
ru_nvcsw: 主动上下文切换
-
ru_nivcsw: 被动上下文切换
-
ru_nswap: 交换区
-
ru_utime.tv_usec: 用户态时间 (microseconds)
-
ru_utime.tv_sec: 用户态时间(seconds)
-
ru_stime.tv_usec: 系统内核时间 (microseconds)
-
ru_stime.tv_sec: 系统内核时间?(seconds)
要看到你的脚本消耗了多少CPU,我们需要看看“用户态的时间”和“系统内核时间”的值。秒和微秒部分是分别提供的,您可以把微秒值除以100万,并把它添加到秒的值后,可以得到有小数部分的秒数。
Php代码
-
// sleep for 3 seconds (non-busy)
-
sleep(3);
-
$data = getrusage();
-
echo “User time: “.
-
($data['ru_utime.tv_sec'] +
-
$data['ru_utime.tv_usec'] / 1000000);
-
echo “System time: “.
-
($data['ru_stime.tv_sec'] +
-
$data['ru_stime.tv_usec'] / 1000000);
-
/* 输出
-
User time: 0.011552
-
System time: 0
-
*/
sleep是不占用系统时间的,我们可以来看下面的一个例子:
Php代码
-
// loop 10 million times (busy)
-
for($i=0;$i<10000000;$i++) {
-
}
-
$data = getrusage();
-
echo “User time: “.
-
($data['ru_utime.tv_sec'] +
-
$data['ru_utime.tv_usec'] / 1000000);
-
echo “System time: “.
-
($data['ru_stime.tv_sec'] +
-
$data['ru_stime.tv_usec'] / 1000000);
-
/* 输出
-
User time: 1.424592
-
System time: 0.004204
-
*/
这花了大约14秒的CPU时间,几乎所有的都是用户的时间,因为没有系统调用。
系统时间是CPU花费在系统调用上的上执行内核指令的时间。Here is an example:
Php code
-
$start = microtime(true);
-
// keep calling microtime for about 3 seconds
-
while(microtime(true) – $start < 3) {
-
}
-
$data = getrusage();
-
echo “User time: “.
-
($data['ru_utime.tv_sec'] +
-
$data['ru_utime.tv_usec'] / 1000000);
-
echo “System time: “.
-
($data['ru_stime.tv_sec'] +
-
$data['ru_stime.tv_usec'] / 1000000);
-
/* prints
-
User time: 1.088171
-
System time: 1.675315
-
*/
We can see that the above example consumes more CPU.
5. Get system constants
PHP provides very useful system constants that allow you to get the current line number (__LINE__), file (__FILE__), directory (__DIR__), function name (__FUNCTION__), class name (__CLASS__), method name (__METHOD__) and namespace ( __NAMESPACE__), much like C language.
We can think that these things are mainly used for debugging, but not necessarily. For example, we can use ?__FILE__ when including other files (of course, you can also use __DIR__ after PHP 5.3). Here is an example.
Php code
-
// this is relative to the loaded script’s path
-
// it may cause problems when running scripts from different directories
-
require_once(‘config/database.php’);
-
// this is always relative to this file’s path
-
// no matter where it was included from
-
require_once(dirname(__FILE__) . ‘/config/database.php’);
The following is using __LINE__ to output some debug information, which will help you debug the program:
Php code
-
// some code
-
// …
-
my_debug(“some debug message”, __LINE__);
-
/* Output
-
Line 4: some debug message
-
*/
-
// some more code
-
// …
-
my_debug(“another debug message”, __LINE__);
-
/* Output
-
Line 11: another debug message
-
*/
-
function my_debug($msg, $line) {
-
echo “Line $line: $msgn”;
-
}
6. Generate unique id
Many friends use md5() to generate unique numbers, but md5() has several shortcomings: 1. Disorder, which leads to a decrease in sorting performance in the database. 2. Too long and requires more storage space. In fact, PHP comes with a function to generate a unique id. This function is uniqid().Here’s how to use it:
Php code
-
// generate unique string
-
echo uniqid();
-
/* Output
-
4bd67c947233e
-
*/
-
// generate another unique string
-
echo uniqid();
-
/* Output
-
4bd67c9472340
-
*/
This algorithm is generated based on CPU timestamps, so in similar time periods, the first few digits of the ID are the same, which also facilitates the sorting of IDs. If you want to better avoid duplication, you can add a prefix before the ID. ,like:
Php code
-
// Prefix
-
echo uniqid(‘foo_’);
-
/* Output
-
foo_4bd67d6cd8b8f
-
*/
-
// There is more entropy
-
echo uniqid(”,true);
-
/* Output
-
4bd67d6cd8b926.12135106
-
*/
-
// All
-
echo uniqid(‘bar_’,true);
-
/* Output
-
bar_4bd67da367b650.43684647
-
*/
7. Serialization
You may use PHP serialization function more and more commonly. When you need to save data to a database or file, you can use the serialize() and unserialize() methods in PHP to achieve serialization and deserialization. , the code is as follows:
Php code
-
// A complex array
-
$myvar = array(
-
‘hello’,
-
42,
-
array(1,’two’),
-
‘apple’
-
);
-
// Serialization
-
$string = serialize($myvar);
-
echo $string;
-
/* Output
-
a:4:{i:0;s:5:"hello";i:1;i:42;i:2;a:2:{i:0;i:1;i:1;s:3: "two";}i:3;s:5:"apple";}
-
*/
-
//Desequential instantiation
-
$newvar = unserialize($string);
-
print_r($newvar);
-
/* Output
-
Array
-
(
-
[0] => hello
-
[1] => 42
-
[2] => Array
-
(
-
[0] => 1
-
[1] => two
-
)
-
[3] => apple
-
)
-
*/
How to serialize into json format? Don’t worry, PHP has already done it for you. Users using PHP 5.2 or above can use the json_encode() and json_decode() functions to serialize json format. The code is as follows:
Php code
-
// a complex array
-
$myvar = array(
-
‘hello’,
-
42,
-
array(1,’two’),
-
‘apple’
-
);
-
// convert to a string
-
$string = json_encode($myvar);
-
echo $string;
-
/* prints
-
["hello",42,[1,"two"],"apple"]
-
*/
-
// you can reproduce the original variable
-
$newvar = json_decode($string);
-
print_r($newvar);
-
/* prints
-
Array
-
(
-
[0] => hello
-
[1] => 42
-
[2] => Array
-
(
-
[0] => 1
-
[1] => two
-
)
-
[3] => apple
-
)
-
*/
8. String compression
When we talk about compression, we may think of file compression. In fact, strings can also be compressed.PHP provides gzcompress() and gzuncompress() functions:
Php code
-
$string =
-
"The truth is that the pain itself is good, it will be successful.
-
customer service. Now let's get it out of my hands
-
coaching There is no easy way. It's a pillow,
-
wisdom or flight of the vestibule, I will not give the price of the hospital,
-
He did not raise the lake as much as before. Thank you very much.
-
let it be good, it will be able to attract the customer. Some
-
the price of any body that is targeted. Yes, and mass
-
but it was an ugly time of mourning. I'm sorry but I'm sorry
-
soft homework It is the very day, it will be the result of life
-
to decorate a, something from now In that great and pushing
-
to lay the ground But not my fear, but Lacinia
-
advertise But unless it's big, decorate it in soft, soft
-
but now. Even at just the right time for homework.
-
There is no need to fear chocolate and chocolate
-
not football. To drink the unsavory lake of football
-
that euismod urn members “;
-
$compressed = gzcompress($string);
-
echo "Original size:". strlen($string).”n”;
-
/* output original size
-
Original size: 800
-
*/
-
echo "Compressed size:". strlen($compressed)."n";
-
/* output 剧情后 size
-
Compressed size: 418
-
*/
-
// 解剧情
-
$original = gzuncompress($compressed);
At the same time, you can also use gzencode() and gzdecode() function to compress, only use different compression algorithms.
Above is the 8个安全必备的PHP function, is it not very practical?
原文出处:8个安全必备的PHP function
http://www.bkjia.com/PHPjc/735057.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/735057.htmlTechArticle 做过PHP 可件的电影员光可以这些,PHP has a lot of built-in functions, grasp all of them, it can help You're in the middle of PHP development...