Jump to content

help with try() catch()


otuatail

Recommended Posts

Hi. I have never tred this before. mysql_connect() generates a visinle error even if i use or die()

 

What I have at the moment is

<?php
  $host = 'mysql5.streamline.net';
  $user = 'john';
  $pass = 'david';
  $data = 'james';

try 
{
  $link = mysql_connect($host, $user, $pass) or die("Houston we have problem");
$database = @mysql_select_db ($data, $link);
}

catch () 
{
echo "Caught exception: $link";
}
?>

 

any ideas on this. It would be better if I can get an error telling me if it was

mysql_connect() OR

mysql_select_db() that caused the error.

 

Desmond.

 

 

Link to comment
Share on other sites

try 
{

  if(!$link = mysql_connect($host, $user, $pass)) {
    throw new Exception("Can't connect to server: ".mysql_error());
  }
  if(!$database = mysql_select_db ($data, $link)) {
    throw new Exception("Can't select database: ".mysql_error());
  }
}

catch (Exception $e) 
{
echo "Caught exception: ". $e->getMessage();
}

Link to comment
Share on other sites

Hi. Sorry this dosn't work. Get this on a web page

 

Warning: mysql_connect() [function.mysql-connect]: Access denied for user: 'john@255.255.255.255' (Using password: YES) in /home/fhlinux190/d/des.co.uk/user/htdocs/errorhandeler2.php on line 9

Caught exception: Can't connect to server: Access denied for user: 'john@255.255.255.255' (Using password: YES)

 

This is what I want to stop. This would expose all my database information (I have changed the details here.

 

 

Link to comment
Share on other sites

Sorry this dosn't work.

 

No it did work that's what you are failing to see and your mysql credentials are wrong (cf "Access denied for user: 'john@255.255.255.255' (Using password: YES)") And if you don't want to expose your information set display_errors to Off on your production server.

 

Try this:

 

try
{
  if(!$link = mysql_connect($host, $user, $pass)) {
    throw new Exception("Can't connect to server: ".mysql_error());
  }
  if(!$database = mysql_select_db ($data, $link)) {
    throw new Exception("Can't select database: ".mysql_error());
  }
}

catch (Exception $e)
{
  error_log("Caught exception: ". $e->getMessage());
  include('404.html');
  exit(0);
}

Link to comment
Share on other sites

1. On production site you should have

error_reporting(0)

at the beginning of your script. This will stop

Warning: mysql_connect() [function.mysql-connect]:....
from appearing.

 

2. If you wan't to remove database information from Exception message, just remove mysql_error().

Link to comment
Share on other sites

ignace  My credentials are not wrong the way you see them. I changed the error messege to hide my details. They are not 255.255.255.255

 

With wrong username and password I get

 

<?php

try

{

$host = 'mysql5.streamline.net';

  $user = 'John';

  $pass = 'david';

  $data = 'james';

 

  if(!$link = @mysql_connect($host, $user, $pass));

{

  throw new Exception("Can't connect to server: $link");

}

if(!$database = mysql_select_db($data, $link));

  throw new Exception("Can't select database: ");

}

 

catch(Exception $e)

{

  echo "Caught exception: ". $e->getMessage();

}

?>

 

I get this  Caught exception: Can't connect to server:

 

with right username and password I still get an error

 

Caught exception: Can't connect to server: Resource id #1

Link to comment
Share on other sites

well, if you are connecting to the db from external hosting than the db hosting,

then you must set the db hosting to allow connection from the external hosting ip.

(so even if you use the right credentials you still can't connect to the db if you don't set it properly in the db hosting)

if the calling script and the db hosting is the same, you should just put localhost in the $host var

Link to comment
Share on other sites

does error_reporting(0) mean that i will be ignorant of any errors and spend weeks trying to find a problem. I want an error of my choosing so I can fix the error and nobody sees my details of the database.,

 

No. It means users won't see any error messages.

For debugging in development set up different error_reporting level.

 

Link to comment
Share on other sites

No riwan. The credentals are perfectly correct and have been for over 5 years. I cchanged the password on the database and without making the changes to my config.php file I got an error revealing all. Even though I had die('My message')

 

I still got the message on the end. What I wanted was to cleanly trap the connection error as it seemed a hi level erro and could not be prevented by the die() function. What I need is a way of trapping this error, re directing to an error page with a specific message and hopefully the page that was responsible for it. I can check out the site before going live but I have to take into consideration the unforseen error.

 

 

Link to comment
Share on other sites

Would this be a better way of dealing with this?

 

$old_error_handler = set_error_handler("myErrorHandler");

  if(!$link = @mysql_connect($host, $user, $pass))
    trigger_error('Can't connect to server:', E_USER_NOTICE);

function myErrorHandler($errno, $errstr, $errfile, $errline)
{
     case E_USER_NOTICE:
        // do something here and header(Location: );
        break;

}

Link to comment
Share on other sites

I said that because you said this before

I get this  Caught exception: Can't connect to server:

with right username and password I still get an error

Caught exception: Can't connect to server: Resource id #1

It would mean that you still can't connect to the db hosting.

I'm not sure why after you use try catch you still got that error.

In that case just as suggested, use error_reporting(0) to hide any system error

but still use the try catch to trap the error and redirect it to the correct error page.

 

 

 

 

Link to comment
Share on other sites

Not really. If anything, use set_error_handler to register error handler like this one:

 

<?php
function exception_error_handler($errno, $errstr, $errfile, $errline ) {
throw new ErrorException($errstr, 0, $errno, $errfile, $errline);
}

set_error_handler("exception_error_handler");

 

then your code can look like this:

 

<?php
define('APPLICATION_ENVIRONMENT', 'development');  //comment one or the other, to select application environment
//define('APPLICATION_ENVIRONMENT', 'production');

switch(APPLICATION_ENVIRONMENT) {
  case 'production':
    error_reporting(0);
    break;
  case 'development':
    error_reporting(E_ALL);
    break;
  default:
    die('Unknown application environment set!');
}


try {
  $link = mysql_connect($host, $user, $pass);
  $database = mysql_select_db ($data, $link);
} catch (ErrorException $e) {
  $error_reporting = error_reporting();   //get current error_reporting level
  if($error_reporting == 0) { //display no error messages
    //show some error message to user
    echo 'An error occured. Please contact admin at admin@site.com';
  } elseif ($error_reporting & E_ALL == E_ALL) { //display all error messages
    echo $e->getMessage();
  }
   //log $e->getMessage() to file[sup][/sup]
  //kill script
}

Link to comment
Share on other sites

They are not 255.255.255.255

 

I figured that much as it's a broadcast address.

 

@Mchl don't you mean ini_set('display_errors', 'Off'); for production instead of error_reporting(0) as setting the latter will mean not a single error is logged only display_errors dictates whether or not it should be published to screen.

 

$host = 'mysql5.streamline.net';

$user = 'John';

$pass = 'david';

 

See if you can login in to phpmyadmin using these details.

Link to comment
Share on other sites

igance: Could be as well. I just usually log exceptions using custom function in catch block, so error_reporting value isn't much more than an information wether I should display full stack trace, or just 'contact the admin'. I do it like that, mostly because it's easier to check error_reporting() ;)

Link to comment
Share on other sites

Ok this is sorted

 

function myErrorHandler($errno, $errstr, $errfile, $errline)

{

    switch ($errno) {

    case E_USER_ERROR:

    $_SESSION['MyError'] = "Gotcha: <br>$errstr<br>$errfile<br>$errline";

mailtoX('Error', $errstr,$_SESSION['MyError']);

$redirect = "Location: myerror.php";

      header($redirect);

      exit(0);

        break;

 

    case E_USER_WARNING:

        // echo "";

        break;

 

    case E_USER_NOTICE:

        // echo "";

        break;

 

    default:

        // echo "";

        break;

    }

    /* Don't execute PHP internal error handler */

    return true;

}

$old_error_handler = set_error_handler("myErrorHandler");

 

  if(!$link = @mysql_connect($host, $user, $pass))

    trigger_error('Can\'t connect to server: ('. $db . ')', E_USER_ERROR);

 

  if(!$database = @mysql_select_db($data, $link))

    trigger_error('Can\'t select database: (' . $db . ')', E_USER_ERROR);

 

I can now redirect to another page just saying sorry and I get an email giving me type of error webpage and line number.

 

Desmond.

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.