Connecting To A Non Standard MySQL Socket In PHP

Friday, February 11, 2011 - 14:28

Connecting to a MySQL database in PHP is usually not a difficult thing to do, in fact it is one of the first things that many tutorials will go though. However, there are certain curcumstances that require more information than the standard host, password and username details. A good example of this is when connecting to a local MySQL server through a different (or at least non standard) socket. The normal place for the MySQL socket to be on a Linux install is /var/run/mysqld/mysqld.sock, but some hosts might change this.

There is a setting in the php.ini file called default_socket, which exists for the pdo_mysql, mysql and mysqli sections and these should be used first if you need to point PHP towards a different socket. There are also system constants called MYSQL_SOCKET and MYSQLI_SOCKET which are created by PHP at compile time with a correctly specified "--with-mysql" setting. Some poorly configured hosts will not compile PHP correctly or not set up these variables and so problems can be experienced when trying to connect to "localhost".

After reading about this for a while I found a lot of confusion on the internet about how all of these settings are created and how they effect PHP when connecting to a MySQL database. MYSQL_SOCKET (and likewise MYSQLI_SOCKET) is used if you specify 'localhost' as the server name. PHP communicates via the socket instead of via TCP/IP in this case. This might only look for socket files in standard locations.

I have read that if the mysql.default_socket setting is specified then that is used instead of the MYSQL_SOCKET setting. My experience is that this isn't the case and that it is the MYSQL_SOCKET setting that takes precedence. If you have any alternative experience of this I would appreciate a comment.

When trying to connect to a localhost that hasn't been configured properly you need to set the socket location when creating a connection to the database. The standard MySQL library and the new MySQLi class work slightly differently here. Assuming that the new socket location is /a/random/directory/mysqld.sock, we can connect to the database using one of the following methods.

1
2
3
$connection = mysql_connect('localhost:3306/a/random/directory/mysqld.sock', 'username', 'password');
 
$mysqli = new mysqli('localhost', 'username', 'password', "", 3306, '/a/random/directory/mysqld.sock');

This doesn't look that hard, but for people who haven't seen this before (i.e., me) the php.net documentation is a little bit confusing on this issue.

Category: 
philipnorton42's picture

Philip Norton

Phil is the founder and administrator of #! code and is an IT professional working in the North West of the UK.
Google+ | Twitter

Add new comment