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
2. Use glob() to find files
3. Get memory usage information
4. Get CPU usage information
5. Get system constants
6. Generate unique id
7. Serialization
8. String compression
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:
// Two defaults Function of 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 PHP's variable parameter usage, which uses the func_get_args() method:
// Yes, the formal 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 literally understand their purpose, but when you see glob(), you may not know what it is used for. , in fact, glob() is the same as scandir() and can be used to find files. Please see the following usage:
// Get all files with PHP suffix
$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 multiple suffixes:
// 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:
$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:
$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. Get memory usage information. PHP's memory recycling mechanism is already very powerful. You can also use PHP scripts to get the current memory usage. Call the memory_get_usage() function to get the current memory usage, and call the memory_get_peak_usage() function to get the memory. peak value used. The reference code is as follows:
echo "Initial: ".memory_get_usage()." bytes n" ;
/* Output
Initial: 361400 bytes
*/
// Use memory
for ($i = 0; $i $ array []= md5($i);
}
// Delete half of the memory
for ($i = 0; $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. Obtain CPU usage information. After obtaining memory usage, you can also use PHP's getrusage() to obtain CPU usage. This method is not available under Windows.
print_r(getrusage());
/* Output
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] => .tv_sec] => 0
[ru_stime.tv_usec] => 6269
[ru_stime.tv_sec] => 0
)
*/
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);
/* Output
User time: 0.011552
System time: 0
*/
for($i=0;$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);
/* Output
User time: 1.424592
System time: 0.004204
*/
// keep calling microtime for about 3 seconds
while(microtime(true) – $start }
$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
*/
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__), and 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 .
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:
// 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 a unique ID. Many friends use md5() to generate a unique number, but md5() has several shortcomings: 1. Unordered, 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(). The following is the usage:
// generate unique string
echo uniqid();
/* Output
4bd67c947233e
*/
// generate another unique string
echo uniqid();
/* Output
4bd67c9472340
*/
This algorithm is generated based on the CPU timestamp, so in a similar time period, 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, such as:
// Prefix
echo uniqid(' foo_');
/* Output
foo_4bd67d6cd8b8f
*/
// Has more entropy
echo uniqid(",true);
/* Output
4bd67d6cd8b926 .12135106
*/
// Both
echo uniqid('bar_',true);
/* Output
bar_4bd67da367b650.43684647
*/
7. Serialization You may use the PHP serialization function more often and it is more common. When you need to save data to a database or file, you can use the serialize() and unserialize() methods in PHP. To implement serialization and deserialization, the code is as follows:
// 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";}
*/
//Deserialization
$newvar = unserialize($string);
print_r($newvar);
/* Output
Array
(
[0] => hello
[1] => 42
[2] => Array
(
[0] => 1
[1] => two
)
[3] => apple
)
*/
How to serialize it into json format? Don’t worry, php has already done it for you. Use php Users of versions 5.2 and above can use the json_encode() and json_decode() functions to serialize json format. The code is as follows:
// 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:
$string =
"Let the pain itself be a lot, it will follow
adipiscing elit. Now let it elit my ultricies
adipiscing. No facilisi. Praesent pulvinar,
wise or feugiat vestibulum , there is no price for medicine, no one will suffer before. Curabitur sed eu elit. Praesent ipsum diam. But it's great if it's soft, but now, it's just that it's soft euismod urn members ";
$compressed = gzcompress($string);
echo "Original size: ". strlen($string)."n";
/* output original size
Original size: 800
*/
echo "Compressed size: ". strlen($compressed)."n";
/* 解发剧后后图像
Compressed size: 418
*/
// 解光剧
$original = gzuncompress($compressed);
It's almost 50% compression ratio. At the same time, you can also use gzencode() and gzdecode() function to compress, only use different compression algorithms.
Above is 8个安全必备的PHP function, is it not very practical?
http://www.bkjia.com/PHPjc/824926.html
www.bkjia.com
true
http: //www.bkjia.com/PHPjc/824926.html
做过PHP 可件的电影员光可以公开,There are many built-in functions in PHP, you can grasp them, you can help You're in the middle of PHP development...

PHPidentifiesauser'ssessionusingsessioncookiesandsessionIDs.1)Whensession_start()iscalled,PHPgeneratesauniquesessionIDstoredinacookienamedPHPSESSIDontheuser'sbrowser.2)ThisIDallowsPHPtoretrievesessiondatafromtheserver.

The security of PHP sessions can be achieved through the following measures: 1. Use session_regenerate_id() to regenerate the session ID when the user logs in or is an important operation. 2. Encrypt the transmission session ID through the HTTPS protocol. 3. Use session_save_path() to specify the secure directory to store session data and set permissions correctly.

PHPsessionfilesarestoredinthedirectoryspecifiedbysession.save_path,typically/tmponUnix-likesystemsorC:\Windows\TemponWindows.Tocustomizethis:1)Usesession_save_path()tosetacustomdirectory,ensuringit'swritable;2)Verifythecustomdirectoryexistsandiswrita

ToretrievedatafromaPHPsession,startthesessionwithsession_start()andaccessvariablesinthe$_SESSIONarray.Forexample:1)Startthesession:session_start().2)Retrievedata:$username=$_SESSION['username'];echo"Welcome,".$username;.Sessionsareserver-si

The steps to build an efficient shopping cart system using sessions include: 1) Understand the definition and function of the session. The session is a server-side storage mechanism used to maintain user status across requests; 2) Implement basic session management, such as adding products to the shopping cart; 3) Expand to advanced usage, supporting product quantity management and deletion; 4) Optimize performance and security, by persisting session data and using secure session identifiers.

The article explains how to create, implement, and use interfaces in PHP, focusing on their benefits for code organization and maintainability.

The article discusses the differences between crypt() and password_hash() in PHP for password hashing, focusing on their implementation, security, and suitability for modern web applications.

Article discusses preventing Cross-Site Scripting (XSS) in PHP through input validation, output encoding, and using tools like OWASP ESAPI and HTML Purifier.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download
The most popular open source editor

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 English version
Recommended: Win version, supports code prompts!
