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

Home php教程 php手冊 PHP中將字符串轉(zhuǎn)化為整數(shù)(int) intval() printf() 性能測試

PHP中將字符串轉(zhuǎn)化為整數(shù)(int) intval() printf() 性能測試

Jun 13, 2016 pm 12:01 PM
int intval php printf sql string performance integer Overview injection test background change

背景、概述
  早在Sql注入橫行的前幾年,字符串轉(zhuǎn)化為整數(shù)就已經(jīng)被列為每個web程序必備的操作了。web程序?qū)et或post來的id、整數(shù)等值強制經(jīng)過轉(zhuǎn)化函數(shù)轉(zhuǎn)化為整數(shù),過濾掉危險字符,盡可能降低系統(tǒng)本身被Sql注入的可能性。
  現(xiàn)如今,雖然Sql注入已經(jīng)逐漸淡出歷史舞臺,但是,為了保證web程序的正常運行,減少出錯概率,更好的保證用的滿意度,我們同樣需要將用戶的不正確輸入轉(zhuǎn)化為我們所需要的。
轉(zhuǎn)化方式
  在PHP中,我們可以使用3種方式將字符串轉(zhuǎn)化為整數(shù)。
1.強制類型轉(zhuǎn)換方式
  強制類型轉(zhuǎn)換方式,就是“在要轉(zhuǎn)換的變量之前加上用括號括起來的目標(biāo)類型”(摘自PHP手冊“類型戲法”節(jié))的方式。

復(fù)制代碼 代碼如下:


$foo = "1"; // $foo 是字符串類型
$bar = (int)$foo; // $bar 是整型
?>


  對于整型來說,強制轉(zhuǎn)換類型名稱為int或者integer。
2.內(nèi)置函數(shù)方式
  內(nèi)置函數(shù)方式,就是使用PHP的內(nèi)置函數(shù)intval進行變量的轉(zhuǎn)換操作。

復(fù)制代碼 代碼如下:


$foo = "1"; // $foo 是字符串類型
$bar = intval($foo); // $bar 是整型
?>


  intval函數(shù)的格式為:
  int intval(mixed $var [, int $base]); (摘自PHP手冊)
  雖然PHP手冊中明確指出,intval()不能用于array和object的轉(zhuǎn)換。但是經(jīng)過我測試,轉(zhuǎn)換array的時候不會出任何問題,轉(zhuǎn)換值為1,而不是想象中的0??峙率且驗樵赑HP內(nèi)部,array類型的變量也被認為是非零值得緣故吧。轉(zhuǎn)換object的時候,PHP會給出如下的 notice:
  Object of class xxxx could not be converted to int in xxxxx.php on line xx
  轉(zhuǎn)換值同樣為1。
3.格式化字符串方式
  格式化字符串方式,是利用sprintf的%d格式化指定的變量,以達到類型轉(zhuǎn)換的目的。

復(fù)制代碼 代碼如下:


$foo = "1"; // $foo 是字符串類型
$bar = sprintf("%d", $foo); // $bar 是字符串類型
?>


  嚴格意義上講sprintf的轉(zhuǎn)換結(jié)果還是string型,因此它不應(yīng)該算是字符串轉(zhuǎn)化為整數(shù)的方式。但是經(jīng)過他處理之后的字符串值確實已經(jīng)成為了“被強制轉(zhuǎn)化為字符串類型的整數(shù)”。
實際測試
  上面介紹了PHP中,將字符串轉(zhuǎn)化為整數(shù)的3種方式。對于一般的程序員來說,看到這里就算結(jié)束了,下面的部分是針對變態(tài)程序員的。
1.基本功能測試
  設(shè)定以下數(shù)組:

復(fù)制代碼 代碼如下:


$a[] = "1";
$a[] = "a1";
$a[] = "1a";
$a[] = "1a2";
$a[] = "0";
$a[] = array('4',2);
$a[] = "2.3";
$a[] = "-1";
$a[] = new Directory();
?>


  使用三種方式依次轉(zhuǎn)化上面給出的數(shù)組中的元素,查看轉(zhuǎn)換情況。程序源代碼如下:

復(fù)制代碼 代碼如下:


$a[] = "1";
$a[] = "a1";
$a[] = "1a";
$a[] = "1a2";
$a[] = "0";
$a[] = array('4',2);
$a[] = "2.3";
$a[] = "-1";
$a[] = new Directory();
// int
print "(int)
";
foreach($a as $v)
{
var_dump((int)$v);
print "
";
}
// intval
print "intval();
";
foreach($a as $v)
{
var_dump(intval($v));
print "
";
}
// sprintf
print "sprintf();
";
foreach($a as $v)
{
var_dump(sprintf("%d", $v));
print "
";
}
?>


  程序的最終運行結(jié)果如下(已經(jīng)去掉轉(zhuǎn)換object時出現(xiàn)的notice):
(int)
int(1)
int(0)
int(1)
int(1)
int(0)
int(1)
int(2)
int(-1)
int(1)
intval();
int(1)
int(0)
int(1)
int(1)
int(0)
int(1)
int(2)
int(-1)
int(1)
sprintf();
string(1) "1"
string(1) "0"
string(1) "1"
string(1) "1"
string(1) "0"
string(1) "1"
string(1) "2"
string(2) "-1"
string(1) "1"
  由此可以看出,三種轉(zhuǎn)換的結(jié)果是完全一樣的。那么從功能上講,3種方式都可以勝任轉(zhuǎn)換工作,那么接下來的工作就是看哪一種效率更高了。
2.性能測試
  被測試字符串是我們在注入工作中可能會使用到的一種:

復(fù)制代碼 代碼如下:


$foo = "1';Select * ...";
?>
  獲取時間點的函數(shù)如下(用于獲取測試起始點和結(jié)束點,以計算消耗時間):

**
* Simple function to replicate PHP 5 behaviour
*/
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
?>


 ?。ㄕ訮HP手冊microtime()函數(shù)節(jié))
  測試過程是使用每種方式轉(zhuǎn)換變量$foo 1000000次(100萬次),并將各自的消耗時間輸出,總共進行三組測試,盡可能降低誤差。測試程序如下:

復(fù)制代碼 代碼如下:


function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$foo = "1';Select * ...";

// (int)
$fStart = microtime_float();
for($i=0;$i{
$bar = (int)$foo;
}
$fEnd = microtime_float();
print "(int):" . ($fEnd - $fStart) . "s
";
// intval()
$fStart = microtime_float();
for($i=0;$i{
$bar = intval($foo);
}
$fEnd = microtime_float();
print "intval():" . ($fEnd - $fStart) . "s
";
// sprintf()
$fStart = microtime_float();
for($i=0;$i{
$bar = sprintf("%d", $foo);
}
$fEnd = microtime_float();
print "sprintf():" . ($fEnd - $fStart) . "s
";
?>


  最終的測試結(jié)果:
(int):0.67205619812012s
intval():1.1603000164032s
sprintf():2.1068270206451s
(int):0.66051411628723s
intval():1.1493890285492s
sprintf():2.1008238792419s
(int):0.66878795623779s
intval():1.1613430976868s
sprintf():2.0976209640503s

  雖然這個測試有點變態(tài)(誰會連續(xù)轉(zhuǎn)換100w次的整數(shù)?),但是由此可以看出,使用強制類型轉(zhuǎn)換將字符串轉(zhuǎn)化為整數(shù)速度是最快的。
總結(jié)
  使用強制類型轉(zhuǎn)換方式將字符串轉(zhuǎn)化為整數(shù)是最直接的轉(zhuǎn)化方式之一(可以直接獲得整型的變量值)。從代碼可讀性角度上講,sprintf方式代碼比較長,而且其結(jié)果有可能還需要再次進行強制類型轉(zhuǎn)換,而intval函數(shù)是典型的面向過程式轉(zhuǎn)換,強制類型轉(zhuǎn)換則比較直接的將“我要轉(zhuǎn)化”這個思想傳遞給閱讀者。從效率上講,強制類型轉(zhuǎn)換方式也是最快速的轉(zhuǎn)化方式。因此,對于經(jīng)常進行轉(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 to access a character in a string by index in PHP How to access a character in a string by index in PHP Jul 12, 2025 am 03:15 AM

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.

How Do Generators Work in PHP? How Do Generators Work in PHP? Jul 11, 2025 am 03:12 AM

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

How to prevent session hijacking in PHP? How to prevent session hijacking in PHP? Jul 11, 2025 am 03:15 AM

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

How to URL encode a string in PHP with urlencode How to URL encode a string in PHP with urlencode Jul 11, 2025 am 03:22 AM

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

PHP get the first N characters of a string PHP get the first N characters of a string Jul 11, 2025 am 03:17 AM

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.

PHP get the last N characters of a string PHP get the last N characters of a string Jul 11, 2025 am 03:17 AM

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.

How to set and get session variables in PHP? How to set and get session variables in PHP? Jul 12, 2025 am 03:10 AM

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

How to prevent SQL injection in PHP How to prevent SQL injection in PHP Jul 12, 2025 am 03:02 AM

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.

See all articles