1

I'm trying to set up a proper connection string to connect to PG 9.2 from php 5.4. Piece of cake, unless the username contains a space...Maybe somebody can help me get my quoting right.

My attempt:

$dbconn = pg_connect('host=localhost dbname='.$database.' user="demo demo" password='.$password)
or die('connect failed');

is rejected by the server:pg_connect(): Unable to connect to PostgreSQL server: missing &quot;=&quot; after &quot;demo&quot;&quot; in connection info string in <b>/var/www/myhost.com/PGAccess/query.php

thanks, Max

1 Answer 1

1

Connection strings are single-quoted, e.g.:

user='my user'

So you need:

'host=localhost dbname=$database user=\'demo demo\' password=$password'

.... however, a user named O'Farrell would break that. If you care about this, you must also replace ' with \' (i.e. backslash-escape it) within strings ... then escape it again so PHP doesn't consume the quotes, producing a PHP string like (untested):

'host=localhost user=\'O\\\'Farrell\' password=whatever'

which gets parsed by PHP into the string to send to PostgreSQL's client library:

host=localhost user='O\'Farrell' password=whatever

which in turn parses it into attributes:

host: localhost
user: O'Farrell
password: whatever

You'll want to do that for passwords and other user-supplied strings. Otherwise a malicious user could set an options= directive passing potentially unwanted settings on the connection by using injection from their password string.

If your client library supports it, it may be easier to use libpq's PQoptions based connections, where each option is a separate string. This supported by Python's psycopg2; I don't know if PHP's Pg driver or PDO support it.

Sign up to request clarification or add additional context in comments.

1 Comment

Also, depending on your password setup in "pg_hba.conf" you may need to md5($password) your password before sending it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.