Retrieve Distributions lists from Active Directory with LDAP / PHP - php

I have an LDAP annuary working on Active Directory (Win Server 2008). I try to connect to this AD with PHP (and LDAP lib) and retrieve all distributions lists from a specific OU.
The connection and authentication is working, but when I want to retrieve the lists from OU, I dont have any results (rights are OK and in local it's working too, without PHP)
Here is my code :
$ldap_host = "ip.add.re.ss";
$ldap_dn = "OU=Listes,DC=domain,DC=tld"; // all there infos are ok
$base_dn = "DC=domain,DC=tld";
$ldap = ldap_connect($ldap_host);
$user = 'username'; $password = '';
$filter="(sAMAccountName=recette)";
$filter="(&(objectClass=user)(objectCategory=person)(OU=Lists))";
ldap_set_option($ldap, LDAP_OPT_PROTOCOL_VERSION,3);
ldap_set_option($ldap, LDAP_OPT_REFERRALS,0);
ldap_bind($ldap, $user, $password);
$results = ldap_search($ldap,$base_dn, $filter);
$member_list = ldap_get_entries($ldap, $results);
If I delete the OU=Lists, it's working, I have results, but the one I want. Then, when I add the OU=Lists, I don't have any results.
Can you help me please? Thanks.

You said you are trying to "Retrieve Distributions lists" and yet your LDAP filter is to retrieve users which have the attribute ou=Lists:
(&(objectClass=user)(objectCategory=person)(OU=Lists))
Try an LDAP filter as:
(&(objectCategory=Group)(proxyAddresses=*))
more like these are at:
http://ldapwiki.com/wiki/Active%20Directory%20Group%20Related%20Searches

Related

Connect to MySQL database in PHP

I'm trying to build a blog website.
It is deployed on Heroku and it is supposed to connect to a MySQL database. The info required to login to my database is stored in an environment variable on Heroku, and looks like this (These are fake credentials of course):
mysql://g46w916ds134b8:639f463e#us-cdbr-east-03.cleardb.net/heroku_45fab1d19h35yetf?reconnect=true
It contains the DB name, the user, the password and the host.
Is there a way to use this one string directly in my PHP code to connect to the database? I checked MySQLi and PDO documentation, and it seems like they only accept DSN/user/password or Host/user/password/DBname format.
This is a url after all, so you can use parse_url function to extract data.
// Connection string from environmental variable in heroku
$connectionStringHerokuEnv = 'mysql://g46w916ds134b8:639f463e#us-cdbr-east-03.cleardb.net/heroku_45fab1d19h35yetf?reconnect=true';
$parsed = parse_url($connectionStringHerokuEnv);
$dbname = ltrim($parsed['path']. '/'); // PATH has prepended / at the beginning, it needs to be removed
// Connecting to the database
$conn = new PDO("{$parsed['scheme']}:host={$parsed};$dbname={$dbname};charset=utf8mb4", $parsed['user'], $parsed['pass'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
For database connection you should always use PDO and not mysqli driver. PDO allows you to connect to almost any database, without rewriting code in 85% of cases.
dont forget options [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION], this will allow you to catch any errors and handle them accordingly to application needs.
PDO accept this connection string driver: host=DATABASE_HOST;dbname=DATABASE_NAME; charset=DEFAULT_CHARSET(use utf8 whenever you can)
Learn more on parse_url: https://www.php.net/manual/en/function.parse-url
Learn more on PDO:
https://www.php.net/manual/en/class.pdo.php
<?php
$str = "mysql://g46w916ds134b8:639f463e#us-cdbr-east-03.cleardb.net/heroku_45fab1d19h35yetf?reconnect=true";
// If I correctly understanded 'mysql://login:passwd#host/dbname?some_params'
// data parsing from input string
$sp = explode('/', $str);
$sp1 = explode('#', $sp[2]);
$first_part_sp = explode(':', $sp1[0]);
$login = $first_part_sp[0];
$passwd = $first_part_sp[1];
$host = $sp1[1];
$dbname = explode('?', $sp[3])[0];
$connect_str = "mysql:host=$host;dbname=$dbname";
echo $connect_str." ".$login." ".$passwd;
// database access
$pdo = new PDO($connect_str, $user, $passwd);
?>

How to Get the GidNumber of a User in LDAP PHP

Stuck with this Code. I need to get the GidNumber of a particular user using PHP. Please help me in this. I have switched to get GIdNumber instead of getting MemberOf function since it is not working. Thanks in Advance.
<?php
session_start();
$ldaphost ="ldap://(hostaddress)";
$ldapport = 389;
$ds = ldap_connect($ldaphost, $ldapport)
or die("Could not connect to $ldaphost");
$person="comp1";
$dn = "ou=Users,dc=compldap,dc=com";
$filter="(|(sn=$person*)(givenName=$person*))";
$justthese = array("gidNumber");
$sr=ldap_search($ds, $dn, $filter, $justthese);
$info = ldap_get_entries($ds, $sr);
echo "ENTRY RESULTS: ";
print_r($info[0]['gidNumber']);
echo "<br />";
?>
The filter seems odd to me, try :
$filter="(|(sn=".$person."*)(givenName=".$person."*))";
Also, the gitNumber should be indexed like this :
print_r($info[0]['gidnumber'][0]);
Try also to check how many entries your search returned :
echo $info["count"]." entries returned\n";
EDIT :
Strangely enough I did not see that you never bind to the server before doing your search ... :
See : http://php.net/manual/fr/function.ldap-bind.php

Library List is not being used in remote PHP DB2 connection to IBM i

I've successfully connected to a remote IBM i DB2 database (AS400) from my local Windows PC via PHP. I'm using the IBM Data Server Client in conjunction with the db2_* functions in PHP. The problem I'm having is that despite my library list being set properly, it is not being used for unqualified table names. Instead it uses the current user name as the library. However, when I qualify the table names everything works like a charm.
I've confirmed that my library list is actually changing when I create the connection by querying QSYS2.LIBRARY_LIST_INFO.
$database = '<database name>';
$user = '<user name>';
$password = '<password';
$port = <port>;
$options['i5_naming'] = DB2_I5_NAMING_ON;
$options['autocommit'] = DB2_AUTOCOMMIT_OFF;
$options['i5_libl'] = 'MYLIB YOURLIB ANYLIB';
$conn = db2_connect($database, $user, $password, $options);
if ($conn) {
echo "Connection succeeded."; //It succeeds
}
else {
echo db2_conn_error()." | ".db2_conn_errormsg()."<br />";
echo "Connection failed.";
}
$sql = "SELECT * FROM QSYS2.LIBRARY_LIST_INFO";
//Works and proves my library list reflects
//what I passed in when creating the connection.
//$sql = "SELECT * FROM LIBRARY_LIST_INFO";
//Generates: "42S02 : [IBM][CLI Driver][AS] SQL0204N "<user name>.LIBRARY_LIST_INFO" is an undefined name. SQLSTATE=42704 SQLCODE=-204"
//where <user name> is the username used to connect to the DB.
//It should be using the library list specified when creating the connection though.
//This holds true for any table from any library including those specified
//when creating the connection (which includes QSYS2).
$stmt = db2_prepare($conn, $sql);
$result = db2_execute($stmt);
if($result){
while($row = db2_fetch_assoc($stmt)){
echo "<pre>";
var_dump($row); //In addition to entries for QSYS, QSYS2, QUSRSYS and QHLPSYS I get entries for MYLIB, YOURLIB and ANYLIB.
echo "</pre>";
}
}else{
echo "failed<br />";
echo db2_stmt_error()." : ".db2_stmt_errormsg()."<br />";
}
Has anyone ever run into this while enabling i5_naming when connecting to a remote DB2 server? I'm not really sure why it wouldn't be using my library list as the PHP manual states "Unqualified files are resolved using the library list for the job." when enabled. http://php.net/manual/en/function.db2-connect.php
I finally solved this after opening a PMR with IBM. All I had to do was apply the latest Fix Pack for DB2 Connect Personal Edition.
Suggested Fix Packs for DB2 Connect:
http://www-01.ibm.com/support/docview.wss?rs=71&uid=swg21321001
Basically the DB2 Connect version I had was released prior to 2013. It was in 2013 IBM added two tier support by adding the i5_naming option. So my DB2 Connect setup was effectively ignoring the option I was passing. So that explains why the other options still went through. On the DB side, since it didn't receive a value for i5_naming - it remained as the default.

Why won't my JSON array query work?

Can anyone see what the problem with my code is / where im going wrong?
I know i have the correct host,database,user and password.
This is the code in the php file, it should get all the details available on the players from my sql database, however if i go on the page it just gives me a white page. Im using go daddy as a host and my database is also on there.
Any ideas? thanks
<?php
$host = "abc12345"; //Your database host server
$db = "abc12345"; //Your database name
$user = "abc12345"; //Your database user
$pass = "abc12345"; //Your password
$connection = mysql_connect($host, $user, $pass);
//Check to see if we can connect to the server
if (!$connection) {
die("Database server connection failed.");
} else {
//Attempt to select the database
$dbconnect = mysql_select_db($db, $connection);
//Check to see if we could select the database
if (!$dbconnect) {
die("Unable to connect to the specified database!");
} else {
$query = "SELECT * FROM Player";
$resultset = mysql_query($query);
$records = array();
//Loop through all our records and add them to our array
while ($r = mysql_fetch_assoc($resultset)) {
$records[] = $r;
}
//Output the data as JSON
echo json_encode($records);
}
}
?>
The script is all right, I checked it with a different query.
Assuming that the table Player is not empty, the error can be either with your raw sql query (as pointed by #Sharikov in comments), otherwise the error is with the way you have configured your godaddy server.
For debugging that, I would suggest inserting dummy print_r or echo statements before you execute the query, and going through your apache logs at /var/log/apache2/access.log.
Also make sure that you don't have any core php package missing on your server (like php5-mysql if you use mysql).

Server is unwilling to perform. LDAP in PHP

I get this error always
Server is unwilling to perform
and my code is the next:
echo "Checking ...";
$username = $_POST["username"];
$passwd = $_POST["passwd"];
$host = 'myhost.co.uk';
$port = 389;
$dn = 'uid='.$username.',cn=nssproxy,ou=users,dc=co,dc=uk';
// conexion a ldap
$conn = ldap_connect( "ldap://".$host.":389") ;
ldap_set_option($conn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($conn, LDAP_OPT_REFERRALS, 0);
// match de usuario y password
$bind = ldap_bind( $conn, $dn, $password );
if ($bind){
echo "OK";
}
else {
echo "NO OK";
}
echo ldap_error($conn);
Why I have this error? I'm always testing with any user, this script return same error.
Thanks in advance.
So I searched Google for Server is unwilling to performand the first result says:
C.1.4. ldap_*: server is unwilling to perform
slapd will return an unwilling to perform error if the backend holding the target entry does not support the given operation.
The password backend is only willing to perform searches. It will return an unwilling to perform error for all other operations.
The shell backend is configurable and may support a limited subset of operations. Check for other errors indicating a shortage of resources required by the directory server. i.e. you may have a full disk etc
ldap_mod_replace() [function.ldap-mod-replace]: Modify: Server is unwilling to perform has some requirements as well
One possibility is what I did... I misconfigured /etc/ldap.conf, and added binddn where I meant to put rootbinddn, and that caused this message.
I had this error. Ldap on virtual machine on windows server 2019 on 10.0.0.14 IP.
I managed to connect and bind successfuly, but this error occurs when ldap_add().
My solution was to check $record array parameters that i want to save.
I this set of properties work for me:
$r = ldap_add($this->LdapConn, 'CN=user 3,'.$this->Branch, array(
'cn' => 'user 3',
'name' => 'test',
'sn' => 'asd',
'instanceType' => '4',
'objectCategory'=> 'CN=Person,CN=Schema,CN=Configuration,DC=test-domain,DC=com',
'mail' => 'mai222222l#mail2.com',
'objectclass'=>array(
'top',
'user',
'person',
'organizationalPerson'
)
));
Note that ldap_add() second parameter is path (dn) to entry and this can cause problem.
Path(dn) must be current branch + entry
For me current branch was 'CN=Users,DC=test-domain,DC=com' and full path mean dn = "CN=user 3,CN=Users,DC=test-domain,DC=com"
Note that this first part cn=user 3 must be the same as in bellow array.
My distinguish names (dc) was incorrect.

Categories