I tried much time to create a user in the group but could not have been. While I am able to create a user but not in a group. My Group name is RDP and Netmetric is the folder where I am creating a user.
if($ldapbind = ldap_bind($ldap_conn, $username, $password) == true)
{ // if ldap bind
$adduserAD["cn"] = $name;// Common name
$adduserAD["givenname"] = $name;
$adduserAD["sn"] = 'Kumar'; // Surname
$adduserAD["sAMAccountName"] = $name; // SamaAccountname declare here
$adduserAD['userPrincipalName'] = $name;
$adduserAD["objectClass"] = "User"; // Object class user
$adduserAD["displayname"] = "Test User";
$adduserAD['mail'] = $email;
$adduserAD["userPassword"] = $pwd; // set password here
$adduserAD["userAccountControl"] = "66080";
$base_dn = "cn=".$name.",ou=Netmetric,DC=ntop,DC=local";// base dn
// Attempt to add the user with ldap_add()
if(ldap_add($ldap_conn, $base_dn, $adduserAD) == true){
echo "User is created";
}
ldap_close($ldap_conn);
}else{
echo "Not connected with server";
}
Since you have a openldap tag on question, I'm assuming you are trying to add users in OpenLDAP database.
If that is the case you should get an error because sAMAccountName,userPrincipalName,userAccountControl attributes are not present in OpenLDAP schema.
Related
I am creating a user in Active Directory using PHP and create it correctly, but now I need to check the options shown in the image from the same PHP code, I also attach an example of how the user created in Active Directory using PHP.
Checks that I need to do using PHP
User creation code
<?php
// Username used to connect to the server
$username = "administrator";
// Password of the user.
$password = "Password01";
// Domain used to connect to.
$domain = "nagara.ca";
// Proper username to connect with.
$domain_username = "$username" . "#" . $domain;
// User directory. Such as all users are placed in
// the Users directory by default.
$user_dir = "OU=Students,DC=nagara,DC=ca";
// Either an IP or a domain.
$ldap_server = "192.168.100.2";
// Get a connection
$ldap_conn = ldap_connect($ldap_server);
// Set LDAP_OPT_PROTOCOL_VERSION to 3
ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3) or die ("Could not set LDAP Protocol version");
// Authenticate the user and link the resource_id with
// the authentication.
if($ldapbind = ldap_bind($ldap_conn, $domain_username, $password) == true)
{
// Setup the data that will be used to create the user
// This is in the form of a multi-dimensional
// array that will be passed to AD to insert.
$adduserAD["cn"] = "testuser";
$adduserAD["givenname"] = "Test";
$adduserAD["sn"] = "User";
$adduserAD["sAMAccountName"] = "testuser";
$adduserAD['userPrincipalName'] = "testuser#nagara.ca";
$adduserAD["objectClass"] = "user";
$adduserAD["displayname"] = "Test User";
$adduserAD["userPassword"] = "Password01";
$adduserAD["userAccountControl"] = "544";
$base_dn = "cn=testuser,ou=students,DC=nagara,DC=ca";
// Attempt to add the user with ldap_add()
if(ldap_add($ldap_conn, $base_dn, $adduserAD) == true)
{
// The user is added and should be ready to be logged
// in to the domain.
echo "User added!<br>";
}else{
// This error message will be displayed if the user
// was not able to be added to the AD structure.
echo "Sorry, the user was not added.<br>Error Number: ";
echo ldap_errno($ldap_conn) . "<br />Error Description: ";
echo ldap_error($ldap_conn) . "<br />";
}
}else{
echo "Could not bind to the server. Check the username/password.<br />";
echo "Server Response:"
// Error number.
. "<br />Error Number: " . ldap_errno($ldap_conn)
// Error description.
. "<br />Description: " . ldap_error($ldap_conn);
}
// Always make sure you close the server after
// your script is finished.
ldap_close($ldap_conn);
?>
I hope you can support me.
Thank you very much.
I want to set active user session limit in ldap using php code at the time of creating users.
$ldap_conn = ldap_connect($ldap_server);// connect ldap server
ldap_set_option($ldap_conn, LDAP_OPT_PROTOCOL_VERSION, 3) or die ("Could
not set LDAP Protocol version");
ldap_set_option($ldap_conn, LDAP_OPT_TIMELIMIT, 3) or die ("Could not set
LDAP Protocol version");
if($ldapbind = ldap_bind($ldap_conn, $username, $password) == true)
{ // bind the ldap if bind then set parameters
$adduserAD["cn"] = $name;
$adduserAD["givenname"] = $name;
$adduserAD["sn"] = 'Kumar';
$adduserAD["sAMAccountName"] = $name;
$adduserAD['userPrincipalName'] = $uname;// log on name
$adduserAD['initials'] = 'Mr';
$adduserAD["objectClass"] = "User";
$adduserAD["displayname"] = "Test User";
$adduserAD['mail'] = $email;// email
$adduserAD['description'] ='We are testing';
$adduserAD["userPassword"] = $pwd;
$adduserAD["userAccountControl"] = "66080"; //enable or disable user..512
66080 389,66048,636,544,
$base_dn = "cn=".$name.",OU=Netmc,DC=xyz,DC=local"; base domain name
// Attempt to add the user with ldap_add()
if(ldap_add($ldap_conn, $base_dn, $adduserAD) == true){// user creation
echo "User is created";
}
ldap_close($ldap_conn);
}else{
echo "Not connected with server";
}
User is created successfully but session time is not set. I don't how to
set session time limit in ldap at the of user creation. Please guide me to
solve this problem. Thanks in advance.
I just cannot figure out what I'm doing wrong, I've scoured the web for answers but cannot find anything that works. Please can someone look at my code and tell me where I'm going wrong? If I comment out "objectclass" I get "server is unwilling to perform 53", if I change the OU to something silly (the $dn) then I get "Naming Violation", if I mash the keyboard and put in random letters for the user's name I still get "already exists" error even though no parts of the things I'm entering exist. If I add an ldap_mod_replace line in for another CN in the same OU it works fine so I know the connection is working. I've tried without the '[0]' on all except objectclass too (as I've seen in all examples). Company and user info edited obviously.
$server = "ldap://ServerName.domain.co.uk";
$dn = "OU=Advertising,OU=EmailDepartmentAccounts,OU=Administration,OU=Central,DC=domain,DC=co,DC=uk";
//domain user to connect to LDAP
$user = "helpdesk.ldap#domain.co.uk";
//user password
$psw = "Password";
$ds = ldap_connect($server);
if ($ds) {
ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
$r = ldap_bind($ds, $user, $psw);
$proxyaddresses_array = array();
$proxyaddresses_array[0] = "X400:c=GB;a= ;p=Company Name p;o=PWEXCHANGE;s=Kitbag;g=Digital;";
$proxyaddresses_array[1] = "SMTP:test.maff#domain.co.uk";
$proxyaddresses_array[2] = "smtp:test.maff#other.co.uk";
//$NewUser = array();
$NewUser["cn"][0] = "Test Maff1";
$NewUser["userprincipalname"][0] = "Test.Maff1#domain.co.uk";
$NewUser["samaccountname"][0] = "Test.Maff";
$NewUser["objectClass"][0] = "top";
$NewUser["objectClass"][1] = "person";
$NewUser["objectClass"][2] = "organizationalPerson";
$NewUser["objectClass"][3] = "user";
//$NewUser["givenname"][0] = "Test";
//$NewUser["sn"][0] = "Maff";
//$NewUser["instancetype"][0] = 4;
//$NewUser["physicaldeliveryofficename"][0] = "Leeds";
//$NewUser["displayname"][0] = "Test Maff";
//$NewUser["proxyaddresses"] = $proxyaddresses_array;
//$NewUser["department"][0] = "IT";
//$NewUser["company"][0] = "Company Name";
//$NewUser["homemta"][0] = "CN=Microsoft MTA,CN=STH-EXC-01B,CN=Servers,CN=BSP,CN=Administrative Groups,CN=Johnston Press plc,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=domain,DC=co,DC=uk";
//$NewUser["displaynameprintable"][0] = "Test Maff";
//$NewUser["mailnickname"][0] = "Test.Maff";
//$NewUser["useraccountcontrol"][0] = "512";
//$NewUser["primarygroupid"][0] = "513";
//$NewUser["name"] [0]= "Test Maff";
$NewUser["objectcategory"][0] = "CN=Person,CN=Schema,CN=Configuration,DC=domain,DC=co,DC=uk";
//$NewUser["mail"] = "Test.Maff#domain.co.uk";
if ($NewUserAdded = ldap_add($ds, $dn, $NewUser)) {
echo "success<br />";
} else {
echo ldap_error($ds) . " " . ldap_errno($ds);
}
ldap_close($ds);
} else {
echo "unable to connect to LDAP server";
}
I might be wrong, but from what I read in your code you have an entry OU=Advertising,OU=EmailDepartmentAccounts,OU=Administration,OU=Central,DC=domain,DC=co,DC=uk. And as far as I interpret your code you want to add an entry below that entry. But you have to provide the DN of the new entry as second parameter to ldap_add. But you provide the baseDN of the new entry. and that is already there. Otherwise you wouldn't be able to add something into it.
So you should call something like the following before calling the ldap_add:
$dn = 'cn=' . $NewUser['cn'][0] . ',' . $dn;
That uses the baseDN and prepends it with the cn of the current user.
Hope that helps
I have a a php function that works for creating a new user in Joomla 2.5. This function is used to synchronize an external customer database with Joomla.
The new requirement is that the email address needs to be an optional field. I can't seem to get the JFactory function to work without an email address. Is there another way to get the user created?
function add_joomla_user($username, $email, $name, $password, $group) {
// Creates a new user in Joomla database with passed in information
$return_message = '';
$mainframe =& JFactory::getApplication("site");
$mainframe->initialise();
$user = JFactory::getUser(0); // it's important to set the "0" otherwise your admin user information will be loaded
jimport('joomla.application.component.helper'); // include libraries/application/component/helper.php
$usersParams = &JComponentHelper::getParams( 'com_users' ); // load the Params
$userdata = array(); // place user data in an array for storing.
$userdata['username'] = $username;
$userdata['email'] = $email;
$userdata['name'] = $name;
$userdata['password'] = $password;
$userdata['password2'] = $password;
$defaultUserGroup = $usersParams->get('new_usertype', $group);
$userdata['groups']=array($defaultUserGroup);
$userdata['block'] = 0; // set this to 0 so the user will be added immediately.
if (!$user->bind($userdata)) { // bind the data and if it fails raise an error
JError::raiseWarning('', JText::_( $user->getError())); // something went wrong!!
$return_message = 'Error binding data: ' . $user->getError();
}
if (!$user->save()) {
JError::raiseWarning('', JText::_( $user->getError()));
$return_message = 'Error creating user: ' . $user->getError();
} else {
$return_message = 'Created user';
}
return $return_message;
}
Joomla user handling definitely requires a unique email address for each user. It's tricky and I somewhat hesitate to suggest this, but what you could do if it is missing is substitute a random string or a string generated based on information in your database (like the $userdata['email'] = $username . '#noemail';. That way they will be easy to find later. Of course this means password reset and other functions will never work, but that would be true anyway if the user has no email.
Good day Everyone..
I have an issue that is puzzling me and I can not seem to find a way to solve it. Even the tech support in my hosting service can not solve it.
I have created a small script to do a simple task. I require the employees to log in to perform any said task.
I have tested the application on a development server and the login script works perfectly, but when I place it on the webserver the connection is never established.
I use the same username and passowrd in the dbcon.php file to log in using phpMyAdmin and it works, and I run the queries and they also work.
Here are the files:
1: dbcon.php
<?php
$connect = "mysql:host=localhost;dbname=mdchaara_draiwil_dms;charset=utf8";
$db_user = "dbusername";
$db_pass = "dbpassword";
$db = new PDO($connect,$db_user,$db_pass);
?>
2: login.php:
<?php
session_start();
require "../../_dbcon/_dbcon.php";
//Timezone settings:
$timezone = "Asia/Kuwait";
if(function_exists('date_default_timezone_set')) date_default_timezone_set($timezone);
// check the username has only alpha numeric characters
if (ctype_alnum($_POST['username']) != true)
{
//if there is no match
$message = "Username must be alpha numeric";
}
//check the password has only alpha numeric characters ***/
if (ctype_alnum($_POST['password']) != true)
{
//if there is no match ***/
$message = "Password must be alpha numeric";
}
else
{
// if we are here the data is valid and we can insert it into database
$username = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$password = filter_var($_POST['password'], FILTER_SANITIZE_STRING);
//SQL Injection Precaution:/
$username = stripslashes($username);
$password = stripslashes($password);
try
{
//Select Statement:
$stmt = $db->query("SELECT *
FROM dms_gt_users
WHERE username = '$username' AND password = '$password'");
$result = $stmt->rowCount();
}
catch(PDOException $ex) {
echo "An Error occured!"; //user friendly message
some_logging_function($ex->getMessage());
}
// If result matched $username and $password, there will be one row
if($result==1){
// check if the account is active:
$stmt = $db->query("SELECT id_status
FROM dms_gt_users
WHERE username = '$username' AND password = '$password'");
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$id_status= $row['id_status'];
}
$stmt = $db->query("SELECT employee_id
FROM dms_gt_users
WHERE username = '$username' AND password = '$password'");
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$employee_id= $row['employee_id'];
}
//Check if account is active:
if($id_status == "A"){
// Create Session ID:
$session_id = "";
$_SESSION['sid'] = "";
$session_id = mt_rand(100000, 999999);
$sid_update = $db->query("UPDATE dms_gt_users
SET `session_id`='$session_id'
WHERE username='$username' and password ='$password'");
$_SESSION['sid'] = $session_id;
//Get last login details:
$current_login = date("Y-m-d H:i:s");
$stmt = $db->query('SELECT `last_log_in`
FROM dms_gt_users
WHERE `employee_id` = '.$employee_id);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$last_log_in = $row['last_log_in'];
}
$_SESSION['last_log_in'] = $last_log_in;
//get IP address:
$ip = getenv('REMOTE_ADDR');
//Add login details to Activity Log:
$stmt = $db->query("INSERT INTO dms_activity_log
(`employee_id`, `activity_date_time`, `activity`, `ip_address`)
VALUES ('$employee_id', '$current_login', 'Logged in', '$ip')");
//Add login details to users table:
$stmt = $db->query("UPDATE dms_gt_users
SET `last_log_in`='$current_login'
WHERE username='$username' and password ='$password'");
//update session login
$_SESSION['login']= 1;
//save employee id to session
$_SESSION['employee_id'] = $employee_id;
// redirect to portal home:
header ("Location:../../../home.php");
}
//Account is not Active:
else{
header ("Location:../../../index.php");
}
}
//Username or password are incorrect
else {
header ("Location:../../../index.php");
}
}
?>
What am I doing wrong? and if my code is ok, what should I tell the hosting Tech Support to look for?
Thanks!!
EDIT
#noc2spam: I have updated the connection string as you have advised, I get no errors logged. I var_dump the $db, and I get object(PDO)#1 (0)
It is pretty hard to tell why this is happening without looking into the server itself. I suggest that you enable the Exception mode so that you can see what the problem is. For example:
try {
$connect = "mysql:host=localhost;dbname=mdchaara_draiwil_dms;charset=utf8";
$db_user = "dbusername";
$db_pass = "dbpassword";
$db = new PDO($connect,$db_user,$db_pass);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
echo 'PDO Exception: '.$e->getMessage();
die();
}
It would be much easier to troubleshoot now. Check if you are getting any error and update the original question with the message if possible. I will edit this answer after that.
IF Roger Ng's answer doesn't solve it, then you may have a firewall blocking your connection. Check your mysql server port... typically 3306.
Check your database's url. Generally, in shared/dedicated hosting environment, DB server and App Server are on different machines. Also, many service providers do not provide mysql cluster services on port 3306. So, please get the correct URL and port of the database from your hosts CPanel or tech support team.
Also, add the App server's IP address to the permitted IP addresses list in Remote MySQL Cpanel interface.