Skip to content

Conversation

@adamziel
Copy link
Collaborator

@adamziel adamziel commented Sep 13, 2025

Motivation for the change, related issues

Allows connecting to a MySQL server when $host is set to "localhost" and not "127.0.0.1".

Mysqlnd driver used by all PHP connectors (mysqli_connect, new PDO, ...) has a hardcoded behavior: when $host is "localhost", it connects via a unix socket and not a TCP socket. Supporting unix sockets from an Emscripten app is not trivial.

Fixes #370
Fixes WordPress/playground-tools#18

Implementation

This PR patches the mysqlnd driver to replace "localhost" with "127.0.0.1" and use a TCP connection.
Technically, this changes the semantics compared to what a native PHP build would do. However, the vast majority of MySQL users don't care about this distinction. All they see is a failed connection to localhost. If a use-case emerges for connecting over a unix socket specifically and not over TCP, we'll need to revisit this approach and explore adding support for unix sockets.

Testing Instructions (or ideally a Blueprint)

CI – there's a new test

@adamziel adamziel marked this pull request as ready for review September 14, 2025 19:12
@adamziel adamziel requested review from a team, sejas and wojtekn September 14, 2025 19:12
Copy link
Collaborator

@zaerl zaerl left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, Adam, for this patch here. Unfortunately, it's not something we could suggest to core PHP maintainers.

Although I don't think we're the only ones who don't want an open socket working on the same machine, at least we have a choice.

🚢

fi

# Replace the hostname assignment line with our patched version
sed -i.bak 's/MYSQLND_CSTRING hostname = { host, host? strlen(host) : 0 };/\tconst char * effective_host = (host \&\& strcmp(host, "localhost") == 0) ? "127.0.0.1" : host;\
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've checked the php-src file, and this is the best quick solution. Great one. Since it hasn't changed in over 10 years, we can assume it will continue to work in the near future as well.

@adamziel adamziel merged commit 4a67173 into trunk Sep 15, 2025
26 checks passed
@adamziel adamziel deleted the mysql-localhost branch September 15, 2025 07:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

wp-now: Error establishing database connection when 'DB_HOST' is 'localhost'

3 participants