Error connecting a remote server from a PHP page - php

I have a .php file which should receive and show data from a remote database. I run my program from PHPStorm (which is connected to the remote database through the "Database" right-hand pane) and a browser. Both ways I get an error which depends on the number of arguments I pass to pg_connect() function.
If I use
$dbconn = pg_connect("host=pg hostaddr=server.address.ru port=5432 dbname=studs user=... password=...")
than the error is
Unable to connect to PostgreSQL server: could not parse network address "server.address.ru": Unknown host in...
But I am sure that I wrote the address correctly (there are no typos in it). This way I am not sure about the correctness of the format of the passed arguments.
If I use
$dbconn = pg_connect("host=server.address.ru dbname=studs user=... password=...")
command, the error is
pg_connect(): Unable to connect to PostgreSQL server: could not connect to server: Connection timed out
I found a lot of information about this errors, but it mostly refers to localhosts and doesn't solve my problem. I guess, the problem can be in the way this connection is set in the function, but I do not know why it doesn't work properly. How can I solve it?

Thanks to #TangentiallyPerpendicular, I got on a right way of setting the connection. But since I have PostgreSQL remote connection, it wasn't just up to this answer.
What I did and how I set the connection (I work from PHPStorm so all the actions are based on this platform):
Open PuTTY and set an SSH connection (an SSH tunnel) between the server's DB port (for PostgreSQL it's usually 5432) and your local computer's PostgreSQL port (5432 most often too). You can do the same from a command line.
Open PHPStorm and in "Database" section (an icon on the right-hand side of the environment or "Data Sources and Drivers" in Settings) set general information ("General" section) and set another SSH tunnel ("SSH/SSL"). In SSH Configurations (the same "SSH/SSL" section) set a local port - it will be important in our connection! Let's say, this port is 20000. The port of the server you're connecting to is a usual one (usually 22 or 2222).
In the program the right use of function is $dbconn = pg_connect("host=localhost port=20000 dbname=studs user=... password=...") or die('Error: ' . pg_last_error());
The connection is set.
For those who has troubles setting an SSH tunnel with a remote PostgreSQL from PHP this can be useful too.

Related

How to create a tunnel to a remote AWS database after being connected in ssh to the Bastion host, all using in PHP

I am trying to create a tunnel using ssh2_tunnel() to a remote AWS database, after being connected in ssh to the bastion host, via php, that has access to this remote MySql db.
Here is my actual code :
<?php
$ssh = ssh2_connect('domainofbastionhost', 22);
if (ssh2_auth_password($ssh,'myuserofthebastion','mypassofthebastion'){
$tunnel = ssh2_tunnel($ssh,'xxxx.xxx.xxx.rds.amazonaws.com',3306);
$stream_set_blocking($tunnel,true);
//Everything works fine up to here
$db = new PDO('mysql:host=xxxx.xxx.xxx.rds.amazonaws.com;port=3306;dbname=myawsdbname','myusertoaccessmyawsdb','mypasstoaccessmyawsdb');
}
?>
Due to this $db line, I get on my localhost page "Uncaught PDOException: SQLSTATE[HY000] [2002] Connection timed out ....".
I have tried to connect to the db from the bastion host (by ssh) through my shell, everything works fine, I am greeted by the "Trying 'IPOFTHEAWSDB'... Connected to 'canonical domain name of the db'. Escape character is '^]'. ] 5.5.5-xx.x.xx-MariaDB-xxxxxxmysql_native_password", which means everything works fine. I even tried to connect directly to the aws db, and I get disconnected, which means that my bastion host is clearly whitelisted to access the db.
I think the problem is that when I want to create my new PDO object, I am not whitelisted to access the resource, which means I have to use that $tunnel variable somewhere. I have seen a few examples online of some users using, instead of my $db line :
$db = new PDO('mysql:unix_socket=/var/run/mysqld/mysqld.sock;dbname=myawsdbname,'myusertoaccessmyawsdb','mypasstoaccessmyawsdb');
But this is not working, as I don't have access to this mysql.sock resource as it should be on the bastion host. It's using my own mysqld.sock from my local machine. But where is the $tunnel stream really stored ? I am not sure.
I am quite confused as if it is possible to do so, and if so, how.
If you know anything or find anything, please tell me, it would mean a lot.
ssh2_tunnel() returns a raw socket resource, which is not going to be usable by any MySQL client libraries. It does not create a tunnel like the ssh CLI binary does. Also Unix sockets and TCP are very different beasts, so I would suggest not trying to follow that thread any further.
I would suggest not attempting to establish the tunnel in the context of a PHP script at all, as every request will open another connection and tunnel, potentially creating a lot of overhead on the bastion's SSH server.
To create an SSH tunnel on the command line:
ssh -N -L 3306:your.rds.instance:3306 your_user#bastion.host
Now you should be able to connect via 127.0.0.1:3306 in your PHP script.
To close the connection/turn off the tunnel issue ssh -O exit your_user#bastion.host.
However, I would not suggest using SSH tunnels for anything intended to be unattended. This is because I have found SSH tunnels to be finnicky, and they do not re-establish themselves after an interruption unless you're using a wrapper script, which is another layer of kludge. So I would suggest this approach for local dev/remote access only.
For a persistent connection that you might want to use to connect services/websites over, I would suggest some form of VPN depending on your particular requirements. I believe you can also apply security groups to your RDS instances to simply whitelist connections from certain public IP addresses/networks, but use with caution.

How to connect a PHP app to MySQL via pipes?

I have found glimpses of the fact that it is possible to connect PHP to MySQL via pipes in their documentation of MySQLi, but I cannot, for the life of me, find anyone explaining what is needed.
The host parameter claims:
When possible, pipes will be used instead of the TCP/IP protocol.
But when is it "possible"? I have my own machine, and I definitely have the necessary privileges to achieve this, I just don't know how. Connecting to the host localhost reports "Localhost via UNIX socket" when examining the host_info.
Trying to follow one (downvoted) comment from that page, and connecting to host ., with socket parameter set to mysql, causes a 2002 connection error.
How do I tell it to (always) connect via a pipe instead?
Today I had the same issue and it required much time to solve this on Windows.
I can establish a named pipe connection with the following code:
$connection = new mysqli('.', 'user', 'pass', 'database', null, '\\\\.\\pipe\\name_of_pipe');
The server, where I want to connect to, has the following configuration:
[mysqld]
skip-networking
enable-named-pipe
socket=name_of_pipe
Using '127.0.0.1', 'localhost' or NULL as hostname doesn't work. Also you must specify a path to the named pipe and not just the name of the pipe.
Unfortunately the PHP documentation is a little bit weak here...
Named Pipes only work under Windows.
Also
Whenever you specify "localhost" or "localhost:port" as server, the MySQL client library will override this and try to connect to a local socket (named pipe on Windows). If you want to use TCP/IP, use "127.0.0.1" instead of "localhost". If the MySQL client library tries to connect to the wrong local socket, you should set the correct path as in your PHP configuration and leave the server field blank.
It is not mentioned in the actual PHP documentation, but it should be still valid.

Error 500 ( Fatal Error ) using pg_connect() in php

im trying to use pg_connect to access postgres on another server,,
i did opened the remote access and i can use bash to connect to my postgres server ! and i did host all all client_ip/32 trust in config but when im trying to use pg_connect i get error 500 !
pgsql is also installed and i've checked it with function_exists('pg_connect') and i returns true !
my code is :
$dbconn = pg_connect("host=remote_IP port=5432 dbname=myDB user=postgres") or die("Could not connect");
i've also tried this and get fatal error 500 again
$dbconn = pg_connect("host=remote_IP port=5432 dbname=myDB
user=another_super_user_i_made password=user_password") or die("Could not connect");
what is the problem ?
when you are able to connect to a server from one machine on your network, but get a connection timed out issue from another machine, it usually is due to one of a few things.
1) DNS. The machine you are testing from (the "remote access" as you call it) is able to resolve the DNS name and the webserver running your PHP code is not. You can use actual IP address instead of DNS names to test this.
2) Connectivity. Different machines are connected in different ways in a network. If you are able to get to an IP from the "remote access" machine but the web server is having trouble connecting to it (with "connection timed out"), try connecting directly to that web server (using "remote access" like SSH) and see if you can connect manually from there.
If it's not a network related issue it could be an issue with your default PG timeouts. Try setting them manually with the connect string. Specifically, the "connect_timeout" option, like this:
$d=pg_connect('host=example.com user=pgsql dbname=postgres connect_timeout=5');
There was host blocking issue !
my client hosting was not enabling remote access to DB !
you should check with your hosting that they can trace your problem

Can't connect to remote SQL database in PHP, but remote access is set up and confirmed working

I'm trying to learn to use SQL stuff in PHP but I'm having an issue simply connecting to my database.
The database is almost certainly working with remote access to some extent. I disabled iptables temporarily (I know, bad bad bad!), so there's no firewall blocking access. The MySQL user I am using is configured to be able to connect from any IP. The SQL server is listening properly to all connections and is run on a Linux dedicated server.
[root#1742CC-XEON ~]# netstat -lpnut | grep mysql
tcp 0 0 0.0.0.0:3315 0.0.0.0:* LISTEN 3915/mysqld
I've also used the exact same credentials to successfully remotely connect to my database in Java, like so:
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://__ip__:_port_/_dbname_", "username", "password");
System.out.println("Connection established.");
This functions just fine, and I can successfully run queries, etc. Since I have iptables disabled at the moment this connection functions just fine anywhere that has Java and the Java SQL connector.
Now, I'm trying to connect to the same database in PHP:
$db = mysqli_connect($sql_host, $sql_user, $sql_pass, $sql_db, $sql_port);
And this connection fails with the following error:
Warning: mysqli_connect(): (HY000/2003): Can't connect to MySQL server on 'xx.xx.xx.ip' (111)
Note that $sql_user, $sql_pass, $sql_host, etc. are all the same as the credentials used in the Java connection, so there shouldn't be any issue with the user not being able to access the server from a new IP, since that user is granted access on % and I've made sure that it is indeed able to access the SQL server from multiple IPs not explicitly allowed in the users table. I've also tried different users, including root, and all give the same connection error.
I've spent a few hours looking around but I honestly can't find anything that seems to be the right answer, would really appreciate any help!
Is it possible that this is caused by my webhost? I've tried this script on HostGator webhost as well as the whois.com hosting and both give the same error. Could they possibly be preventing the PHP script from connecting to the remote database?
Have you tried telneting to the server on 3315 from your webhosts?

Trouble Connection to phpMyAdmin MySQL database

I'm pretty new at php and I'm getting an error whenever I try to load a php page that requires access to the database I set up on phpMyAdmin
Here is the error:
Database connection failed: Can't connect to local MySQL server
through socket '/tmp/mysql.sock' (46) (2002)
The code I'm using for the connection is this:
<?php
define("DB_SERVER", "localhost");
define("DB_USER", "xxxx");
define("DB_PASS", "xxxx");
define("DB_NAME", "tester");
$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
// Test if connection occurred.
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
?>
I set up phpMyAdmin on my server by following the directions from the site that hosts my website, so I'm pretty sure I did that correctly.
I've been able to get databases to work before on my computer by using WAMP, but this is the first time I've actually tried getting everything working online, so I don't know if this is a stupid error on my part, or if it's something bigger.
I don't know what a socket is either so I'm not sure how to troubleshoot this.
Thanks for your help!!
You have to find a way to connect to your MySQL instance. There are two ways, TCP (networking, even if that network address is 127.0.0.1) and sockets (a file such as /var/run/mysqld/mysql.sock). Generally, MySQL is configured out of the box to listen on both, and again in general there's little difference between the two. You have to be careful when creating or editing permissions that they match the connection type, user bob#localhost is different from user bob#127.0.0.1. I tend to use sockets and that's also what your script is trying to do by default. You could tell it to connect via TCP, but it's just as easy to tell it the proper path to the socket.
Anyway, for me the quickest way to figure it out is to try the command line tool. If you can do mysql -u root -p at the command line and get a MYSQL> shell prompt, type in "STATUS" and look for the Connection line, which might read Localhost via UNIX socket; and a bit further down you might see a line like "UNIX socket: /var/run/mysqld/mysql.sock" in which case you just tell your PHP script or global PHP configuration about the socket path, because right now it's looking in /tmp/mysql.sock which doesn't exist.
You can also see this when you log in to phpMyAdmin, it should display on the right hand side of the page some "Database Server" information -- look here for the "Server" line which might read something like "phpMyAdmin demo - MySQL (192.168.30.23 via TCP/IP" (a clear indication you're connecting over TCP).
Anyway, whichever method you use to find the path to the socket or deciding to use TCP networking, see the PHP manual page for information about using that to connect. You can also just set the global path in php.ini for the socket (which is what I'd suggest you do), then you don't have to set it manually in each script as it just uses the php.ini setting as a default. You may need to set each of the values for pdo_mysql.default_socket, mysql.default_socket, and mysqli.default_socket (though in your code you're only using mysqli, so technically you only need to set the last value...but why risk confusing your future self with questions like "why would mysqli work but pdo fail?" -- just set them all now and don't worry about it).
Hope this helps.
That either means you don't have the privileges to access phpMyAdmin or that socket isn't there. Try reinstalling phpMyAdmin.

Categories