How to see LDAP errors generated from PHP - php

I'm trying to bind to a remote, third party LDAP server. I can connect/bind/search just fine from the command line on my server, but PHP just gives the monumentally unhelpful error: "Cannot connect to server".
I've seen where I can set the log level, but I don't know where those errors actually get logged to. Searching along the lines of "ldap [client] log location" returns results exclusively for ldap servers
How do I see the errors PHP generates when trying to bind?
If it matters, I'm using Debian.
Edit
Here's the relevant code:
public function auth($username,$password){
$ims_config = $this->di()->get('config')->ims;
$username = $this->filterUsername($username);
$this->conn = ldap_connect($ims_config->url);
if($this->conn){
$rdn = str_replace('?', $username, $ims_config->bind_rdn);
if(ldap_bind($this->conn,$rdn,$password)){
$this->isAuthed = TRUE;
}
}
return $this->isAuthed;
}
I have checked $ims_config->url and $rdn, and they are correct.

This is a pretty old question and the poster probably found the answer already, but for the sake of answering and completion, the PHP LDAP technote explains how you can do this using ldap_error($conn) and ldap_get_option($conn, LDAP_OPT_DIAGNOSTIC_MESSAGE, $err).

Related

ldap_connect() function in php accepts any value and doesnt throw an error

I am writing a php code to connect to my LDAP server.
$adServer = $ini['ldap'];
$ldap = ldap_connect($adServer) or die("Could not connect to {$adServer}");
The Value for $adServer I am fetching from a configuration file.
Looks like ldap_connect() is not throwing an error when I pass blank value or any other random value like "Hello".
I tried giving the below code to check if any error message was generated.
echo ldap_error($ldap)
It always says 'Success'.
Hence I am not able to authenticate if the connection was established or not to the LDAP Server and throw an appropriate error message.
In what situation does the 'die' get triggered for ldap_connect() function.
I would like to throw an appropriate error message to the end user if the Server Name provided in the configuration file is not working.
Note: I am using Version 5.6 for PHP
ldap_connect() always returns a resource when it can parse the provided parameter as a URL. The first time that resource is actually used (and therefore a connection is established and a possible failure can be detected) is when using ldap_bind().
As ldap_connect() almost always returns a resource-handle (as described in http://php.net/ldap_connect) your construct with die() wouldn't do what you want. It will only work if the provided parameter can't be parsed as URL internally. so as long as you provide a string that looks like a servername or a URL, everything works.
I always check after an unsuccessfull ldap_bind() what happened exactly and then throw an Exception depending on the error returned by . Alternatively I sometimes check before using the ldap_bind() by opening (and just closing) a connection using f.i fsockopen(). If that connection can't be opened the ldap-connection won't work either.
The examples on the referred php-documentation are missleading and it seems we will have to change them. So thanks for spotting and throwing up the question!
BTW: calling #ldap_connect('ldap:'); for instance would be such a case where the die() would work as it's an incomplete URL. Or using a string with whitespace.
I found a better way to do authenticate instead of using die.
After ldap connect, we would continue using ldap bind. If the bind fails, then we can check for the ldap error.
$ldap = #ldap_connect($adServer);
$bind = #ldap_bind ($ldap, $ldaprdn, $password);
if (!$bind) { // If Bind Failed then.
if (ldap_errno ($ldap) == 49 {
//Invalid Credentials
} else {
//LDAP Connection to LDAP Server Failed
}
}
For a list of all the LDAP Error Number, you can check here

Mysqli connection warning showing if connection details are bad

I have some code that allows a user to input details for their database on their server. After they submit the details, the code checks a connection to the database to see if valid details were entered. I want it to give outcomes of variables being true if the connection either works or does, like this:
$mysqli = new mysqli($_POST['dbHost'],$_POST['dbUser'],$_POST['dbPassword'],$_POST['dbName']);
if ($mysqli->connect_errno) { $badDetails = true; }
else { goodDetails = true; }
Problem is, if the details are indeed incorrect, it shows a PHP warning from the first line of the code above giving 'Unknown MySQL server host'.
What is the way around this? I don't want PHP throwing it's own visible error for this, I want to deal with the error myself.
You should not worry about visual errors. In a production environment, these should be turned off in the ini, and all errors should go to a log on the server instead of just to the screen.
This is configured with the display_errors setting and error_reporting()
Many frameworks override the PHP error handler with a custom implementation to display error in a pretty way, depending on their severity.
To achieve this, you can override the PHP error handler
As seen in the manual one can register custom handlers for regular errors and exceptions. And it is also possible to trigger an user defined error.
Just use a die()
$mysqli = new mysqli($_POST['dbHost'],$_POST['dbUser'],$_POST['dbPassword'],$_POST['dbName']) or die("Database Connection Failed");
A quick, dirty method would be error supression:
$con = #mysqli_connect( /* info */ );
Note that you should not keep this there, as this will suppress all errors, and mysqli can have multiple errors that you might need to know about.
Though I would check the host variable first, to see why the error is caused. You can also use die.
$con = mysqli_connect(/* info */) or die ("SQL Error!");
As far as where to look, try seeing that the host var is actually set and check it's value:
if (!isset($_POST['dbHost'])) {
echo "Host var not set!";
} else {
echo "Host var set: " . $_POST['dbHost']
}

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!

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.

How do I test for an Oracle connection

I'm trying to connect to an Oracle DB which is currently offline. When it's online it's not a problem, however, now that it's offline my program is getting hung up on the $connection = oci_connect() line and timing out. How do I simply check the connectio and bail out if it's not there?
Try this (fill in your ip and port):
if ( #fsockopen($db_ip,$db_port ) ) {
//connect to database
} else {
// didn't work
}
This gives you both a manual error, plus will return the actual error.
$connection = oci_connect() or die("Critical Error: Could not connect to database.\n\n". oci_error());
Make sure to test this as hopefully the Oracle error doesn't do something stupid like return the connection string (with your DB password) but I wouldn't assume until you see for yourself.
You could select null from dual.
OK, now I see what your asking, I think.
You want to know how to tell if a database is up before you connect to it?
You can use TNSPING to see if a database is up... ok, maybe that's not 100% accurate but it's a good indicator. go to a command prompt and type TNSPING and hit enter. So then you have to figure out how to call a command line tool from PHP.
Here is what I do in ASP.NET
Dim OracleConn As New OracleConnection(YOUR CONNECTION STRING HERE)
Try
OracleConn.Open()
OracleConn.Close()
Catch ex As Exception
Session("ErrorMessage") = "OracleConn: " & ex.Message
Response.Redirect("AccessDenied.aspx")
End Try
It doesnt necessarily say the DB is offline, but an exception will occur if the connection cannot be opened

Categories