Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Sample Active Directory command line php script

Here is a sample Active Directory php script that you can user for debugging and testing your configuration

Login in your host, save the php script below, give it a name, e.g. "ad_test.php" and change the following variables at the beginning to match your configuration:

$basedn = "DC=domain,DC=company,DC=com";
$ldapuser = 'username@domain.company.com';
$ldappass = "yoursupersecretpass";
$ldapserver = "ldap.domain.company.com";
$ldapport = 389; // 389 is the default port number for AD servers
$uid = "username"; // uid to search for

Then run the script:
user@host:~/tests$ php ad_test.php

Easy XML and RSS integration in PHP


This post shows how to get XML and/or RSS data from external sites to our site using PHP.
Using this method we could integrate various PHP based CMS's like Drupal, Joomla, Wordpress with external XML feeds.

Getting external RSS feeds

Now consider for example, that you want to get the first two news items from the BBC RSS news feed.
You can do this very easily and quickly using the following piece of code:

Useful linux localization related commands

Below you can find some linux localization related commands

Set local timezone

dpkg-reconfigure tzdata


Restart all deamons (or reboot)
Check: /etc/timezone


Display all localization settings, eg: locale
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_ALL=


MySQL Transactions in PHP

Error handling transactions in PHP


Transactions are very crucial for maintaining the integrity of our data. Web applications often ignore transactional integrity which can be very dangerous.

A common problem is when we need to perform two or more inserts in one operation. If we don't use transactions, then only some of them will be inserted which will bring a complete chaos in our database.

Debugging LDAP php scripts

Sometimes trying to find out what's wrong when you try to connect to an LDAP from your php scripts and programs can be very hard.

Here is one of the most important commands which you can use in order to troubleshoot your ldap connections.

How to connect to an SSL OpenLdap

After a lot of troubleshooting I managed to connect to an ssl OpenLdap and I would like to share this information with you.

Some of the problems that you may encounter are:

Ldap host.

Verify, using ping if you have access to the ldap server.

I suggest you try both, IP and hostname. In some configurations the dns name of the ldap host is working fine, but sometimes it doesn't. So try both in case you have problems.

SSL specific problems

For php, try
ldap_connect("ldaps://host", port)
ldap_connect("ldaps://host:port")

If the host you are using to invoke the scripts does not have a ssl certificate installed then you have to add the following line to your ldap.conf:
TLS_REQCERT     never

Sample php script

Here is a sample script to connect to a secured OpenLdap. Also the script assumes that you DON'T have anonymous access to the LDAP server. In case you do have, then just do a bind with no credentials.
You must change the parameters in the beginning of the script in order to match your organization's OpenLdap configuration.


<?php
// Set the parameters below to fit your organization's openldap
$basedn = "DC=example,DC=com";
$login = "user";
$ldapuser = "uid=$login,ou=people,dc=example,dc=com";
$ldappass = "pass";
$filter = "(uid=$login)";
$ldapurl = "ldaps://ldap.example.com:XXX"; 
$LDAPFieldsToFind = array("cn", "mail");
$debug = false;

// Set debugging
if ($debug) {
  ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);
}

// connect to ldap server
$ldapconn = ldap_connect($ldapurl) or die ("Couldn't connect");

// binding to ldap server
echo "Trying to bind with $ldapuser - $ldappass\n";
$ldapbind = @ldap_bind($ldapconn, $ldapuser, $ldappass);

if (!$ldapbind) {
  echo "Unable to bind to server $ldapurl\n";
  echo "OpenLdap error message: " . ldap_error($ldapconn) . "\n";
  exit;
}

echo "Bind succesfull\n";
echo "\nSearching in base_dn $basedn - filter: $filter\n";    
$userdetails = ldap_search($ldapconn, $basedn, $filter, $LDAPFieldsToFind);
$info = ldap_get_entries($ldapconn, $userdetails);

for ($x=0; $x<$info["count"]; $x++) {
$email=$info[$x]['mail'][0];
$nam=$info[$x]['cn'][0];
  print "\n\nOpenLdap attributes:\n";
  print "CN is: $nam \n";
  print "Mail is: $email\n";
}
  
if ($x==0) { echo "\nOops, was not found. Please try again."; }

?>

How-to: Execute any linux script using mail

The following guide will show you how to execute a php or any other command line program by sending mail to a specific mail address.

This can be used for many applications. For example say that we want to create a new trouble ticket to our organisation's central ticket/issue management system.

The first step is to create and test the script.
<?php
/*
 * newticket.php
 */
error_reporting(E_ALL);

$user="root";
$password="XXX";
$database="tests";

echo "Connecting...\n";

mysql_connect("localhost",$user,$password);
mysql_select_db($database) or die( "Unable to select database");
$dt = date("F j, Y, g:i a s");
$query="insert ticket (description) values (\"$dt\")";
mysql_query($query) or die(mysql_error());
mysql_close();
?>

This scripts assumes that you have the table ticket created in a mysql database called tests:
CREATE TABLE IF NOT EXISTS `ticket` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `description` varchar(50) NOT NULL,
  PRIMARY KEY (`id`)
)

If you place it for example in /var/www then you can test the php script from the command line using:
php -q /var/www/newticket.php

If everything is OK, this script will insert one row in table ticket with its field description set as the current datetime.

Now, if you don't already have one, you need to install a mail server. In this example I used postfix. So for debian/ubuntu just type:
sudo aptitude install postfix

Postfix doesn't allow by default mail aliases to execute commands. In order to enable this you have to configure postfix for this by adding the following lines of the file main.cf which is located at /etc/postfix. Edit the file with:
sudo vi /etc/postfix/main.cf

And then add the attributes allow_mail_to_commands and allow_mail_to_files:
allow_mail_to_commands = alias,forward,include
allow_mail_to_files = alias,forward,include

Then we need to edit the /etc/aliases in order to add the mail alias that will execute the script we just created:

# See man 5 aliases for format
postmaster:    root
newticket: "| php -q /var/www/newticket.php" 

Now we have to refresh the aliases used by sendmail by executing the command (rebuilds the data base for the mail aliases file.
sudo newaliases

Finally test the alias just created by running the sendmail like this:
user@host:/var/www$ sendmail newticket
.

Don't forget the "." which marks the end of the message body and tells sendmail to actually send the mail.
Now check your database. If everything went fine, you should have a new row inserted in your ticket table.
If not, then you have to do some troubleshooting by running the mailq program to check your mail queue.

Beware of the case sensitivity in php and LDAP/AD connections!

Ok, things do not behave always as they should!
One of those frustrations is case sensitivity when you try use ldap queries from php code.
Consider the following example:
<?php
$ldapuser = "user";
$ldappass = "pass";
$basedn = "OU=People,DC=staff,DC=company,DC=com";
$domain = "staff.company.com";
$ldaphost = "ldap.staff.company.com";
$filter="(&(objectclass=person)(sAMAccountName=$ldapuser))";
$LDAPFieldsToFind = array("cn", "mail", "sAMAccountName");

// connect to ldap server
$ldapconn = ldap_connect($ldaphost);

// Setting Active Directory
ldap_set_option($ldapconn, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldapconn, LDAP_OPT_REFERRALS, 0);

// binding to ldap server
$ldapbind = @ldap_bind($ldapconn, "{$ldapuser}@{$domain}", $ldappass);
echo "\nSearching in base_dn $basedn - filter: $filter\n";
$userdetails = ldap_search($ldapconn, $basedn, $filter, $LDAPFieldsToFind);
$info = ldap_get_entries($ldapconn, $userdetails);

  for ($x=0; $x<$info["count"]; $x++) {
    $email=$info[$x]['mail'][0];
    $nam=$info[$x]['cn'][0];
    $samaccountname=$info[$x]["sAMAccountName"][0];
      print "\nCN is: $nam \n";
      print "Mail is: $email\n";
      print "Uid: $samaccountname\n";
  }
?>

Although the above piece of code is perfectly right, you won't get any results!

You will also get a message similar to:
PHP Notice:  Undefined index: sAMAccountName in xxx.php on line xxx

Why?? Because for some strange reason, the attributes should be in lower case.
Therefore if you change sAMAccountName to samaccountname everything will work as expected...

The lines that should modified are:
$filter="(&(objectclass=person)(samaccountname=$ldapuser))";
$LDAPFieldsToFind = array("cn", "mail", "samaccountname"); 
$samaccountname=$info[$x]["samaccountname"][0];
Try it for yourself, and post your comments in case you experience something different...

Connect to an LDAP/AD using Joomla 2.5

Sometimes, things that should be straightforward, they just aren't!

After some fiddling around I managed to connect to an AD from Joomla, so I would like to share with you the configuration.

Apart from being a requirement in many projects, here are the benefits of using an LDAP/AD for Joomla authentication: