search
HomeBackend DevelopmentPHP TutorialParsing safe mode (safe_mode) in PHP

Parsing safe mode (safe_mode) in PHP

What is PHP safe mode: safe_mode

Simply put, PHP safe mode is Run php in safe mode.

php's safe mode provides a basic secure shared environment on a php open web server where multiple user accounts exist. When PHP is running in safe mode on a web server, some functions will be completely disabled and some available functions will be limited.

In safe mode, some functions that try to access the file system will be restricted. Running the web server user ID, if you want to operate a certain file, you must have access permission to read or write the file. There is no problem for PHP to implement this restriction function.

When safe mode is turned on, when trying to read or write a local file, PHP will check whether the current accessing user is the owner of the target file. If you are not the owner, the operation will be disabled.

(Writing permissions: Under lower-level file access permissions, it may be allowed to read or write files in the system operating system. This is achieved through PHP's safe mode to prevent you from operating another user's files. Operation. Of course, a web server may be able to access an arbitrary file with global write permission.)

When safe mode is turned on, the functionality of the following function list will be restricted:

chdir, move_uploaded_file, chgrp, parse_ini_file, chown, rmdir, copy, rename, fopen, require, highlight_file, show_source, include, symlink, link, touch, mkdir, unlink

Same, Some functions in PHP extensions will also be affected. (Loading module: The dl function will be prohibited in safe mode. If you want to load an extension, you can only modify the extension options in php.ini and load it when PHP starts)

Opened in PHP safe mode When you need to execute a system program, it must be the program in the directory specified in the safe_mode_exec_dir option, otherwise the execution will fail. Even if execution is allowed, it will automatically be passed to the escapeshellcmd function for filtering.

The following function list for executing commands will be affected:

exec,shell_exec,passthru,system,popen

In addition, the back marking operator (`) will also be closed.

When running in safe mode, although no error will be caused, the putenv function will be invalid. Similarly, other functions set_time_limit and set_include_path that try to change PHP environment variables will also be ignored.

How to turn on PHP safe mode (please note that PHP5.3 will no longer have a safe mode)

To turn on or off PHP's safe mode, use php.ini The safe_mode option:

safe_mode=On(使用安全模式)
safe_mode=Off(关闭安全模式)

The corresponding setting method of VirtualHost in apache's httpd.conf

php_admin_flag safe_mode On(使用安全模式)
php_admin_flag safe_mode Off(关闭安全模式)
或者:
php_admin_value safe_mode1(使用安全模式)
php_admin_value safe_mode0(关闭安全模式)

The impact of enabling safe mode:

When The function will perform a file owner check when accessing the file system. By default, the user ID of the file owner is checked. When you can modify the file owner's group ID (gid), it is specified by the safe_mode_gid option.

If you have a shared library file on your system, when you encounter the need to include or require, then you can use the safe_mode_include_dir option to set your path to ensure that your code works normally. (Inclusion path: If you want to use the safe_mode_include_dir option to include more include paths, then you can use the colon to separate under unix/linux systems and semicolons under windows like the include_path option)

For example, if you want to include files under /usr/local/include/php in safe mode, then you can set the option to:

safe_mode_include_dir=/usr/local/include/php

If your included files need to be executed, then you The safe_mode_exec_dir option can be set.

For example, if you need the files in the /usr/local/php-bin path to be executable, then you can set the option to:

safe_mode_exec_dir=/usr/local/php-bin

(Executable: If the program you execute is in / usr/bin directory, then you can connect these binary files to the path that can be executed under the options you specify)

If you want to set certain environment variables, you can use the safe_mode_allowed_env_vars option. The value of this option is the prefix of an environment variable. By default, environment variables starting with php_ are allowed. If you want to change it, you can set the value of this option. Use commas to separate multiple environment variable prefixes.

For example, if the environment variable tz of the time zone is allowed below, then modify the value of this option to:

safe_mode_allowed_env_vars=php_,tz

In addition to the safe mode, php also provides many other features to ensure the security of php.

1. [Hide PHP version number]

You can use the expose_php option in php.ini to prevent the web server from leaking PHP report information. As follows:

expose_php=on

With this entire setup, you can thwart some attacks from automated scripts targeting web servers. Normally, the http header information contains the following information:

server:apache/1.3.33(unix)php/5.2.4mod_ssl/2.8.16openssl/0.9.7c

After the expose_php option is turned on, the PHP version information will not be included in the above header information.

当然,用户访问网站的时候同样能够看到.php的文件扩展名。如果你想整个的使用不同的文件扩展名,你需要在httpd.conf中找到如下这行:

addtype application/x-httpd.php

你就可以修改.php为任何你喜欢的文件扩展名。你能够指定任意多个的文件扩展名,中间使用空格进行分割。如果你想在服务器端使用php来解析.html和.htm文件的时候,那么你设置选项如下:

addtype application/x-httpd.html.htm

(解析html:配置你的web服务器使用php去解析所有的html文件,但是如果非服务器端代码也需要php去解析,会影响服务器的性能。静态页面你可以使用不同的扩展名,这样能够消除对php脚本引擎的依赖,增强性能。)

2、[文件系统安全]

安全模式限制了脚本所有者只能访问属于自己的文件,但是你可以使用open_basedir选现来指定一个你必须访问的目录。如果你指定了一个目录,php将拒绝访问除了该目录和该目录子目录的其他目录。open_basedir选项能够工作在安全模式之外。

限制文件系统只能访问/tmp目录,那么设置选项为:

open_basedir=/tmp

3、[函数访问控制]

你能够在disable_functions选项中使用逗号分割来设定函数名,那么这些函数将在php脚本中被关闭。这个设置能够工作在安全模式之外。

disable_functions=dl

当然,同样的你能够使用disable_classes选项来关闭对一些类的访问。

4、[数据库安全]

假设你的php脚本中包含一个基于表单值来执行的mysql查询:

$sql=”update mytable set col1=”.$_post[“value”].”where col2=’somevalue'”;
$res=mysql_query($sql,$db);

你希望$_post[“value”]包含一个整数值来更新你的列col1。可是,一个恶意用户能够输入一个分号在表单字段里,接着,是一段他/她想被任意执行的sql语句。

举例,假设下面是$_post[“value”]提交的值:

0;insert into admin_users(username,password) values (‘me’,’mypassword’);

那么当这个查询发送给mysql查询的时候,那么就变成了下面这条sql:

update mytable set col1=0;
insert into admin_users(username,password) values (‘me’,’mypassword’);
where col2=’somevalue';

这明显是一个有害的查询!首先这个查询会在mytable表里更新col1。这个并没有什么麻烦的,但是第二个表达式,它将执行insert表达式 来插入一个能登陆的新管理员。第三个表达式就废弃了,但同时sql解析器将抛出一个错误,这个有害的查询才完成。这个攻击就是大家常说的sql injection(注:sql注入)。

当然,sql injection存在一个问题,对方必须了解你的数据库结构。在这个例子中,攻击者是知道你有一个表admin_users,并且知道包含username和password字段,同时,存储的密码是没有加密的。

除了你自己,一般的网站访问者是不知道这些关于数据库的信息。可是,如果你使用了一个开发源代码的在线电子商务程序,或者使用一个自由的讨论版程序,这些数据表的定义都是已知的,或者有一些用户能够访问到你的数据库。

此外,你的脚本输出会提示一个查询错误,这些信息里包含了很多关于数据库结构的重要信息。在一个正常工作的网站上,你应该考虑设置 display_errors选项为off,并且使用log_errors来代替display_errors,把警告和错误信息插入到文件中。

(数据库权限:它是一个非常重要的东西,你只有正确的权限,才能通过脚本正确的连接数据库。你应该不要在脚本中使用管理员去连接数据库。如果你这么 做,那么一个攻击者将可能获取全部的数据库权限,并且包括其他相同服务器的权限。攻击者将可能运行grant或create user命令来获取更多的访问权限。)

如果你要防止sql injection攻击,你必须保证用户表单里提交的内容不是一个能够执行的sql表达式。

前一个例子中,我们使用一个整型值来进行更新。如果在单引号后面跟上一个字符串,这个攻击者在分号之前必须提交一个闭合的引用在整个sql表达式中。可是,当magic_quotes_gpc选项是开启的时候,在web表单中提交的引号将自动被转义。

为了防止被恶意的攻击者进行sql injection攻击,你应该总是确认提交的数据是合法的。如果你需要的是一个整数值,那么你可以使用is_numeric函数来测试这个表达值,或者使用settype函数来转换为一个数字,清除任何一个傻傻的sql语句。

如果你开发的程序需要几个提交的值在一个sql表达式里,你能够使用sprintf函数来构建一个sql字符串,使用格式化字符来指示数据类型的每个值。看下面的例子:

$sql=sprintf(“update mytable set col1=%d where col2=’%s'”, $_post[“number”], mysql_escape_string($_post[“string”]));

在上一个例子中,整个mysql的数据已经被使用,所以这个字符串已经通过mysql_escape_string函数进行过滤。对于其他数据库,你可以使用addslashes函数进行转义,或者使用其他方法。

For more php related knowledge, please visit php tutorial!

The above is the detailed content of Parsing safe mode (safe_mode) in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:oschina. If there is any infringement, please contact admin@php.cn delete
PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

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尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool