Check connection to server php

mysqli_ping

Checks whether the connection to the server is working. If it has gone down and global option mysqli.reconnect is enabled, an automatic reconnection is attempted.

Note: The php.ini setting mysqli.reconnect is ignored by the mysqlnd driver, so automatic reconnection is never attempted.

This function can be used by clients that remain idle for a long while, to check whether the server has closed the connection and reconnect if necessary.

Parameters

Procedural style only: A mysqli object returned by mysqli_connect() or mysqli_init()

Return Values

Returns true on success or false on failure.

Errors/Exceptions

If mysqli error reporting is enabled ( MYSQLI_REPORT_ERROR ) and the requested operation fails, a warning is generated. If, in addition, the mode is set to MYSQLI_REPORT_STRICT , a mysqli_sql_exception is thrown instead.

Examples

Example #1 mysqli::ping() example

$mysqli = new mysqli ( «localhost» , «my_user» , «my_password» , «world» );

/* check connection */
if ( $mysqli -> connect_errno ) printf ( «Connect failed: %s\n» , $mysqli -> connect_error );
exit();
>

/* check if server is alive */
if ( $mysqli -> ping ()) printf ( «Our connection is ok!\n» );
> else printf ( «Error: %s\n» , $mysqli -> error );
>

/* close connection */
$mysqli -> close ();
?>

$link = mysqli_connect ( «localhost» , «my_user» , «my_password» , «world» );

/* check connection */
if ( mysqli_connect_errno ()) printf ( «Connect failed: %s\n» , mysqli_connect_error ());
exit();
>

/* check if server is alive */
if ( mysqli_ping ( $link )) printf ( «Our connection is ok!\n» );
> else printf ( «Error: %s\n» , mysqli_error ( $link ));
>

/* close connection */
mysqli_close ( $link );
?>

The above examples will output:

User Contributed Notes 3 notes

The behaviour about the option mysqli.reconnect is default set to Off at Debian PHP Packages. So i would recommend to update the first line description about the recommendation at the option mysqli.reconnect. (practice note ;))

As jay at grooveshark dot com very helpfully pointed out, the mysqlnd driver which is becoming pretty standard does not obey reconnect commands. If you have a DB wrapper class (which hopefully you do) you can implement your own version of ping() such as:

class db extends mysqli
private $db_host ;
private $db_user ;
private $db_pass ;
private $db_name ;
private $persistent ;

public function __construct ( $db_host , $db_user , $db_pass , $db_name , $persistent = true )
$this -> db_host = $db_host ;
$this -> db_user = $db_user ;
$this -> db_pass = $db_pass ;
$this -> db_name = $db_name ;
$this -> persistent = $persistent ;

parent :: init ();
parent :: options ( MYSQLI_OPT_CONNECT_TIMEOUT , 1 );
@ parent :: real_connect (( $this -> persistent ? ‘p:’ : » ) . $this -> db_host , $this -> db_user , $this -> db_pass , $this -> db_name );

if ( $this -> connect_errno )
die( «All DB servers down!\n» );
>

public function ping ()
@ parent :: query ( ‘SELECT LAST_INSERT_ID()’ );

if ( $this -> errno == 2006 )
$this -> __construct ( $this -> db_host , $this -> db_user , $this -> db_pass , $this -> db_name , $this -> persistent );
>
.
>

$db = new db ( DB_HOST , DB_USER , DB_PASS , DB_NAME );
// Some code that potentially takes a really long time to execute goes here
// Ping for safety to try to gracefully reconnect
$db -> ping ();
// Now we should be able to run queries again
$db -> query ( ‘SELECT LAST_INSERT_ID()’ );

?>

If you wanted you could even put «$this->ping();» at the top of db::query() to avoid any explicit reconnection calls but I wouldn’t recommend it due to the (slight) overhead of running the cheap «SELECT LAST_INSERT_ID()» query every time prior to running your real intended query. There are probably even cheaper queries to run in favor of «SELECT LAST_INSERT_ID()» but it was the first that came to mind and is cheap enough for most purposes since you shouldn’t be calling ping() a whole bunch anyway.

Источник

Php php check connection to server

Is there any port that I need to open beside SQL server port for PHP successfully connect to the server? The purpose of the code is to check an open port remotely at difference server (server 2012) and count the total connections and print it.

PHP server connection test

Is there a php script/snippets out there that allows you to check a URL/IP for connection speed. Say example the URL is www.example.com and when I run the php script it will display how long it took to connect (211ms) to the URL/IP, I found some scripts that just show me if it’s online or offline but not the speed it took.

I’m very aware of the free and paid services. I want create my own custom/private one to monitor my many servers and having trouble finding a simple script to connect to given locations.

 // Close handle curl_close($ch); ?> 
$ch = curl_init("http://www.google.com/"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $start = microtime(); $foo = curl_exec($ch); $end = microtime(); curl_close($ch); echo "Seconds to load = ". $end - $start; 

This won’t consider images or javascript, just the intital response time and running of server code.

Php — Check for database connection, otherwise display message, Try this:

Connect PHP to SQL Server

PHP Connect to MySQL Database

Check is internet connection is working from PHP

I need to check if internet connection is effectively working in PHP.

function hasConnection() < $ch = curl_init("https://www.google.com"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); curl_exec($ch); $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); return ($httpcode>=200 && $httpcode

Generally two codes are working. But in this answer a read that ping is not always sure for check internet connection.

It’s cURL a sure/true way for check that? There is one more sure/true way?

Ping and traceroute only tell you whether or not the server is there NOT the service you want/need. If all you care about is whether or not a server is there/reachable then ping should be fine. If you care whether or not a particular service, like a web server is there, then cURL is what you are looking for.

Check connection php Code Example, Queries related to “check connection php” · php check internet connection · php check if internet connection is alive · if connect internet laravel

PHP checking remote server port and count connections

I have made a PHP to check an open port locally and count how many connections that is connect and print it. It works great locally but once i want to check remotely (my web server is on diff server) it just failed to get the result. The remote server is server 2012 with port 80 close. Below is the code.

 $handle = fopen("Includes/online.txt", "r"); $contents = fread($handle, filesize("Includes/online.txt")); fclose($handle); $contents = explode("\n", $contents); //print_r($contents); if (!$contents || (time() - $contents[1]) > $ocs) < $command = "netstat -p TCP -n"; exec($command,$status); //$status = PsExecute($command); //print_r($status); $status = array_slice($status, 5); $connections = array(); foreach ($status as $stat =>$s) < $c = preg_split('/ /', $s, -1, PREG_SPLIT_NO_EMPTY); if ($c[3] == 'ESTABLISHED') < $ipp = preg_split('/:/', $c[1], -1, PREG_SPLIT_NO_EMPTY); $ripp = preg_split('/:/', $c[2], -1, PREG_SPLIT_NO_EMPTY); for ($i=0; $i < 6; $i++ )< if ($ipp[1] == $config['server'][$i]['port']) < $connections[] = array('type'=>$c[0],'ip'=>$ipp[0],'port'=>$ipp[1],'rip'=>$ripp[0],'rport'=>$ripp[1],'con'=>$c[3]); > > > > $con = (!count($connections) ? 0 : count($connections)) ."\n". time(); if ($fp = fopen('Includes/online.txt', 'w')) < fwrite ($fp, $con); >$con = array('online' => count($connections)); > else < $con = array('online' =>$contents[0]); > //print_r($status); 
$config['server'] = array(array('ip'=>'ipxxx', 'port'=>10201),array('ip'=>'ipxxx', 'port'=>10202),array('ip'=>'ipxxx', 'port'=>10203),array('ip'=>'ipxxx', 'port'=>10204),array('ip'=>'ipxxx', 'port'=>10205),array('ip'=>'ipxxx', 'port'=>10208)); $ocs = "20";//in seconds it checks 

The purpose of the code is to check an open port remotely at difference server (server 2012) and count the total connections and print it. I have failed to do that remotely. Is there any port that I need to open beside SQL server port for PHP successfully connect to the server? MSSQL is connected and I don’t have any problems with that.

To me it’s unclear what you are asking for.

To check active TCP/IP connections on SQL-Server you can use there stored procedure sp_who2 or this query:

select * from sys.sysprocesses where net_library like 'TCP/IP%' 

SQL-Server has default TCP/IP port 1433. The TCP/IP protocol must be enabled on server side.

Php connection check Code Example, Queries related to “php connection check” · php check internet connection · php check if internet connection is alive · if connect internet laravel

Check external server DB availability with php script and connection

How can I catch a timeout error on mysql_connect on an external server/DB?

I am trying to write a script on my 2nd server to monitor if the other server is online. And I want to be able to connect to its database (not just check if a .html file is delivered out).

So I connect to the external server ( mysql_connect ) and perform a simple query. But I learned, when the server is really down the mysql_connect() will just hang on forever until the script times out.

Is there any solution for that? Like setting a time limit for mysql_connect .

I would like to have an Error thrown if mysql_connect can not connect to the database within 2-5 seconds (cause if that happens the server is really busy and something is going wrong) Any ideas?

I think what suit you better in this case is to use mysqli_real_connect(), especially because you are using it for an external server db, it will provide you with more options you can see the doc for further infos. It will provide you with a way to set the timeout like this :

if (!mysqli_options($link, MYSQLI_OPT_CONNECT_TIMEOUT, 5))

Step 3: Proof of concept connecting to SQL using PHP, Step 1: Connect · OpenConnection · < $serverName = "tcp:myserver.database.windows.net,1433"; $connectionOptions = ; Step 2: Execute query · ReadData

Источник

PHP checking mysql connection

I am building a project with installation (suck as WordPress) and the user provides database information (server, username, password and database). Now, I have to check if it can connect to the provided database. I tried this code, but it seems that it does not work (I am using Mysqli btw):

public function checkDataBaseConnection($server, $user, $pass, $db) < $conn = @mysqli_connect($server, $user, $pass, $db); if(mysqli_connect_error()) < return FALSE; >else < mysqli_close($conn); return TRUE; >> 

3 Answers 3

One thing: Remove the @ , that suppresses some php warnings.

public function checkDataBaseConnection($server, $user, $pass, $db) < $conn = @mysqli_connect($server, $user, $pass, $db); if(!$conn) < return FALSE; >else < //mysqli_close($conn); why would you close the connection? return $conn; >> 

Have you tried something like this?

if (checkDataBaseConnection($server, $user, $pass, $db)) echo "Success!"; else echo "Fail."; 

By the way you just can do this way

mysqli_connect($server, $user, $pass) or die('Connection failed'); 

Well, if you look at the PHP page for mysqli_connect you can see this example:

connect_error) < die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error); > /* * Use this instead of $connect_error if you need to ensure * compatibility with PHP versions prior to 5.2.9 and 5.3.0. */ if (mysqli_connect_error()) < die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error()); >echo 'Success. ' . $mysqli->host_info . "\n"; $mysqli->close(); ?> 

Источник

Читайте также:  Проверка содержит ли строка подстроку python
Оцените статью