Describes how PHP can prevent direct access to. php files,
How PHP prevents direct access to. php files
To ensure the security of Apis written in PHP, access methods other than interfaces should be prohibited.
For example, if our project is example, there is a folder dir1 and an interface file api. php. The structure is: Input Image Description
At this time, we only need to use example/api. php to call the service in file. php, and cannot directly access the service through example/dir1/file. php.
In php, there is such a variable $ _ SERVER, which is an array variable and contains various key-value pairs. You can search for details. now we can get the script name through SCRIPT_NAME in $ _ SERVER. $ _ SERVER ['script _ name']. The value is similar to xxx/api. php, then we can determine whether the access Link contains APIs. php to determine whether the access is valid. If the access is valid, it will continue to be executed. If the access is illegal, it will be blocked.
The Code is as follows:
If (strpos ($ _ SERVER ['script _ name'], 'api. php') === false) {echo "error"; exit ;}
Add the above Code at the beginning of file. php.
The above is PHP to prevent direct access. php file implementation method. If you have any questions, please leave a message or go to the community on this site for discussion. Thank you for reading this article and hope to help you. Thank you for your support for this site!