IMPORTANT: Per accedir als fitxer de subversion: http://acacha.org/svn (sense password). Poc a poc s'aniran migrant els enllaços. Encara però funciona el subversion de la farga però no se sap fins quan... (usuari: prova i la paraula de pas 123456)

Molts dels exemples d'aquesta web els podeu trobar a:

http://www.iesebre.com/subversion/projectes/consultesLDAP/

Paquet php5-ldap

Aquest és el paquet que instal·la la llibreria de PHP per a Ldap:

$ sudo apt-get install php5-ldap

Els fitxers instal·lats són:

$ dpkg -L php5-ldap
/.
/usr
/usr/lib
/usr/lib/php5
/usr/lib/php5/20090626
/usr/lib/php5/20090626/ldap.so
/usr/share
/usr/share/doc
/etc
/etc/php5
/etc/php5/conf.d
/etc/php5/conf.d/ldap.ini
/usr/share/doc/php5-ldap

/etc/php5/conf.d/ldap.ini

Fitxer que activa el mòdul Ldap per a PHP:

$ cat /etc/php5/conf.d/ldap.ini
# configuration for php LDAP module
extension=ldap.so

Documentació /usr/share/doc/php5-ldap

$ ls -la /usr/share/doc/php5-ldap
lrwxrwxrwx 1 root root 11 2011-06-01 12:46 /usr/share/doc/php5-ldap -> php5-common
$ ls -la /usr/share/doc/php5-common/
total 420
drwxr-xr-x    3 root root   4096 2011-05-05 16:16 .
drwxr-xr-x 1475 root root  61440 2011-06-01 12:46 ..
-rw-r--r--    1 root root  50905 2011-05-03 00:52 changelog.Debian.gz
-rw-r--r--    1 root root  70803 2009-06-17 14:22 changelog.gz
-rw-r--r--    1 root root   4764 2007-07-19 01:10 CODING_STANDARDS.gz
-rw-r--r--    1 root root   7757 2011-05-03 01:19 copyright
-rw-r--r--    1 root root     91 2002-04-22 16:45 CREDITS
drwxr-xr-x    2 root root   4096 2011-05-05 16:16 examples
-rw-r--r--    1 root root   2462 2008-02-27 10:35 EXTENSIONS.gz
-rw-r--r--    1 root root    851 2011-05-03 00:52 NEWS.Debian.gz
-rw-r--r--    1 root root   2522 2007-07-13 01:44 README.CVS-RULES.gz
-rw-r--r--    1 root root   2849 2011-05-03 00:52 README.Debian.gz
-rw-r--r--    1 root root   1052 2011-05-03 00:52 README.Debian.security
-rw-r--r--    1 root root   3116 2003-06-29 18:07 README.EXT_SKEL.gz
-rw-r--r--    1 root root   2035 2004-08-25 00:01 README.PHP4-TO-PHP5-THIN-CHANGES.gz
-rw-r--r--    1 root root   2083 2002-10-23 23:35 README.SELF-CONTAINED-EXTENSIONS.gz
-rw-r--r--    1 root root   1943 2004-02-08 23:49 README.Zeus.gz
-rw-r--r--    1 root root 150503 2011-05-03 01:18 test-results.txt.gz
-rw-r--r--    1 root root    265 2011-05-03 00:52 TODO.Debian
-rw-r--r--    1 root root   2469 2007-05-02 01:04 TODO.gz

Funcions Ldap

A la web oficial de PHP:

Exemple bàsic

Bind amb usuari:

 <?php
 $ldapconfig['host'] = '192.168.0.8';
 #Només cal indicar el port si es diferent del port per defecte
 $ldapconfig['port'] = NULL;
 $ldapconfig['basedn'] = 'dc=iesebre,dc=com';
   
 $ds=ldap_connect($ldapconfig['host'], $ldapconfig['port']);
 
 ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
 
 $password="secret";
 $dn="cn=webfaltes,ou=people,ou=acls,dc=iesebre,dc=com";
 
 if ($bind=ldap_bind($ds, $dn, $password)) {
   echo("Login correct");
 } else {
   # Error
 }
 ?>

Bind anònim:

 <?php
 $ldapconfig['host'] = '192.168.0.8';
 #Només cal indicar el port si es diferent del port per defecte
 $ldapconfig['port'] = NULL;
 $ldapconfig['basedn'] = 'dc=iesebre,dc=com';
   
 $ds=ldap_connect($ldapconfig['host'], $ldapconfig['port']);
 
 ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
 
 $password="secret";
 $dn="cn=webfaltes,ou=people,ou=acls,dc=iesebre,dc=com";
 
 if ( $bind=ldap_bind($ds) ) {
   echo("Anonymous login correct");
 } else {
   # Error
 }
 ?>

SSL:

Exemples

Exemples de consulta ldap (Ldap search)

<?php
$ldapconfig['host'] = '192.168.0.8';
#Només cal indicar el port si es diferent del port per defecte
$ldapconfig['port'] = NULL;
$ldapconfig['basedn'] = 'dc=iesebre,dc=com';
  
$ds=ldap_connect($ldapconfig['host'], $ldapconfig['port']);

ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

$password="PARAULA DE PAS";
$dn="cn=admin,dc=iesebre,dc=com";

if ($bind=ldap_bind($ds, $dn, $password)) {
  echo("Login correct\n");
} else {
  # Error
}

echo "Searching for (sn=S*) ..."; 
    // Search surname entry 
    $sr=ldap_search($ds,"ou=All,dc=iesebre,dc=com", "sn=S*");   
    echo "Search result is ".$sr."<p>"; 

    echo "Number of entires returned is ".ldap_count_entries($ds,$sr)."<p>"; 

    echo "Getting entries ...<p>"; 
    $info = ldap_get_entries($ds, $sr); 
    echo "Data for ".$info["count"]." items returned:<p>"; 

    for ($i=0; $i<$info["count"]; $i++  ) { 
        echo "dn is: ". $info[$i]["dn"] ."\n"; 
        echo "first cn entry is: ". $info[$i]["cn"][0] ."\n"; 
        echo "first email entry is: ". $info[$i]["email"][0] ."\n"; 
    } 

    echo "Closing connection"; 
    ldap_close($ds); 
?>

Operador negatiu. Absència d'un atribut

<?php
$ldapconfig['host'] = '192.168.0.8';
#Només cal indicar el port si es diferent del port per defecte
$ldapconfig['port'] = NULL;
$ldapconfig['basedn'] = 'dc=iesebre,dc=com';
  
$ds=ldap_connect($ldapconfig['host'], $ldapconfig['port']);

ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

$password="";
$dn="cn=admin,dc=iesebre,dc=com";

if ($bind=ldap_bind($ds, $dn, $password)) {
  echo("Login correct\n");
} else {
  # Error
}

echo "Searching for (sn=S*) ..."; 
    // Search surname entry 
    $sr=ldap_search($ds,"ou=All,dc=iesebre,dc=com", "(!(jpegPhoto=*))");   
    echo "Search result is ".$sr."<p>"; 

    echo "Number of entries returned is ".ldap_count_entries($ds,$sr)."<p>"; 

    echo "Getting entries ...<p>"; 
    $info = ldap_get_entries($ds, $sr); 
    echo "Data for ".$info["count"]." items returned:<p>"; 

    for ($i=0; $i<$info["count"]; $i++  ) { 
        echo "dn is: ". $info[$i]["dn"] ."\n"; 
        echo "first cn entry is: ". $info[$i]["cn"][0] ."\n"; 
        echo "first email entry is: ". $info[$i]["email"][0] ."\n"; 
    } 

    echo "Closing connection"; 
    ldap_close($ds); 
?>

Afegir un objecte

<?php
#IMPORTANT: no poseu les paraules de pas a aquest fitxer:
include "/etc/paraulesdepas.php";


$ldapconfig['host'] = '192.168.0.8';
#Només cal indicar el port si es diferent del port per defecte
$ldapconfig['port'] = NULL;
$ldapconfig['basedn'] = 'dc=iesebre,dc=com';

$ds=ldap_connect($ldapconfig['host'], $ldapconfig['port']);

ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

$password=$PASSWD;
$dn="cn=admin,dc=iesebre,dc=com";

$basedn="ou=All,dc=iesebre,dc=com";
$basedn1="dc=iesebre,dc=com";

if ($bind=ldap_bind($ds, $dn, $password)) {
  echo("Login correct\n");
} else {
  # Error
}

$info['ou'] = "groups";
$info['objectclass'][0] = "top";
$info['objectclass'][1] = "organizationalUnit";

$addresult = ldap_add($ds, "ou=groups,ou=aborrar,ou=All,dc=iesebre,dc=com", $info);

if ($addresult) {
	echo "OK\n";
} else {
	echo "LDAP ERROR: ". ldap_error($ds) ."\n";
}
 

?>

Manipulació de fotos camp jpegPhoto

TODO

<?php
function mymodule_user($op, &$edit, &$account, $category = NULL) {
  if ($op == 'login' && module_exists('ldapauth')) {
    $attributes = _ldapauth_user_lookup($account->name);
    if (!empty($attributes['jpegphoto'][0])) {
      $ourFileName ="sites/default/files/pictures/" . $account->name . ".jpg";
      if ($ourFileHandle = fopen($ourFileName, 'w')) {
        fwrite($ourFileHandle, $attributes['jpegphoto'][0]);
        fclose($ourFileHandle);
        $picture = "sites/default/files/pictures/" . $account->name . ".jpg";
        user_save($account,  array('picture' =>  $picture),  'account');
      }
    }
  }
}
?>

Usuaris amb foto o sense foto

<?php
$ldapconfig['host'] = '192.168.0.8';
#Només cal indicar el port si es diferent del port per defecte
$ldapconfig['port'] = NULL;
$ldapconfig['basedn'] = 'dc=iesebre,dc=com';
  
$ds=ldap_connect($ldapconfig['host'], $ldapconfig['port']);

ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

$password="ie76pNCgxC3Ig";
$dn="cn=admin,dc=iesebre,dc=com";

if ($bind=ldap_bind($ds, $dn, $password)) {
  echo("Login correct\n");
} else {
  # Error
}

echo "Searching for (sn=S*) ..."; 
    // Search surname entry 
    $sr=ldap_search($ds,"ou=All,dc=iesebre,dc=com", "(&(objectclass=posixAccount)(!(jpegPhoto=*)))");   
    echo "Search result is ".$sr."<p>"; 

    echo "Number of entries returned is ".ldap_count_entries($ds,$sr)."<p>"; 

    echo "Getting entries ...<p>"; 
    $info = ldap_get_entries($ds, $sr); 
    echo "Data for ".$info["count"]." items returned:<p>"; 

    for ($i=0; $i<$info["count"]; $i++  ) { 
        echo "dn is: ". $info[$i]["dn"] ."\n"; 
        echo "i:"+$i."\n";
    } 

    echo "Closing connection"; 
    ldap_close($ds); 
?>

Canviar la paraula de pas

Ojo al Gosa! el gosa canvia la paraula de pas de Unix i la de Samba! Cal fer quelcom similar...

gosa --> functions,inc

function change_password ($dn, $password, $mode=0, $hash= "")
{
  global $config;
  $newpass= ""; 

  /* Convert to lower. Methods are lowercase */
  $hash= strtolower($hash); 

  // Get all available encryption Methods

  // NON STATIC CALL :)
  $methods = new passwordMethod(session::get('config'),$dn);
  $available = $methods->get_available_methods();

  // read current password entry for $dn, to detect the encryption Method
  $ldap       = $config->get_ldap_link();
 $ldap->cat ($dn, array("shadowLastChange", "userPassword", "uid"));
 $attrs      = $ldap->fetch ();

 /* Is ensure that clear passwords will stay clear */
 if($hash == "" && isset($attrs['userPassword'][0]) && !preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0])){
   $hash = "clear";
 }

 // Detect the encryption Method
 if ( (isset($attrs['userPassword'][0]) &&  preg_match ("/^{([^}]+)}(.+)/", $attrs['userPassword'][0], $matches)) ||  $hash != ""){

   /* Check for supported algorithm */
   mt_srand((double) microtime()*1000000);

   /* Extract used hash */
   if ($hash == ""){
     $test = passwordMethod::get_method($attrs['userPassword'][0],$dn);
   } else {
     $test = new $available[$hash]($config,$dn);
     $test->set_hash($hash);
   }

 } else {
   // User MD5 by default
   $test = new  $available['md5']($config, $dn);
 }

if($test instanceOf passwordMethod){

   $deactivated = $test->is_locked($config,$dn);
   /* Feed password backends with information */
   $test->dn= $dn;
   $test->attrs= $attrs;
   $newpass= $test->generate_hash($password);
   // Update shadow timestamp?
   if (isset($attrs["shadowLastChange"][0])){
     $shadow= (int)(date("U") / 86400);
   } else {
     $shadow= 0;
   }
   // Write back modified entry
   $ldap->cd($dn);
   $attrs= array();
   // Not for groups
   if ($mode == 0){
     // Create SMB Password
     $attrs= generate_smb_nt_hash($password);
     if ($shadow != 0){
       $attrs['shadowLastChange']= $shadow;
     }
   }
   $attrs['userPassword']= array();
   $attrs['userPassword']= $newpass;
   $ldap->modify($attrs);
   /* Read ! if user was deactivated */
   if($deactivated){
     $test->lock_account($config,$dn);
   }
   new log("modify","users/passwordMethod",$dn,array_keys($attrs),$ldap->get_error());
   if (!$ldap->success()) {
     msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $dn, LDAP_MOD, ERROR_DIALOG));
   } else {
     /* Run backend method for change/create */
     if(!$test->set_password($password)){
       return(FALSE);
     }
     /* Find postmodify entries for this class */
     $command= $config->search("password", "POSTMODIFY",array('menu'));
     if ($command != ""){
       /* Walk through attribute list */
       $command= preg_replace("/%userPassword/", $password, $command);
       $command= preg_replace("/%dn/", $dn, $command);
       if (check_command($command)){
         @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $command, "Execute");
         exec($command);
       } else {
         $message= sprintf(_("Command '%s', specified as POSTMODIFY for plugin '%s' doesn't seem to exist."), $command, "password");
         msg_dialog::display(_("Configuration error"), $message, ERROR_DIALOG);
       }
     }
   }
   return(TRUE);
 }
}

El propi usuaris s'ha de poder canviar la paraula de pas...


$new["userPassword"] = '{md5}' . base64_encode(pack('H*',
md5($newpass_in_plaintext)));
$this->result = ldap_modify($connection,
"uid=testuser,cn=users,dc=test,dc=net", $new);

Pujar una foto des d'un fitxer a Ldap (camp jpegPhoto)

http://www.iesebre.com/subversion/projectes/consultesLDAP/
<?php

#IMPORTANT: no poseu les paraules de pas a aquest fitxer:
include "/etc/paraulesdepas.php";


$ldapconfig['host'] = '192.168.0.8';
#Només cal indicar el port si es diferent del port per defecte
$ldapconfig['port'] = NULL;
$ldapconfig['basedn'] = 'dc=iesebre,dc=com';

$ds=ldap_connect($ldapconfig['host'], $ldapconfig['port']);

ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

$password=$PASSWD;
$dn="cn=admin,dc=iesebre,dc=com";

$basedn="ou=All,dc=iesebre,dc=com";

if ($bind=ldap_bind($ds, $dn, $password)) {
  echo("Login correct\n");
} else {
  # Error
}

$USERDN="cn=Tur AsAdmin Sergi,ou=people,ou=maninfo,ou=Personal,ou=All,dc=iesebre,dc=com";

$attrs=array();

if(class_exists('Imagick')){

	$im = new Imagick('/home/sergi/Escriptori/SergiTurGosa.jpeg');
	$im->setImageOpacity(1.0);
	//$im->resizeImage(147,200,Imagick::FILTER_UNDEFINED,0.5,TRUE);
	//$im->setCompressionQuality(90);
	$im->setImageFormat('jpeg'); 
	$attrs['jpegphoto']=$im->getImageBlob();

} else {
	echo "ERROR!";
}
$ret1=ldap_mod_add($ds,$USERDN,$attrs);	
	
if (!$ret1) {
	echo "Error at ldap_mod_add: $ret1\n";
}

?>

Pujar fotos d'un directori i subdirectoris a Ldap/Gosa

http://www.iesebre.com/subversion/projectes/consultesLDAP/
<?php

#IMPORTANT: no poseu les paraules de pas a aquest fitxer:
include "/etc/paraulesdepas.php";


$ldapconfig['host'] = '192.168.0.8';
#Només cal indicar el port si es diferent del port per defecte
$ldapconfig['port'] = NULL;
$ldapconfig['basedn'] = 'dc=iesebre,dc=com';

$ds=ldap_connect($ldapconfig['host'], $ldapconfig['port']);

ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

$password=$PASSWD;
$dn="cn=admin,dc=iesebre,dc=com";

$basedn="ou=All,dc=iesebre,dc=com";

if ($bind=ldap_bind($ds, $dn, $password)) {
  echo("Login correct\n");
} else {
  # Error
}


$dnis=array();


function getDirectory( $path = '.', $level = 0 ) {

    $ignore = array( 'cgi-bin', '.', '..' );
    
    // Directories to ignore when listing output. Many hosts
    // will deny PHP access to the cgi-bin.

    $dh = @opendir( $path );
    // Open the directory to the handle $dh
    
    while( false !== ( $file = readdir( $dh ) ) ){
    // Loop through the directory
    
        if( !in_array( $file, $ignore ) ){
        // Check that this file is not to be ignored
            
            str_repeat( ' ', ( $level * 4 ) );
            // Just to add spacing to the list, to better
            // show the directory tree.
            
            if( is_dir( "$path/$file" ) ){
            // Its a directory, so we need to keep reading down...
            
                echo "$path/$file;";
                getDirectory( "$path/$file", ($level+1) );
                // Re-call this same function but on a new directory.
                // this is what makes function recursive.
            
            } else {
                echo "$path/$file;";
                // Just print out the filename
            
            }
        
        }
    
    }
    
    closedir( $dh );
    // Close the directory handle

}

ob_start();
getDirectory( "/home/sergi/prova/TIC2011-12" );

$files = ob_get_contents();
ob_end_clean();

//echo $files."\n\n\n\n\n\n";

$files_a=split(";",$files);
$files_a_filtered = preg_grep("/^.*\.(png)$/i", $files_a);

//DEBUG
//print_r($files_a);
//print_r($fl_array);
/*
foreach ($files_a_filtered as $filea) {
	echo $filea."\n";
}
exit;
* */

foreach ($files_a_filtered as $file) {
    echo $file."\n";
    //echo basename($file,".png")."\n";
    
    
    //Search Ldap object with this DNI
    echo "Searching DNI: " . basename($file,".png") . "..."; 
    
    // Search surname entry 
    $filter="(irisPersonalUniqueID=".basename($file,".png").")";
    $sr=ldap_search($ds,$basedn, $filter);   
    
    $found=ldap_count_entries($ds,$sr); 
    
	switch ($found) {
		case 0:
			echo "DNI NOT FOUND! $file\n";
			break;
		case 1:
			//Comprovar si existeix el camp jpegPhoto
			$info = ldap_get_entries($ds, $sr); 
			//echo "Data for ".$info["count"]." items returned:<p>"; 
			echo " dn is: ". $info[0]["dn"] . " "; 
			//echo "array: ". print_r($info[0]) ."\n"; 
			if (in_array("jpegphoto", $info[0])) {
				echo "PHOTO OK!\n";
			} else {
				echo "PHOTO NOT FOUND! Adding photo... ";
				
				if(class_exists('Imagick')){
					$im = new Imagick($file);
					$im->setImageOpacity(1.0);
					//$im->resizeImage(147,200,Imagick::FILTER_UNDEFINED,0.5,TRUE);
					//$im->setCompressionQuality(90);
					$im->setImageFormat('jpeg'); 
					$attrs['jpegphoto']=$im->getImageBlob();
				} else {
					echo "ERROR!";
				}
				
				$ret1=ldap_mod_add($ds,$info[0]["dn"],$attrs);	
				if ($ret1) {
					echo "PHOTO CORRECTLY ADDED: $ret1\n";
				} else {
					echo "Error adding photo: $ret1" . ldap_error($ds) . " \n";
				}
				
			}
				
			/*
			for ($i=0; $i<$info["count"]; $i++  ) { 
				echo "dn is: ". $info[$i]["dn"] ."\n"; 
				echo "i:"+$i."\n";
			} *
			*/
			break;
		default:
			echo "MULTIPLE RESULTS FOUND! $file\n";
			break;
	}


/*
    echo "Getting entries ...<p>"; 
    $info = ldap_get_entries($ds, $sr); 
    echo "Data for ".$info["count"]." items returned:<p>"; 

    for ($i=0; $i<$info["count"]; $i++  ) { 
        echo "dn is: ". $info[$i]["dn"] ."\n"; 
        echo "i:"+$i."\n";
    } 
*/
}


echo "Closing connection"; 
ldap_close($ds); 


?>

Baixar fotos d'un directori Ldap

L'última versió del fitxer la trobareu a:

http://www.iesebre.com/subversion/projectes/consultesLDAP/downloadPhotos.php

NOTA: Aquest script pot ser molt útil per tal de passar fotos de Ldap a Moodle. Consulteu

<?php

#IMPORTANT: no poseu les paraules de pas a aquest fitxer:
include "/etc/paraulesdepas.php";

$destinationDIR=getcwd()."/moodlePhotos";

echo "CURRENT DIRECTORY: " . getcwd() . "\n";

echo "Generating destination directory...\n";

mkdir($destinationDIR);



$ldapconfig['host'] = '192.168.0.8';
#Només cal indicar el port si es diferent del port per defecte
$ldapconfig['port'] = NULL;
$ldapconfig['basedn'] = 'dc=iesebre,dc=com';

$ds=ldap_connect($ldapconfig['host'], $ldapconfig['port']);

ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

$password=$PASSWD;
$dn="cn=admin,dc=iesebre,dc=com";

$basedn="ou=All,dc=iesebre,dc=com";

if ($bind=ldap_bind($ds, $dn, $password)) {
  echo("Login correct\n");
} else {
  # Error
}

//Obtain all users

//Search al Accounts with jpegPhotos
$filter="(jpegphoto=*)";
$sr=ldap_search($ds,$basedn, $filter);   

$totalUsers=ldap_count_entries($ds,$sr); 

echo "Usuaris totals:".$totalUsers."\n";

$info = ldap_get_entries($ds, $sr); 

echo "Data for ".$info["count"]." items returned:<p>"; 

for ($i=0; $i<$info["count"]; $i++  ) { 
	$uid= $info[$i]["uid"][0];
	$jpegphoto= $info[$i]["jpegphoto"][0];
	echo "i: "+$i . "|". $info[$i]["dn"] . " uid: " . $uid . "\n"; 


	if(class_exists('Imagick')){

	$im = new Imagick();
	$im->readImageBlob($jpegphoto);
	$im->setImageOpacity(1.0);
	//$im->resizeImage(147,200,Imagick::FILTER_UNDEFINED,0.5,TRUE);
	//$im->setCompressionQuality(90);
	$im->setImageFormat('jpeg'); 
	
	$destinationfilename=$destinationDIR."/".$uid .".jpg";
	echo "Creating file $destinationfilename...\n";
	$im->writeImage ($destinationfilename);

} else {
	echo "ERROR!";
}

} 


/*
$USERDN="cn=Tur AsAdmin Sergi,ou=people,ou=maninfo,ou=Personal,ou=All,dc=iesebre,dc=com";

$attrs=array();

if(class_exists('Imagick')){

	$im = new Imagick('/home/sergi/Escriptori/SergiTurGosa.jpeg');
	$im->setImageOpacity(1.0);
	//$im->resizeImage(147,200,Imagick::FILTER_UNDEFINED,0.5,TRUE);
	//$im->setCompressionQuality(90);
	$im->setImageFormat('jpeg'); 
	$attrs['jpegphoto']=$im->getImageBlob();

} else {
	echo "ERROR!";
}
$ret1=ldap_mod_add($ds,$USERDN,$attrs);	
	
if (!$ret1) {
	echo "Error at ldap_mod_add: $ret1\n";
}*/

?>

Moure un objecte Ldap

<?php
#IMPORTANT: no poseu les paraules de pas a aquest fitxer:
include "/etc/paraulesdepas.php";


$ldapconfig['host'] = '192.168.0.8';
#Només cal indicar el port si es diferent del port per defecte
$ldapconfig['port'] = NULL;
$ldapconfig['basedn'] = 'dc=iesebre,dc=com';

$ds=ldap_connect($ldapconfig['host'], $ldapconfig['port']);

ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

$password=$PASSWD;
$dn="cn=admin,dc=iesebre,dc=com";

$basedn="ou=All,dc=iesebre,dc=com";
$basedn1="dc=iesebre,dc=com";

if ($bind=ldap_bind($ds, $dn, $password)) {
  echo("Login correct\n");
} else {
  # Error
}

$dn="cn=albertmestres,ou=groups,ou=Informàtica,ou=Alumnes,ou=All,ou=201011,dc=iesebre,dc=com";
$newrdn="cn=albertmestres";
$newparent="ou=201011,dc=iesebre,dc=com";

$result= ldap_rename ( $ds , $dn , $newrdn , $newparent , TRUE );

if ($result) {
	echo "OK\n";
} else {
	echo "ERROR\n";
}
?>


Resol·lució de problemes

Protocol error fer el binding

Cal indicar que es vol utilitzar la versió 3 del protocol:

$ldapconfig['host'] = '192.168.0.8';
#Només cal indicar el port si es diferent del port per defecte
$ldapconfig['port'] = NULL;
$ldapconfig['basedn'] = 'dc=iesebre,dc=com'; 
$ds=ldap_connect($ldapconfig['host'], $ldapconfig['port']);

ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);

Vegeu també

Enllaços externs