安装

phpMyAdmin 不会在 MySQL 数据库服务器上应用任何特别的安全措施。正确设置 MySQL 数据库的权限是系统管理员应该做的。phpMyAdmin 的 用户 页面可以帮助系统管理员设置权限。

警告

Mac 用户需要注意若您的系统版本低于 Mac OS X,StuffIt 会把文件解压为 Mac 格式。因为 PHP 似乎不支持 Mac 式的换行符(“\r”),所以在将文件上传到服务器之前您必须用 BBEdit 将所有 phpMyAdmin 脚本重新保存为 Unix 格式。

Linux distributions

phpMyAdmin is included in most Linux distributions. It is recommended to use distribution packages when possible - they usually provide integration to your distribution and you will automatically get security updates from your distribution.

塞尔维亚语

Debian’s package repositories include a phpMyAdmin package, but be aware that the configuration file is maintained in /etc/phpmyadmin and may differ in some ways from the official phpMyAdmin documentation. Specifically it does:

参见

More information can be found in README.Debian (it is installed as /usr/share/doc/phmyadmin/README.Debian with the package).

OpenSUSE

OpenSUSE already comes with phpMyAdmin package, just install packages from the openSUSE Build Service.

Ubuntu

Ubuntu ships phpMyAdmin package, however if you want to use recent version, you can use packages from phpMyAdmin PPA.

参见

The packages are same as in 塞尔维亚语 please check the documentation there for more details.

Gentoo

Gentoo ships the phpMyAdmin package, both in a near stock configuration as well as in a webapp-config configuration. Use emerge dev-db/phpmyadmin to install.

Mandriva

Mandriva在“contrib”分支中搭载着phpMyAdmin软件包,可以从通常的控制中心中安装。

Fedora

Fedora 搭载有phpMyAdmin软件包,但注意配置文件放在“/etc/phpMyAdmin/”中,并且可能会和官方phpMyAdmin有不同。

红帽企业Linux

Red Hat Enterprise Linux itself and thus derivatives like CentOS don’t ship phpMyAdmin, but the Fedora-driven repository Extra Packages for Enterprise Linux (EPEL) is doing so, if it’s enabled. But be aware that the configuration file is maintained in /etc/phpMyAdmin/ and may differ in some ways from the official phpMyAdmin documentation.

Windows安装

The easiest way to get phpMyAdmin on Windows is using third party products which include phpMyAdmin together with a database and web server such as XAMPP.

您可以从`维基百科 <https://en.wikipedia.org/wiki/List_of_AMP_packages>`_.找到更多选择。

Installing from Git

You can clone current phpMyAdmin source from https://github.com/phpmyadmin/phpmyadmin.git:

git clone https://github.com/phpmyadmin/phpmyadmin.git

Additionally you need to install dependencies using the Composer tool:

composer update

If you do not intend to develop, you can skip the installation of developer tools by invoking:

composer update --no-dev

Installing using Composer

You can install phpMyAdmin using the Composer tool, since 4.7.0 the releases are automatically mirrored to the default Packagist repository.

注解

The content of the Composer repository is automatically generated separately from the releases, so the content doesn’t have to be 100% same as when you download the tarball. There should be no functional differences though.

To install phpMyAdmin simply run:

composer create-project phpmyadmin/phpmyadmin

Alternatively you can use our own composer repository, which contains the release tarballs and is available at <https://www.phpmyadmin.net/packages.json>:

composer create-project phpmyadmin/phpmyadmin --repository-url=https://www.phpmyadmin.net/packages.json --no-dev

Installing using Docker

phpMyAdmin comes with a Docker image, which you can easily deploy. You can download it using:

docker pull phpmyadmin/phpmyadmin

The phpMyAdmin server will listen on port 80. It supports several ways of configuring the link to the database server, either by Docker’s link feature by linking your database container to db for phpMyAdmin (by specifying --link your_db_host:db) or by environment variables (in this case it’s up to you to set up networking in Docker to allow the phpMyAdmin container to access the database container over network).

Docker environment variables

You can configure several phpMyAdmin features using environment variables:

PMA_ARBITRARY

Allows you to enter a database server hostname on login form.

PMA_HOST

Host name or IP address of the database server to use.

PMA_HOSTS

Comma-separated host names or IP addresses of the database servers to use.

注解

Used only if PMA_HOST is empty.

PMA_VERBOSE

Verbose name of the database server.

PMA_VERBOSES

Comma-separated verbose name of the database servers.

注解

Used only if PMA_VERBOSE is empty.

PMA_USER

User name to use for Config 认证方式.

PMA_PASSWORD

Password to use for Config 认证方式.

PMA_PORT

Port of the database server to use.

PMA_PORTS

Comma-separated ports of the database server to use.

注解

Used only if PMA_PORT is empty.

PMA_ABSOLUTE_URI

The fully-qualified path (https://pma.example.net/) where the reverse proxy makes phpMyAdmin available.

By default, Cookie 认证方式 is used, but if PMA_USER and PMA_PASSWORD are set, it is switched to Config 认证方式.

注解

The credentials you need to log in are stored in the MySQL server, in case of Docker image there are various ways to set it (for example MYSQL_ROOT_PASSWORD when starting the MySQL container). Please check documentation for MariaDB container or MySQL container.

Customizing configuration

Additionally configuration can be tweaked by /etc/phpmyadmin/config.user.inc.php. If this file exists, it will be loaded after configuration is generated from above environment variables, so you can override any configuration variable. This configuration can be added as a volume when invoking docker using -v /some/local/directory/config.user.inc.php:/etc/phpmyadmin/config.user.inc.php parameters.

Note that the supplied configuration file is applied after Docker environment variables, but you can override any of the values.

For example to change default behaviour of CSV export you can use following configuration file:

<?php
$cfg['Export']['csv_columns'] = true;
?>

参见

See 设置 for detailed description of configuration options.

Docker Volumes

You can use following volumes to customize image behavior:

/etc/phpmyadmin/config.user.inc.php

Can be used for additional settings, see previous chapter for more details.

/sessions/

Directory where PHP sessions are stored. You might want to share this for example when using Signon 认证方式.

/www/themes/

Directory where phpMyAdmin looks for themes. By default only those shipped with phpMyAdmin are included, but you can include additional phpMyAdmin themes (see Custom Themes) by using Docker volumes.

Docker Examples

To connect phpMyAdmin to a given server use:

docker run --name myadmin -d -e PMA_HOST=dbhost -p 8080:80 phpmyadmin/phpmyadmin

To connect phpMyAdmin to more servers use:

docker run --name myadmin -d -e PMA_HOSTS=dbhost1,dbhost2,dbhost3 -p 8080:80 phpmyadmin/phpmyadmin

To use arbitrary server option:

docker run --name myadmin -d --link mysql_db_server:db -p 8080:80 -e PMA_ARBITRARY=1 phpmyadmin/phpmyadmin

You can also link the database container using Docker:

docker run --name phpmyadmin -d --link mysql_db_server:db -p 8080:80 phpmyadmin/phpmyadmin

Running with additional configuration:

docker run --name phpmyadmin -d --link mysql_db_server:db -p 8080:80 -v /some/local/directory/config.user.inc.php:/etc/phpmyadmin/config.user.inc.php phpmyadmin/phpmyadmin

Running with additional themes:

docker run --name phpmyadmin -d --link mysql_db_server:db -p 8080:80 -v /custom/phpmyadmin/theme/:/www/themes/theme/ phpmyadmin/phpmyadmin

Using docker-compose

Alternatively you can also use docker-compose with the docker-compose.yml from <https://github.com/phpmyadmin/docker>. This will run phpMyAdmin with an arbitrary server - allowing you to specify MySQL/MariaDB server on login page.

docker-compose up -d

Customizing configuration file using docker-compose

You can use an external file to customize phpMyAdmin configuration and pass it using the volumes directive:

phpmyadmin:
    image: phpmyadmin/phpmyadmin
    container_name: phpmyadmin
    environment:
     - PMA_ARBITRARY=1
    restart: always
    ports:
     - 8080:80
    volumes:
     - /sessions
     - ~/docker/phpmyadmin/config.user.inc.php:/etc/phpmyadmin/config.user.inc.php
     - /custom/phpmyadmin/theme/:/www/themes/theme/

Running behind haproxy in a subdirectory

When you want to expose phpMyAdmin running in a Docker container in a subdirectory, you need to rewrite the request path in the server proxying the requests.

For example using haproxy it can be done as:

frontend http
    bind *:80
    option forwardfor
    option http-server-close

    ### NETWORK restriction
    acl LOCALNET  src 10.0.0.0/8 192.168.0.0/16 172.16.0.0/12

    # /phpmyadmin
    acl phpmyadmin  path_dir /phpmyadmin
    use_backend phpmyadmin if phpmyadmin LOCALNET

backend phpmyadmin
    mode http

    reqirep  ^(GET|POST|HEAD)\ /phpmyadmin/(.*)     \1\ /\2

    # phpMyAdmin container IP
    server localhost     172.30.21.21:80

When using traefik, something like following should work:

defaultEntryPoints = ["http"]
[entryPoints]
  [entryPoints.http]
  address = ":80"
    [entryPoints.http.redirect]
      regex = "(http:\\/\\/[^\\/]+\\/([^\\?\\.]+)[^\\/])$"
      replacement = "$1/"

[backends]
  [backends.myadmin]
    [backends.myadmin.servers.myadmin]
    url="http://internal.address.to.pma"

[frontends]
   [frontends.myadmin]
   backend = "myadmin"
   passHostHeader = true
     [frontends.myadmin.routes.default]
     rule="PathPrefixStrip:/phpmyadmin/;AddPrefix:/"

You then should specify PMA_ABSOLUTE_URI in the docker-compose configuration:

version: '2'

services:
  phpmyadmin:
    restart: always
    image: phpmyadmin/phpmyadmin
    container_name: phpmyadmin
    hostname: phpmyadmin
    domainname: example.com
    ports:
      - 8000:80
    environment:
      - PMA_HOSTS=172.26.36.7,172.26.36.8,172.26.36.9,172.26.36.10
      - PMA_VERBOSES=production-db1,production-db2,dev-db1,dev-db2
      - PMA_USER=root
      - PMA_PASSWORD=
      - PMA_ABSOLUTE_URI=http://example.com/phpmyadmin/

快速安装

  1. 从 phpmyadmin.net 下载页选择一个合适的版本。有些版本只有英语,有些包含了所有语言。假设您选择了一个名字类似于 phpMyAdmin-x.x.x -all-languages.tar.gz 的版本。

  2. Ensure you have downloaded a genuine archive, see Verifying phpMyAdmin releases.
  3. 解开这个压缩包(包括子目录):在您网站服务器的文档根目录中执行 tar -xzvf phpMyAdmin_x.x.x-all-languages.tar.gz。如果您不能直接访问服务器,请先把这些文件解压到您自己的电脑上,等完成第 4 步之后,再通过 ftp 等方式将文件上传到您的网站服务器。

  4. 确保所有的脚本都有正确的所有者(若 PHP 运行于安全模式,脚本间所有者的不同将会导致问题)。参见 4.2 What’s the preferred way of making phpMyAdmin secure against evil access?1.26 I just installed phpMyAdmin in my document root of IIS but I get the error “No input file specified” when trying to run phpMyAdmin.

  5. 现在开始设置您的安装。两种方法。以前,用户只能手动编辑一份 config.inc.php 文件,但现在我们为那些喜欢使用图形界面安装的用户提供了一个向导式的安装脚本。手动创建 config.inc.php 仍然是一个快速安装的方法且一些高级功能也需要手动编辑该文件。

Manually creating the file

To manually create the file, simply use your text editor to create the file config.inc.php (you can copy config.sample.inc.php to get a minimal configuration file) in the main (top-level) phpMyAdmin directory (the one that contains index.php). phpMyAdmin first loads libraries/config.default.php and then overrides those values with anything found in config.inc.php. If the default value is okay for a particular setting, there is no need to include it in config.inc.php. You’ll probably need only a few directives to get going; a simple configuration may look like this:

<?php
// use here a value of your choice at least 32 chars long
$cfg['blowfish_secret'] = '1{dd0`<Q),5XP_:R9UK%%8\"EEcyH#{o';

$i=0;
$i++;
$cfg['Servers'][$i]['auth_type']     = 'cookie';
// if you insist on "root" having no password:
// $cfg['Servers'][$i]['AllowNoPassword'] = true; `
?>

或者,若您不想每次都登录:

<?php

$i=0;
$i++;
$cfg['Servers'][$i]['user']          = 'root';
$cfg['Servers'][$i]['password']      = 'cbb74bc'; // use here your password
$cfg['Servers'][$i]['auth_type']     = 'config';
?>

警告

Storing passwords in the configuration is insecure as anybody can then manipulate with your database.

所有设置的完整说明请参见本文档的 设置 一节。

使用安装脚本

Instead of manually editing config.inc.php, you can use phpMyAdmin’s setup feature. The file can be generated using the setup and you can download it for upload to the server.

Next, open your browser and visit the location where you installed phpMyAdmin, with the /setup suffix. The changes are not saved to the server, you need to use the Download button to save them to your computer and then upload to the server.

现在文件保存好了。您可以使用您最喜欢的编辑器来复查或编辑一些安装脚本中没有提供的高级选项。

  1. 若您使用“config”认证方式,您应保护好 phpMyAdmin 的安装文件夹,因为 config 认证不要求用户输入密码即可访问 phpMyAdmin。我们建议使用其它认证方式,如在 .htaccess 文件中设置 HTTP 认证或修改``认证方式``为 cookie 或 http。参见 ISPs, multi-user installations,特别要注意 4.4 phpMyAdmin always gives “Access denied” when using HTTP authentication.

  2. Open the main phpMyAdmin directory in your browser. phpMyAdmin should now display a welcome screen and your databases, or a login dialog if using HTTP or cookie authentication mode.

Setup script on Debian, Ubuntu and derivatives

Debian and Ubuntu have changed way how setup is enabled and disabled, in a way that single command has to be executed for either of these.

To allow editing configuration invoke:

/usr/sbin/pma-configure

To block editing configuration invoke:

/usr/sbin/pma-secure

Setup script on openSUSE

Some openSUSE releases do not include setup script in the package. In case you want to generate configuration on these you can either download original package from <https://www.phpmyadmin.net/> or use setup script on our demo server: <https://demo.phpmyadmin.net/STABLE/setup/>.

Verifying phpMyAdmin releases

Since July 2015 all phpMyAdmin releases are cryptographically signed by the releasing developer, who through January 2016 was Marc Delisle. His key id is 0xFEFC65D181AF644A, his PGP fingerprint is:

436F F188 4B1A 0C3F DCBF 0D79 FEFC 65D1 81AF 644A

and you can get more identification information from <https://keybase.io/lem9>.

Beginning in January 2016, the release manager is Isaac Bennetch. His key id is 0xCE752F178259BD92, and his PGP fingerprint is:

3D06 A59E CE73 0EB7 1B51 1C17 CE75 2F17 8259 BD92

and you can get more identification information from <https://keybase.io/ibennetch>.

Some additional downloads (for example themes) might be signed by Michal Čihař. His key id is 0x9C27B31342B7511D, and his PGP fingerprint is:

63CB 1DF1 EF12 CF2A C0EE 5A32 9C27 B313 42B7 511D

and you can get more identification information from <https://keybase.io/nijel>.

You should verify that the signature matches the archive you have downloaded. This way you can be sure that you are using the same code that was released. You should also verify the date of the signature to make sure that you downloaded the latest version.

Each archive is accompanied with .asc files which contains the PGP signature for it. Once you have both of them in the same folder, you can verify the signature:

$ gpg --verify phpMyAdmin-4.5.4.1-all-languages.zip.asc
gpg: Signature made Fri 29 Jan 2016 08:59:37 AM EST using RSA key ID 8259BD92
gpg: Can't check signature: public key not found

As you can see gpg complains that it does not know the public key. At this point you should do one of the following steps:

$ gpg --import phpmyadmin.keyring
  • Download and import the key from one of the key servers:
$ gpg --keyserver hkp://pgp.mit.edu --recv-keys 3D06A59ECE730EB71B511C17CE752F178259BD92
gpg: requesting key 8259BD92 from hkp server pgp.mit.edu
gpg: key 8259BD92: public key "Isaac Bennetch <bennetch@gmail.com>" imported
gpg: no ultimately trusted keys found
gpg: Total number processed: 1
gpg:               imported: 1  (RSA: 1)

This will improve the situation a bit - at this point you can verify that the signature from the given key is correct but you still can not trust the name used in the key:

$ gpg --verify phpMyAdmin-4.5.4.1-all-languages.zip.asc
gpg: Signature made Fri 29 Jan 2016 08:59:37 AM EST using RSA key ID 8259BD92
gpg: Good signature from "Isaac Bennetch <bennetch@gmail.com>"
gpg:                 aka "Isaac Bennetch <isaac@bennetch.org>"
gpg: WARNING: This key is not certified with a trusted signature!
gpg:          There is no indication that the signature belongs to the owner.
Primary key fingerprint: 3D06 A59E CE73 0EB7 1B51  1C17 CE75 2F17 8259 BD92

The problem here is that anybody could issue the key with this name. You need to ensure that the key is actually owned by the mentioned person. The GNU Privacy Handbook covers this topic in the chapter Validating other keys on your public keyring. The most reliable method is to meet the developer in person and exchange key fingerprints, however you can also rely on the web of trust. This way you can trust the key transitively though signatures of others, who have met the developer in person. For example you can see how Isaac’s key links to Linus’s key.

Once the key is trusted, the warning will not occur:

$ gpg --verify phpMyAdmin-4.5.4.1-all-languages.zip.asc
gpg: Signature made Fri 29 Jan 2016 08:59:37 AM EST using RSA key ID 8259BD92
gpg: Good signature from "Isaac Bennetch <bennetch@gmail.com>" [full]

Should the signature be invalid (the archive has been changed), you would get a clear error regardless of the fact that the key is trusted or not:

$ gpg --verify phpMyAdmin-4.5.4.1-all-languages.zip.asc
gpg: Signature made Fri 29 Jan 2016 08:59:37 AM EST using RSA key ID 8259BD92
gpg: BAD signature from "Isaac Bennetch <bennetch@gmail.com>" [unknown]

phpMyAdmin 高级功能

在 3.4.0 版更改: Prior to phpMyAdmin 3.4.0 this was called Linked Tables Infrastructure, but the name was changed due to extended scope of the storage.

For a whole set of additional features (书签, comments, SQL-history, tracking mechanism, PDF-generation, 转换, 关系 etc.) you need to create a set of special tables. Those tables can be located in your own database, or in a central database for a multi-user installation (this database would then be accessed by the controluser, so no other user should have rights to it).

Zero configuration

In many cases, this database structure can be automatically created and configured. This is called “Zero Configuration” mode and can be particularly useful in shared hosting situations. “Zeroconf” mode is on by default, to disable set $cfg['ZeroConf'] to false.

The following three scenarios are covered by the Zero Configuration mode:

  • When entering a database where the configuration storage tables are not present, phpMyAdmin offers to create them from the Operations tab.
  • When entering a database where the tables do already exist, the software automatically detects this and begins using them. This is the most common situation; after the tables are initially created automatically they are continually used without disturbing the user; this is also most useful on shared hosting where the user is not able to edit config.inc.php and usually the user only has access to one database.
  • When having access to multiple databases, if the user first enters the database containing the configuration storage tables then switches to another database, phpMyAdmin continues to use the tables from the first database; the user is not prompted to create more tables in the new database.

Manual configuration

Please look at your ./sql/ directory, where you should find a file called create_tables.sql. (If you are using a Windows server, pay special attention to 1.23 I’m running MySQL on a Win32 machine. Each time I create a new table the table and column names are changed to lowercase!).

If you already had this infrastructure and:

  • upgraded to MySQL 4.1.2 or newer, please use sql/upgrade_tables_mysql_4_1_2+.sql.
  • upgraded to phpMyAdmin 4.3.0 or newer from 2.5.0 or newer (<= 4.2.x), please use sql/upgrade_column_info_4_3_0+.sql.
  • upgraded to phpMyAdmin 4.7.0 or newer from 4.3.0 or newer, please use sql/upgrade_tables_4_7_0+.sql.

and then create new tables by importing sql/create_tables.sql.

您可以使用 phpMyAdmin 来创建这些表。但请注意您可能需要特殊(管理员)权限来创建数据库和表,而且可能还需要根据数据库名修改脚本。

After having imported the sql/create_tables.sql file, you should specify the table names in your config.inc.php file. The directives used for that can be found in the 设置.

You will also need to have a controluser ($cfg['Servers'][$i]['controluser'] and $cfg['Servers'][$i]['controlpass'] settings) with the proper rights to those tables. For example you can create it using following statement:

GRANT SELECT, INSERT, UPDATE, DELETE ON <pma_db>.* TO 'pma'@'localhost'  IDENTIFIED BY 'pmapass';

从旧版本升级

警告

Never extract the new version over an existing installation of phpMyAdmin, always first remove the old files keeping just the configuration.

This way you will not leave old no longer working code in the directory, which can have severe security implications or can cause various breakages.

Simply copy config.inc.php from your previous installation into the newly unpacked one. Configuration files from old versions may require some tweaking as some options have been changed or removed. For compatibility with PHP 5.3 and later, remove a set_magic_quotes_runtime(0); statement that you might find near the end of your configuration file.

请勿 复制 libraries/config.default.phpconfig.inc.php 因为默认配置文件仅对当前版本有效。

The complete upgrade can be performed in few simple steps:

  1. Download the latest phpMyAdmin version from <https://www.phpmyadmin.net/downloads/>.
  2. Rename existing phpMyAdmin folder (for example to phpmyadmin-old).
  3. Unpack freshly donwloaded phpMyAdmin to desired location (for example phpmyadmin).
  4. Copy config.inc.php` from old location (phpmyadmin-old) to new one (phpmyadmin).
  5. Test that everything works properly.
  6. Remove backup of previous version (phpmyadmin-old).

If you have upgraded your MySQL server from a version previous to 4.1.2 to version 5.x or newer and if you use the phpMyAdmin configuration storage, you should run the SQL script found in sql/upgrade_tables_mysql_4_1_2+.sql.

If you have upgraded your phpMyAdmin to 4.3.0 or newer from 2.5.0 or newer (<= 4.2.x) and if you use the phpMyAdmin configuration storage, you should run the SQL script found in sql/upgrade_column_info_4_3_0+.sql.

Do not forget to clear the browser cache and to empty the old session by logging out and logging in again.

认证方式的使用

当您在**多用户环境**下想让用户只能访问各自的数据库时我们推荐您使用 HTTP 和 cookie 认证方式。但请注意直到 IE 6 时微软的 IE 浏览器仍然有处理 cookies 的缺陷。您也许在**单用户环境**下仍然会使用 HTTP 或 cookie 认证方式,因为这样您的用户名/密码将不会以明文出现在配置文件中。

HTTP and cookie authentication modes are more secure: the MySQL login information does not need to be set in the phpMyAdmin configuration file (except possibly for the $cfg['Servers'][$i]['controluser']). However, keep in mind that the password travels in plain text, unless you are using the HTTPS protocol. In cookie mode, the password is stored, encrypted with the AES algorithm, in a temporary cookie.

每一个*真实的*用户应在特定的数据库上具有一定的权限。除非你很明白这些权限的作用 (例如,需要创建一个超级用户),否则不应轻易授予普通用户任何全局权限。

GRANT ALL PRIVILEGES ON user_base.* TO 'real_user'@localhost IDENTIFIED BY 'real_password';

现在用户可以做什么已经完全被 MySQL 用户管理系统所控制了。在 HTTP 或 cookie 认证方式下,您不需要填写 $cfg['Servers'] 中的 user/password 设置。

HTTP 认证方式

注解

There is no way to do proper logout in HTTP authentication, most browsers will remember credentials until there is no different successful authentication. Because of this this method has limitation that you can not login with same user after logout.

Signon 认证方式

The very basic example of saving credentials in a session is available as examples/signon.php:

<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * Single signon for phpMyAdmin
 *
 * This is just example how to use session based single signon with
 * phpMyAdmin, it is not intended to be perfect code and look, only
 * shows how you can integrate this functionality in your application.
 *
 * @package    PhpMyAdmin
 * @subpackage Example
 */

/* Use cookies for session */
@ini_set('session.use_cookies', 'true');
/* Change this to true if using phpMyAdmin over https */
$secure_cookie = false;
/* Need to have cookie visible from parent directory */
session_set_cookie_params(0, '/', '', $secure_cookie, true);
/* Create signon session */
$session_name = 'SignonSession';
session_name($session_name);
// Uncomment and change the following line to match your $cfg['SessionSavePath']
//session_save_path('/foobar');
@session_start();

/* Was data posted? */
if (isset($_POST['user'])) {
    /* Store there credentials */
    $_SESSION['PMA_single_signon_user'] = $_POST['user'];
    $_SESSION['PMA_single_signon_password'] = $_POST['password'];
    $_SESSION['PMA_single_signon_host'] = $_POST['host'];
    $_SESSION['PMA_single_signon_port'] = $_POST['port'];
    /* Update another field of server configuration */
    $_SESSION['PMA_single_signon_cfgupdate'] = array('verbose' => 'Signon test');
    $id = session_id();
    /* Close that session */
    @session_write_close();
    /* Redirect to phpMyAdmin (should use absolute URL here!) */
    header('Location: ../index.php');
} else {
    /* Show simple form */
    header('Content-Type: text/html; charset=utf-8');
    echo '<?xml version="1.0" encoding="utf-8"?>' , "\n";
    ?>
    <!DOCTYPE HTML>
    <html lang="en" dir="ltr">
    <head>
    <link rel="icon" href="../favicon.ico" type="image/x-icon" />
    <link rel="shortcut icon" href="../favicon.ico" type="image/x-icon" />
    <meta charset="utf-8" />
    <title>phpMyAdmin single signon example</title>
    </head>
    <body>
    <?php
    if (isset($_SESSION['PMA_single_signon_error_message'])) {
        echo '<p class="error">';
        echo $_SESSION['PMA_single_signon_error_message'];
        echo '</p>';
    }
    ?>
    <form action="signon.php" method="post">
    Username: <input type="text" name="user" /><br />
    Password: <input type="password" name="password" /><br />
    Host: (will use the one from config.inc.php by default)
    <input type="text" name="host" /><br />
    Port: (will use the one from config.inc.php by default)
    <input type="text" name="port" /><br />
    <input type="submit" />
    </form>
    </body>
    </html>
    <?php
}
?>

Alternatively you can also use this way to integrate with OpenID as shown in examples/openid.php:

<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * Single signon for phpMyAdmin using OpenID
 *
 * This is just example how to use single signon with phpMyAdmin, it is
 * not intended to be perfect code and look, only shows how you can
 * integrate this functionality in your application.
 *
 * It uses OpenID pear package, see https://pear.php.net/package/OpenID
 *
 * User first authenticates using OpenID and based on content of $AUTH_MAP
 * the login information is passed to phpMyAdmin in session data.
 *
 * @package    PhpMyAdmin
 * @subpackage Example
 */

if (false === @include_once 'OpenID/RelyingParty.php') {
    exit;
}

/* Change this to true if using phpMyAdmin over https */
$secure_cookie = false;

/**
 * Map of authenticated users to MySQL user/password pairs.
 */
$AUTH_MAP = array(
    'https://launchpad.net/~username' => array(
        'user' => 'root',
        'password' => '',
        ),
    );

/**
 * Simple function to show HTML page with given content.
 *
 * @param string $contents Content to include in page
 *
 * @return void
 */
function Show_page($contents)
{
    header('Content-Type: text/html; charset=utf-8');
    echo '<?xml version="1.0" encoding="utf-8"?>' , "\n";
    ?>
    <!DOCTYPE HTML>
    <html lang="en" dir="ltr">
    <head>
    <link rel="icon" href="../favicon.ico" type="image/x-icon" />
    <link rel="shortcut icon" href="../favicon.ico" type="image/x-icon" />
    <meta charset="utf-8" />
    <title>phpMyAdmin OpenID signon example</title>
    </head>
    <body>
    <?php
    if (isset($_SESSION) && isset($_SESSION['PMA_single_signon_error_message'])) {
        echo '<p class="error">' , $_SESSION['PMA_single_signon_message'] , '</p>';
        unset($_SESSION['PMA_single_signon_message']);
    }
    echo $contents;
    ?>
    </body>
    </html>
    <?php
}

/**
 * Display error and exit
 *
 * @param Exception $e Exception object
 *
 * @return void
 */
function Die_error($e)
{
    $contents = "<div class='relyingparty_results'>\n";
    $contents .= "<pre>" . htmlspecialchars($e->getMessage()) . "</pre>\n";
    $contents .= "</div class='relyingparty_results'>";
    Show_page($contents);
    exit;
}


/* Need to have cookie visible from parent directory */
session_set_cookie_params(0, '/', '', $secure_cookie, true);
/* Create signon session */
$session_name = 'SignonSession';
session_name($session_name);
@session_start();

// Determine realm and return_to
$base = 'http';
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
    $base .= 's';
}
$base .= '://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'];

$realm = $base . '/';
$returnTo = $base . dirname($_SERVER['PHP_SELF']);
if ($returnTo[strlen($returnTo) - 1] != '/') {
    $returnTo .= '/';
}
$returnTo .= 'openid.php';

/* Display form */
if (!count($_GET) && !count($_POST) || isset($_GET['phpMyAdmin'])) {
    /* Show simple form */
    $content = '<form action="openid.php" method="post">
OpenID: <input type="text" name="identifier" /><br />
<input type="submit" name="start" />
</form>
</body>
</html>';
    Show_page($content);
    exit;
}

/* Grab identifier */
if (isset($_POST['identifier']) && is_string($_POST['identifier'])) {
    $identifier = $_POST['identifier'];
} else if (isset($_SESSION['identifier']) && is_string($_SESSION['identifier'])) {
    $identifier = $_SESSION['identifier'];
} else {
    $identifier = null;
}

/* Create OpenID object */
try {
    $o = new OpenID_RelyingParty($returnTo, $realm, $identifier);
} catch (Exception $e) {
    Die_error($e);
}

/* Redirect to OpenID provider */
if (isset($_POST['start'])) {
    try {
        $authRequest = $o->prepare();
    } catch (Exception $e) {
        Die_error($e);
    }

    $url = $authRequest->getAuthorizeURL();

    header("Location: $url");
    exit;
} else {
    /* Grab query string */
    if (!count($_POST)) {
        list(, $queryString) = explode('?', $_SERVER['REQUEST_URI']);
    } else {
        // I hate php sometimes
        $queryString = file_get_contents('php://input');
    }

    /* Check reply */
    try {
        $message = new OpenID_Message($queryString, OpenID_Message::FORMAT_HTTP);
    } catch (Exception $e) {
        Die_error($e);
    }

    $id = $message->get('openid.claimed_id');

    if (!empty($id) && isset($AUTH_MAP[$id])) {
        $_SESSION['PMA_single_signon_user'] = $AUTH_MAP[$id]['user'];
        $_SESSION['PMA_single_signon_password'] = $AUTH_MAP[$id]['password'];
        session_write_close();
        /* Redirect to phpMyAdmin (should use absolute URL here!) */
        header('Location: ../index.php');
    } else {
        Show_page('<p>User not allowed!</p>');
        exit;
    }
}

If you intend to pass the credentials using some other means than, you have to implement wrapper in PHP to get that data and set it to $cfg['Servers'][$i]['SignonScript']. There is very minimal example in examples/signon-script.php:

<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
 * Single signon for phpMyAdmin
 *
 * This is just example how to use script based single signon with
 * phpMyAdmin, it is not intended to be perfect code and look, only
 * shows how you can integrate this functionality in your application.
 *
 * @package    PhpMyAdmin
 * @subpackage Example
 */


/**
 * This function returns username and password.
 *
 * It can optionally use configured username as parameter.
 *
 * @param string $user User name
 *
 * @return array
 */
function get_login_credentials($user)
{
    /* Optionally we can use passed username */
    if (!empty($user)) {
        return array($user, 'password');
    }

    /* Here we would retrieve the credentials */
    $credentials = array('root', '');

    return $credentials;
}

Config 认证方式

  • This mode is sometimes the less secure one because it requires you to fill the $cfg['Servers'][$i]['user'] and $cfg['Servers'][$i]['password'] fields (and as a result, anyone who can read your config.inc.php can discover your username and password).
  • ISPs, multi-user installations 一节中将会说明如何保护您的配置文件。

  • 为了让该认证方式更加安全,您还可以考虑使用主机认证的 $cfg['Servers'][$i]['AllowDeny']['order']$cfg['Servers'][$i]['AllowDeny']['rules'] 指令。

  • 与 cookie 和 http 不同,在访问 phpMyAdmin 时 config 认证方式不会要求用户登录。虽然设计如此但这将导致任意用户都能访问。我们建议使用某些方式进行限制,如一个含有要求 HTTP 认证指令的 .htaccess 文件或者从路由器或防火墙设置禁止特定的 HTTP 访问(上述方法均不属于本文档的范围,但可以很容易地通过 Google 搜索到)。

加固您的 phpMyAdmin 安装

The phpMyAdmin team tries hard to make the application secure, however there are always ways to make your installation more secure:

  • Follow our Security announcements and upgrade phpMyAdmin whenever new vulnerability is published.

  • Serve phpMyAdmin on HTTPS only. Preferably, you should use HSTS as well, so that you’re protected from protocol downgrade attacks.

  • Ensure your PHP setup follows recommendations for production sites, for example display_errors should be disabled.

  • Remove the test directory from phpMyAdmin, unless you are developing and need test suite.

  • Remove the setup directory from phpMyAdmin, you will probably not use it after the initial setup.

  • Properly choose an authentication method - Cookie 认证方式 is probably the best choice for shared hosting.

  • Deny access to auxiliary files in ./libraries/ or ./templates/ subfolders in your webserver configuration. Such configuration prevents from possible path exposure and cross side scripting vulnerabilities that might happen to be found in that code. For the Apache webserver, this is often accomplished with a .htaccess file in those directories.

  • Deny access to temporary files, see $cfg['TempDir'] (if that is placed inside your web root, see also Web server upload/save/import directories.

  • It is generally a good idea to protect a public phpMyAdmin installation against access by robots as they usually can not do anything good there. You can do this using robots.txt file in root of your webserver or limit access by web server configuration, see 1.42 How can I prevent robots from accessing phpMyAdmin?.

  • In case you don’t want all MySQL users to be able to access phpMyAdmin, you can use $cfg['Servers'][$i]['AllowDeny']['rules'] to limit them or $cfg['Servers'][$i]['AllowRoot'] to deny root user access.

  • Consider hiding phpMyAdmin behind an authentication proxy, so that users need to authenticate prior to providing MySQL credentials to phpMyAdmin. You can achieve this by configuring your web server to request HTTP authentication. For example in Apache this can be done with:

    AuthType Basic
    AuthName "Restricted Access"
    AuthUserFile /usr/share/phpmyadmin/passwd
    Require valid-user
    

    Once you have changed the configuration, you need to create a list of users which can authenticate. This can be done using the htpasswd utility:

    htpasswd -c /usr/share/phpmyadmin/passwd username
    
  • If you are afraid of automated attacks, enabling Captcha by $cfg['CaptchaLoginPublicKey'] and $cfg['CaptchaLoginPrivateKey'] might be an option.

  • Failed login attemps are logged to syslog (if available, see $cfg['AuthLog']). This can allow using a tool such as fail2ban to block brute-force attempts. Note that the log file used by syslog is not the same as the Apache error or access log files.

  • In case you’re running phpMyAdmin together with other PHP applications, it is generally advised to use separate session storage for phpMyAdmin to avoid possible session based attacks against it. You can use $cfg['SessionSavePath'] to achieve this.

Using SSL for connection to database server

It is recommended to use SSL when connecting to remote database server. There are several configuration options involved in the SSL setup:

$cfg['Servers'][$i]['ssl']
Defines whether to use SSL at all. If you enable only this, the connection will be encrypted, but there is not authentication of the connection - you can not verify that you are talking to the right server.
$cfg['Servers'][$i]['ssl_key'] and $cfg['Servers'][$i]['ssl_cert']
This is used for authentication of client to the server.
$cfg['Servers'][$i]['ssl_ca'] and $cfg['Servers'][$i]['ssl_ca_path']
The certificate authorities you trust for server certificates. This is used to ensure that you are talking to a trusted server.
$cfg['Servers'][$i]['ssl_verify']
This configuration disables server certificate verification. Use with caution.

Known issues

Users with column-specific privileges are unable to “Browse”

If a user has only column-specific privileges on some (but not all) columns in a table, “Browse” will fail with an error message.

As a workaround, a bookmarked query with the same name as the table can be created, this will run when using the “Browse” link instead. Issue 11922.

Trouble logging back in after logging out using ‘http’ authentication

When using the ‘http’ auth_type, it can be impossible to log back in (when the logout comes manually or after a period of inactivity). Issue 11898.