DIGITAL4FRONT / CODE BASE

PHP on Windows: mysql_config_editor and .mylogin.cnf

Understand why mysql_config_editor ignores PHP proc_open() password pipes on Windows. Create a MySQL login path securely, call mysql.exe from PHP without a password argument, and avoid common credential-storage mistakes.

Share

`mysql_config_editor` can create a MySQL `.mylogin.cnf` login-path file on Windows, but it is not a normal program that you can reliably automate by writing a password to `proc_open()` standard input. Its password prompt is designed for interactive entry. The practical solution is to provision the login path in a real console, then let PHP launch MySQL client commands with `--login-path`. For unattended installation, use a deliberate secrets-provisioning process rather than assuming a pipe can answer the prompt.

The problem: proc_open works with a batch file but hangs with MySQL

A PHP installer might need to configure MySQL access without leaving a password in a plain-text option file. MySQL provides `mysql_config_editor`, which creates an obfuscated login-path file named `.mylogin.cnf`.

A developer can successfully send input to a batch file with `proc_open()`:

php
<?php
$process = proc_open('test.bat', [
    0 => ['pipe', 'r'],
    1 => ['pipe', 'w'],
    2 => ['pipe', 'w'],
], $pipes);

if (!is_resource($process)) {
    throw new RuntimeException('Unable to start the process.');
}

fwrite($pipes[0], "20\n");
fclose($pipes[0]);

$output = stream_get_contents($pipes[1]);
$error = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);

$exitCode = proc_close($process);

But replacing the batch file with `mysql_config_editor set --password` can leave the command waiting at its password prompt. Writing password text to `$pipes[0]` does not necessarily satisfy the prompt.

The important distinction is that `proc_open()` creates **process pipes**, not network sockets and not automatically a real terminal. An interactive program can obtain password input from a console or terminal independently of the redirected standard input stream. A prompt displayed in the console therefore does not prove the process is reading from the stdin pipe.

Do not respond to this by adding longer sleep calls. Timing is not the underlying problem.

What mysql_config_editor actually stores

A MySQL login path is a named set of connection settings such as host, username, port and password. The official MySQL client tools can read those settings later without including a password on the command line.

On Windows, the default location is:

text
%APPDATA%\MySQL\.mylogin.cnf

On Linux and other non-Windows systems, the default location is the current user's home directory:

text
$HOME/.mylogin.cnf

The file is **obfuscated**, not an unbreakable credential vault. A determined attacker with access to the file may be able to recover its contents. Restrict access using operating-system permissions and use a dedicated least-privilege MySQL account.

The file is also associated with the operating-system account running the MySQL client. Creating it under your interactive Windows account does not mean a web server service, scheduled task or different Windows user will automatically see the same file.

See the MySQL 8.4 mysql_config_editor reference for supported options, locations and security limitations.

1. Create the login path interactively on Windows

Open Command Prompt or PowerShell using the Windows account that should own the login-path file. Ensure that the MySQL installation's `bin` directory is on PATH, or use the full executable path.

Run this command:

bash
mysql_config_editor set --login-path=app --host=127.0.0.1 --port=3306 --user=app_user --password

Enter the password only when prompted. Do not append the password after `--password`.

Confirm the saved login path:

bash
mysql_config_editor print --login-path=app

The utility should show the saved connection details while masking the password. Then test the credentials with the MySQL command-line client:

bash
mysql --login-path=app --execute="SELECT 1"

If it succeeds, MySQL can read the configured login path. This is the supported path from credential provisioning to noninteractive client execution.

Avoid choosing `client` as the login-path name unless you intend its settings to become defaults for ordinary MySQL client commands. A dedicated name such as `app` makes the selection explicit.

2. Call MySQL securely from PHP after provisioning

Once the login path exists, PHP can run MySQL client commands without receiving the database password and without passing it as a command-line argument.

The following example requires PHP 8 or later, an installed MySQL command-line client and an existing login path named `app`. Run it through PHP CLI. Configure `MYSQL_EXE` to the full path of `mysql.exe`, particularly if the MySQL directory is not on PATH.

Save the file as `check-mysql-login.php`:

php
<?php
declare(strict_types=1);

if (PHP_SAPI !== 'cli') {
    fwrite(STDERR, "This script requires PHP CLI.\n");
    exit(1);
}

$mysqlExe = getenv('MYSQL_EXE');

if (!is_string($mysqlExe) || $mysqlExe === '') {
    fwrite(STDERR, "Set MYSQL_EXE to the mysql executable path.\n");
    exit(1);
}

$command = [
    $mysqlExe,
    '--login-path=app',
    '--batch',
    '--skip-column-names',
    '--execute=SELECT 1',
];

$descriptors = [
    0 => ['pipe', 'r'],
    1 => ['pipe', 'w'],
    2 => ['pipe', 'w'],
];

$process = proc_open($command, $descriptors, $pipes);

if (!is_resource($process)) {
    throw new RuntimeException('Could not launch the MySQL client.');
}

fclose($pipes[0]);
$output = stream_get_contents($pipes[1]);
$error = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);

$exitCode = proc_close($process);

if ($exitCode !== 0 || trim((string) $output) !== '1') {
    error_log('MySQL client check failed (exit code ' . $exitCode . ').');
    exit(1);
}

echo "MySQL login path works.\n";

On Windows PowerShell, set the executable path for the current session, adjusting it to your installation:

bash
$env:MYSQL_EXE = 'C:\Program Files\MySQL\MySQL Server 8.4\bin\mysql.exe'
php check-mysql-login.php

The script uses an argument array rather than constructing a shell command string. PHP can launch the executable without passing the command through `cmd.exe`, avoiding common shell quoting mistakes. The database password is supplied by MySQL's login-path mechanism, not by PHP.

This example performs a short, fixed query. Code that produces large stdout and stderr streams should handle both streams without allowing pipe buffers to block the child process.

The PHP proc_open documentation explains Windows process options and descriptor behaviour.

3. Why redirecting stdin does not fix the password prompt

The `proc_open()` descriptor specification tells PHP which streams to connect to the child process. For example, `0 => ['pipe', 'r']` gives PHP a way to write to the child's standard input.

That arrangement works when a child program actually reads the intended input from standard input. Password-handling utilities can instead use console-specific input to avoid accidental exposure through pipes or redirected input.

The result can look confusing: PHP successfully launches the executable, a prompt appears, but the child continues waiting even after PHP writes the password and flushes the pipe.

Windows offers native console and pseudoconsole facilities, but using them properly is platform-specific. A Unix-style `expect` workflow is not a drop-in, dependency-free solution for Windows PHP. Neither a PHP pipe nor an arbitrary socket is a portable replacement for a terminal.

For interactive setup, run the official utility in a genuine console. For fully unattended setup, choose a different provisioning architecture and document how secrets enter it.

4. Should PHP create .mylogin.cnf directly?

It is technically possible to write the binary file from PHP. The Stack Overflow discussion includes a PHP implementation that follows an existing reverse-engineered encoder, and the question's author reported that it worked in their Windows tests.

That does not make the binary format a supported, stable public interface. A hand-built encoder depends on implementation details, file layout, cryptographic conventions and MySQL client compatibility. It also puts raw passwords into the PHP process while constructing the file.

For a disposable development environment with a pinned MySQL version, a carefully reviewed encoder might be an explicit engineering choice. For production credential provisioning, favour the official utility and controlled OS-account permissions. Do not present a copied AES encryption snippet as a general-purpose secure credential store.

If your requirement is that a PHP installer creates a working `.mylogin.cnf` without human interaction, document that this requires either a deliberately supported automation mechanism in the environment or maintaining and testing a version-specific encoder. There is no promise that ordinary `fwrite()` to a `proc_open()` stdin pipe will do it.

5. Does PDO automatically read .mylogin.cnf?

Do not assume that PHP PDO or MySQLi automatically uses a login path created for the MySQL command-line tools. The login-path feature is designed for compatible MySQL client programs. PDO database connection code ordinarily takes its host, database name, username and password from the DSN and connection arguments supplied by the application.

For a native PHP web application that needs PDO, a common arrangement is to provision its secret separately and inject it through a protected configuration mechanism:

php
<?php
declare(strict_types=1);

$dsn = getenv('DB_DSN');
$user = getenv('DB_USER');
$password = getenv('DB_PASSWORD');

if (!$dsn || !$user || $password === false) {
    throw new RuntimeException('Database configuration is missing.');
}

$pdo = new PDO($dsn, $user, $password, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_EMULATE_PREPARES => false,
]);

The environment settings must come from a trusted configuration or secrets-management system. Environment variables are not a universal security boundary; restrict access to the PHP process, hosting account and deployment environment. Do not expose them through diagnostic pages or logs.

The two use cases are different: `mysql --login-path=app` suits a MySQL command-line client launched from PHP, while PDO should use a properly managed application secret.

6. Common Windows installation failures

**The program still waits for a password:** The command was launched without an interactive console. Verify that `mysql_config_editor set` works when run manually in Command Prompt or PowerShell.

**The login path works as your user but not as a scheduled task:** The task may run under a different Windows account or profile. Check its account identity, `%APPDATA%`, access permissions and the login-path file used by that account.

**PHP cannot find mysql.exe:** Use the full executable path in `MYSQL_EXE`. The MySQL executable and `mysql_config_editor.exe` are different programs.

**The MySQL client asks for credentials again:** Confirm that the named login path exists and that the client can read it. Check for conflicting command-line options, incorrect account permissions and the Windows user running the process.

**A login path must be stored somewhere else:** MySQL supports the `MYSQL_TEST_LOGIN_FILE` environment variable to select an alternate login-path file. This changes which file supported MySQL client programs use; it does not make an invalid path or weak file permissions safe. See the MySQL 8.4 environment variable reference.

**The installer must run silently from a browser:** Avoid a browser-triggered process that waits for console input. Use an administrator-controlled installer, scheduled provisioning workflow or separately managed PDO credentials.

Security checks and next steps

Do not put MySQL passwords in command arguments, batch files, debug output or application logs. MySQL also warns against using the `MYSQL_PWD` environment variable as a password-passing workaround; it is insecure and deprecated in MySQL 8.4.

Treat `.mylogin.cnf` as a sensitive credential file despite its obfuscation. Restrict access, use separate database users for installation and normal application operation, and rotate credentials when access is compromised.

For a typical Windows PHP application, the recommended sequence is simple: create the login path once with `mysql_config_editor` in an interactive session, verify it with `mysql --login-path=app`, then run supported MySQL client commands from PHP using an argument-array `proc_open()` call. For PDO connections, supply credentials through your application's protected configuration instead.

The central lesson is that **a pipe is not a terminal**, and writing a password into a process stream is not equivalent to responding to a console password prompt.

For further reading, consult the MySQL 8.4 login-path documentation, MySQL password security guidance, PHP process execution documentation and the original Stack Overflow discussion.

WhatsApp us