Eli
Eli

Reputation: 4359

How to check if a database hostname:3306 is reachable with PHP

I am researching on how I can check to see if a specific hostname pointing to a database (presumably on port 3306) is reachable.

In php I am having a user fill out their database details, and with ajax I am running a script that pings the hostname provided but I can't seem to get the results I want.

With my current script:

if (fsockopen($host, $port, $errno, $errstr, $timeout)) {

    $return[$host]['message'] = "{$host} was reached";
    $return[$host]['status'] = true;

} else {

    $return[$host]['message'] = "{$host} is unreachable";
    $return[$host]['status'] = false;
}

i get that the host is reachable, which in some of my test is true but in other its suppose to be false.

as my end result i want to tell the user that the hostname provided is incorrect, or unreachable.

Edit:

This is my ajax call for those interested.

$('#db_host').focusout(function () {

    $.ajax({
        url:'/json/auth/ping/' + $(this).val(),
        dataType:'json',
        success:function (data) {

            if ($('#db_host').val() !== '') {

                if (data.status === false) {

                    $('#db_host').qtip({
                        content:data.message,
                        position : {
                            my :'left center',
                                at :'right center'
                        },
                        effect:function () {

                            $(this).slideUp(500);
                        },
                        style : {
                            classes : 'ui-tooltip-red'
                        },
                            show : {
                            ready : true
                        }
                    });
                }
            }
        }

    });
});

Upvotes: 1

Views: 2709

Answers (2)

Max
Max

Reputation: 2112

If your host will let you ping:

<?php
exec("ping -n 4 $host 2>&1", $output, $retval);
if ($retval != 0) { 
echo "Host Unreachable"; 
} 
else { 
echo "Host Reachable"; 
}    ?>

But I feel like that's unnescesary, and not nescesarily fast or dependable.

Otherwise, fsockopen is the best way to go about it: if you want to make sure you can connect to their db, why not just see if you can connect to their db?

<?php
$link = mysql_connect($host.':'.$port, $dbUsername, $dbPassword);
if (!$link) {
   die('Could not connect: ' . mysql_error());
}

Upvotes: 2

You could try this way.

<?php

$conn = mysql_connect('localhost','user','pass');
mysql_select_db('db',$conn);

if (!mysql_ping ($conn)) {
   mysql_close($conn);
   $conn = mysql_connect('localhost','user','pass');
   mysql_select_db('db',$conn);
   echo "connected again";
}

?>

Upvotes: 1

Related Questions