做过PHP开发的程序员应该清楚,PHP中有很多内置的功能,掌握了它们,可以帮助你在做PHP开发时更加得心应手,本文将分享8个开发必备的PHP功能,个个都非常实用,希望各位PHP开发者能够掌握。
1、传递任意数量的函数参数
我们在.NET或者JAVA编程中,一般函数参数个数都是固定的,但是PHP允许你使用任意个数的参数。下面这个示例向你展示了PHP函数的默认参数:
Php代码
- // 两个默认参数的函数
- function foo($arg1 = ”, $arg2 = ”) {
- echo “arg1: $arg1\n”;
- echo “arg2: $arg2\n”;
- }
- foo(‘hello’,'world’);
- /* 输出:
- arg1: hello
- arg2: world
- */
- foo();
- /* 输出:
- arg1:
- arg2:
- */
- 下面这个示例是PHP的不定参数用法,其使用到了 [url=http://us2.php.net/manual/en/function.func-get-args.php]func_get_args()[/url]方法:
- // 是的,形参列表为空
- function foo() {
- // 取得所有的传入参数的数组
- $args = func_get_args();
- foreach ($args as $k => $v) {
- echo “arg”.($k+1).”: $v\n”;
- }
- }
- foo();
- /* 什么也不会输出 */
- foo(‘hello’);
- /* 输出
- arg1: hello
- */
- foo(‘hello’, ‘world’, ‘again’);
- /* 输出
- arg1: hello
- arg2: world
- arg3: again
- */
- // 取得所有的后缀为PHP的文件
- $files = glob(‘*.php’);
- print_r($files);
- /* 输出:
- Array
- (
- [0] => phptest.php
- [1] => pi.php
- [2] => post_output.php
- [3] => test.php
- )
- */
- // 取PHP文件和TXT文件
- $files = glob(‘*.{php,txt}’, GLOB_BRACE);
- print_r($files);
- /* 输出:
- Array
- (
- [0] => phptest.php
- [1] => pi.php
- [2] => post_output.php
- [3] => test.php
- [4] => log.txt
- [5] => test.txt
- )
- */
- $files = glob(‘../images/a*.jpg’);
- print_r($files);
- /* 输出:
- Array
- (
- [0] => ../images/apple.jpg
- [1] => ../images/art.jpg
- )
- */
- $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:\wamp\www\images\apple.jpg
- [1] => C:\wamp\www\images\art.jpg
- )
- */
- echo “Initial: “.memory_get_usage().” bytes \n”;
- /* 输出
- Initial: 361400 bytes
- */
- // 使用内存
- for ($i = 0; $i
- $array []= md5($i);
- }
- // 删除一半的内存
- 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”;
- /* 输出峰值
- Peak: 13687072 bytes
- */
- 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
- )
- */
- 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)
- // 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
- */
- // loop 10 million times (busy)
- 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);
- /* 输出
- User time: 1.424592
- System time: 0.004204
- */
- $start = microtime(true);
- // 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
- */
- // 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’);
- // some code
- // …
- my_debug(“some debug message”, __LINE__);
- /* 输出
- Line 4: some debug message
- */
- // some more code
- // …
- my_debug(“another debug message”, __LINE__);
- /* 输出
- Line 11: another debug message
- */
- function my_debug($msg, $line) {
- echo “Line $line: $msg\n”;
- }
- // generate unique string
- echo uniqid();
- /* 输出
- 4bd67c947233e
- */
- // generate another unique string
- echo uniqid();
- /* 输出
- 4bd67c9472340
- */
- // 前缀
- echo uniqid(‘foo_’);
- /* 输出
- foo_4bd67d6cd8b8f
- */
- // 有更多的熵
- echo uniqid(”,true);
- /* 输出
- 4bd67d6cd8b926.12135106
- */
- // 都有
- echo uniqid(‘bar_’,true);
- /* 输出
- bar_4bd67da367b650.43684647
- */
- // 一个复杂的数组
- $myvar = array(
- ‘hello’,
- 42,
- array(1,’two’),
- ‘apple’
- );
- // 序列化
- $string = serialize($myvar);
- echo $string;
- /* 输出
- 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”;}
- */
- // 反序例化
- $newvar = unserialize($string);
- print_r($newvar);
- /* 输出
- Array
- (
- [0] => hello
- [1] => 42
- [2] => Array
- (
- [0] => 1
- [1] => two
- )
- [3] => apple
- )
- */
- // 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
- )
- */
- $string =
- “Lorem ipsum dolor sit amet, consectetur
- adipiscing elit. Nunc ut elit id mi ultricies
- adipiscing. Nulla facilisi. Praesent pulvinar,
- sapien vel feugiat vestibulum, nulla dui pretium orci,
- non ultricies elit lacus quis ante. Lorem ipsum dolor
- sit amet, consectetur adipiscing elit. Aliquam
- pretium ullamcorper urna quis iaculis. Etiam ac massa
- sed turpis tempor luctus. Curabitur sed nibh eu elit
- mollis congue. Praesent ipsum diam, consectetur vitae
- ornare a, aliquam a nunc. In id magna pellentesque
- tellus posuere adipiscing. Sed non mi metus, at lacinia
- augue. Sed magna nisi, ornare in mollis in, mollis
- sed nunc. Etiam at justo in leo congue mollis.
- Nullam in neque eget metus hendrerit scelerisque
- eu non enim. Ut malesuada lacus eu nulla bibendum
- id euismod urna sodales. “;
- $compressed = gzcompress($string);
- echo “Original size: “. strlen($string).”\n”;
- /* 输出原始大小
- Original size: 800
- */
- echo “Compressed size: “. strlen($compressed).”\n”;
- /* 输出压缩后的大小
- Compressed size: 418
- */
- // 解压缩
- $original = gzuncompress($compressed);
原文出处:8个开发必备的PHP功能

PHPSession失效的原因包括配置錯誤、Cookie問題和Session過期。 1.配置錯誤:檢查並設置正確的session.save_path。 2.Cookie問題:確保Cookie設置正確。 3.Session過期:調整session.gc_maxlifetime值以延長會話時間。

在PHP中調試會話問題的方法包括:1.檢查會話是否正確啟動;2.驗證會話ID的傳遞;3.檢查會話數據的存儲和讀取;4.查看服務器配置。通過輸出會話ID和數據、查看會話文件內容等方法,可以有效診斷和解決會話相關的問題。

多次調用session_start()會導致警告信息和可能的數據覆蓋。 1)PHP會發出警告,提示session已啟動。 2)可能導致session數據意外覆蓋。 3)使用session_status()檢查session狀態,避免重複調用。

在PHP中配置會話生命週期可以通過設置session.gc_maxlifetime和session.cookie_lifetime來實現。 1)session.gc_maxlifetime控制服務器端會話數據的存活時間,2)session.cookie_lifetime控制客戶端cookie的生命週期,設置為0時cookie在瀏覽器關閉時過期。

使用數據庫存儲會話的主要優勢包括持久性、可擴展性和安全性。 1.持久性:即使服務器重啟,會話數據也能保持不變。 2.可擴展性:適用於分佈式系統,確保會話數據在多服務器間同步。 3.安全性:數據庫提供加密存儲,保護敏感信息。

在PHP中實現自定義會話處理可以通過實現SessionHandlerInterface接口來完成。具體步驟包括:1)創建實現SessionHandlerInterface的類,如CustomSessionHandler;2)重寫接口中的方法(如open,close,read,write,destroy,gc)來定義會話數據的生命週期和存儲方式;3)在PHP腳本中註冊自定義會話處理器並啟動會話。這樣可以將數據存儲在MySQL、Redis等介質中,提升性能、安全性和可擴展性。

SessionID是網絡應用程序中用來跟踪用戶會話狀態的機制。 1.它是一個隨機生成的字符串,用於在用戶與服務器之間的多次交互中保持用戶的身份信息。 2.服務器生成並通過cookie或URL參數發送給客戶端,幫助在用戶的多次請求中識別和關聯這些請求。 3.生成通常使用隨機算法保證唯一性和不可預測性。 4.在實際開發中,可以使用內存數據庫如Redis來存儲session數據,提升性能和安全性。

在無狀態環境如API中管理會話可以通過使用JWT或cookies來實現。 1.JWT適合無狀態和可擴展性,但大數據時體積大。 2.Cookies更傳統且易實現,但需謹慎配置以確保安全性。


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

mPDF
mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 Linux新版
SublimeText3 Linux最新版

記事本++7.3.1
好用且免費的程式碼編輯器

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中