Implementing a Heart Beat In PHP With STOMP - php

I am conecting to a feed using the STOMP protocol in PHP
Because there are not many messages coming from the feed I believe my script thinks I have lost connection and the below error pops out:-
Uncaught exception 'StompException' with message 'Unexpected EOF while reading from socket'
If I can send a heart beat I believe the script will keep running - ie know I'm still there
The code is below. My problem is that I am getting errors. See NEW EDIT below
$channel="VSTP_ALL";
$con=new Stomp($server,$user,$password,array('heart-beat'=>'0,20000'));
if (!$con) {
die('connection failed: ' .stomp_connect_error());
}
$con->subscribe("/topic/".$channel);
if ($con->hasFrame()){
$msg=$con->readFrame();
foreach (json_decode($msg->body) as $event) {
var_dump($event);
}
$con->ack($msg);
}
die ('connection lost:'.time());
?>
EDIT
Have edited above to move/change syntax of array('heart-beat','0,20000') to array('heart-beat'=>'0,20000')
However I now get errors as follows in the foreach line:-
Notice: Trying to get property of non-object in
Warning: Invalid argument supplied for foreach()
and then in the ack($msg) line
Warning: Stomp::ack(): Expects parameter 2 to be a string or a StompFrame object. in

Related

Class 'MyDatabaseException' not found in /public_html/Connections/pdo.php on line 17

I'm not new to php but I'm unfamiliar with exceptions and OOP.
The problem here is that sometimes mysql doesn't load or loads after the web server. So I'm getting this fatal error:
PHP message: PHP Stack trace:
PHP message: PHP 1. {main}() /public_html/jpa.php:0
PHP message: PHP 2. require_once() /public_html/jpa.php:9
PHP message: PHP 3. require_once() /public_html/common/japan.php:9
PHP message: PHP 4. PDO->__construct('mysql:host=localhost;dbname=xxx;charset=utf8', 'xxx', 'xxx') /public_html/Connections/pdo.php:10
PHP message: PHP Fatal error: Class 'MyDatabaseException' not found in /public_html/Connections/pdo.php on line 17
Here is my code, copied directly from the PHP page.
<?php
try
{
$db = new PDO("mysql:host={$hostname_data_connect};dbname={$database_data_connect};charset=utf8", "{$username_data_connect}", "{$password_data_connect}");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch( PDOException $Exception )
{
// Note The Typecast To An Integer!
throw new MyDatabaseException( $Exception->getMessage( ) , (int)$Exception->getCode( ) );
}
What I would like to achieve is to return a 503 maintenance message or redirect the user to a custom 503 maintenance message page instead of throwing a fatal exception. The time mysql finishes loading.
I have no idea how to do that. Please help.
Or perform a php check to test whether mysqld is up and running before executing the code above. Again I have no idea how to do that.
A snippet of code would be greatly appreciated. Dealing with that error for 3 years now.
MyDatabaseException is not a pre-defined PHP class, it's just an example name of something that you might create yourself, like $myString or myFunction(). But you haven't created any such class. Instead of just re-throwing the exception, perform your desired action in the catch block:
try {
// some db stuff
} catch PDOException($e) {
// maybe dynamically generate a 503 page
header('HTTP/1.1 503 Service Unavailable');
// output page content here
exit();
// or redirect to an existing one
header('Location: http://your.domain/your/503/page');
exit;
}

Connect to SQLite using PHP - Cannot Connect

I'm trying to use PHP to connect to SQLite. I created a database by importing a CSV file into the tables for three tables. However, I'm unable to connect using the following code:
$dbhandle = sqlite_open('db/pokedex.db', 0666, $error);
if(!$dbhandle) die ($error);
This returns the following error:
Warning: sqlite_open() [function.sqlite-open]: file is encrypted or is not a database in /pokedex/configpokedexdb-sqlite.php on line 12
file is encrypted or is not a database
Googling told me I might have a version mismatch. Despite finding some SQLite3 mentions in my phpinfo(), I decided it might still be a problem so I tried the following suggested code:
try
{
//connect to SQLite database
$dbhandle = new PDO("sqlite:db/pokedex.db"); //sqlite:VPN0.sqlite
// echo "Handle has been created ...... <br><br>";
}
catch(PDOException $e)
{
echo $e->getMessage();
echo "<br><br>Database -- NOT -- loaded successfully .. ";
die( "<br><br>Query Closed !!! $error");
}
After which I received the following error:
Warning: sqlite_exec() expects parameter 1 to be resource, object given in /home/rawdco81/public_html/pokedex/index-sqlite.php on line 53
Before this, I tried running new PDO("sqlite:VPN0.sqlite"); which was what the site provided, but that was obviously wrong because it didn't point to my .db file at all. You'll see this piece of code in the comments beside the function call.
I'm having a hard time just connecting to the database...What is the proper way to do this?
Also, I'm running PHP Version 5.2.13.
EDITED: I pasted the wrong error message in the wrong place.
Now that I look more closely.., I think you are connecting successfully in the second code segment! You shouldn't be using sqlite_exec in tandem w/ PDO though; those are two different PHP interfaces into SQLite.
The reason the first bit of code bombed is because the legacy library doesn't support PDO v3. The second bit of code is bombing once you try to run sqlite_exec against the PDO object I presume.
I bet if you put a var_dump($dbhandle); after the try/catch you'll see you've got an initialized PDO object.
Just read up on using PDO to run queries and you should be golden!

mysql_query() expects parameter 2 to be resource error in connection with remote mysql DB

My PHP code works well in connecting remote windows system mysql database and returns the output. But, when I'm using the same to connect remote linux system's mysql database, I got the following error:
"mysql_query() expects parameter 2 to be resource, boolean given in
C:\wamp\www\mysqldb.php on line 88"
That line 88 have the following content "$this->resultQur =
mysql_query($query, $this->connID);"
Help me to solve this.
yes. The resource is null in this case. But the same works in windows mysql connection. I got the error only in linux. Need to do any change for linux environment?
While putting "print mysql_error();" i got the following error
"A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond."
The resource you're providing comes from a mysql_connect and that did not succeed!
Put error reporting on
Build some basic error handling in your script
Do not use mysql_* but mysqli_* or even better PDO with parameter binding
Output returned string from mysql_error() after your query. In that way you will see actual error.
$this->resultQur = mysql_query($query, $this->connID);
print mysql_error();
mysql_connect returns a resource on success, but a boolean "false" on error.
Your connection attempt probably failed an so the mysql_query won't be successful.
Try something like the following to see what exactly is causing the error.
mysql_connect(..) or die(mysql_error());
Additionally, it seems that the "old" mysql-library get's deprecated in PHP and it's recommended to switch to a more modern version, eg mysqli or PDO.
1 . Firstly put ini_set(‘display_errors’,1);error_reporting(E_ALL|E_STRICT); in your code at the start of the page
2 . Put Try catch around the query and print the Exception message
try { enter code here }catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
3 . Use PDO then the mysql object for query it's a modern and better approach
Use try catch around the the query and try

PHP Error handling in WordPress plugin

I am a newbie to both PHP and Wordpress (but do ok in C#), and am struggling to understand the error handling in a custom plugin I am attempting to write. The basics of the plugin is to query an exsiting MSSQL database (note its not the standard MYSQL db...) and return the rows back to the screen. This was working well, but the hosting provider has taken my database offline, which led me to the error handling problem (which I thought was ok).
The following code is failing to connect to the database (as expected), but puts an error onto the screen and stops the page processing. It does not even output the 'or die' error text.
QUESTION: How can I just output a simple "Cant load data" message, and continue on normally?
function generateData()
{
global $post;
if ("$post->post_title" == "Home")
{
try
{
$myServer = "<servername>";
$myUser = "<username>";
$myPass = "<password>";
$myDB = "<dbName>";
//connection to the database
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
or die("Couldn't open database $myDB");
//... query processing here...
}
catch (Exception $e)
{
echo "Cannot load data<br />";
}
}
return $content;
}
Error being generated: (line 31 is $dbhandle = mssql_connect...)
Warning: mssql_connect() [function.mssql-connect]: Unable to connect to server: <servername> in <file path> on line 31
Fatal error: Maximum execution time of 30 seconds exceeded in <file path> on line 31
First of all, if mssql_connect raises a warning when there's a problem, there is not much you can do to avoid it : the only thing you could do is hide it, using the # operator :
if (($dbhandle = #mssql_connect($myServer, $myUser, $myPass)) === false) {
// connection failed
}
Note : you should not die() when a connection error occurs : it'll stop the execution of the whole application, which is most certainly not desired.
The Fatal Error is a second problem (which is probably a consequence of the first one).
Note that you cannot recover from a Fatal Error : it is Fatal. Which means you must avoid it, one way or another.
Here, the error is that your script is working for more than max_execution_time seconds ; as the error is reported on the mssql_connect line, I suppose the script is waiting for the connection to succeed, and it doesn't get etablished in less that 30 seconds.
I don't have an SQL Server database to test, but looking at the Runtime Configuration section of the manual for mssql, I'd say that these look interesting :
name Default value
mssql.connect_timeout "5"
mssql.timeout "60"
You could try changing those,
either in your php.ini file, if you can modify it
or using ini_set() before trying to connect.
In the second case, something like this might do the trick :
ini_set('mssql.connect_timeout', '3');
ini_set('mssql.timeout', '3');
You may also want to look at WP_Error Class for handling your errors in an elegant manner. Note that this is a generic approach & that you will have to handle the particular error detection logic separately. WP_Error will help you in gathering all the errors in one place.

Occasional MySQL query Error in PHP

I have a php file that has to be loaded as a web page.
This page is 17Kb in size.
It has a php mysql query script inside.
the problem now, sometimes my mysql_query() lines gives an error.
When being refreshed, it works again.
It just have an error sometimes on that same line.
I check the query string and it was okay, for if that was the problem the error should happen all the time.
any idea?...
I was thinking maybe it was the file that has not been loaded completely.
And if that so, anyone to help me?... thanks.
You can use mysql_error() to get more details about the error that's currently occuring.
Just below the line that triggers the error, add:
echo mysql_error();
"Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource."
Sound like you have a problem with mysql connection. Try the the following code, after you called connect function, try to print out the error message.
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}

Categories