how to fetch the data from active directory as JSON? - php

I have the below PHP file through which I am trying to make an ajax call and fetch my required data from the JSON array :
<?php
$username = 'xxxxxxxxxxxx';
$password = 'xxxxxxx';
$server = 'ldap://xxxxxxx';
$domain = '#asia.xxxxxxxx.com';
$port = 389;
$ldap_connection = ldap_connect($server, $port);
if (! $ldap_connection)
{
echo '<p>LDAP SERVER CONNECTION FAILED</p>';
exit;
}
// Help talking to AD
ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3);
ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0);
$ldap_bind = #ldap_bind($ldap_connection, $username.$domain, $password);
if (! $ldap_bind)
{
echo '<p>LDAP BINDING FAILED</p>';
exit;
}
else
{
echo 'login successful';
}
$base_dn = "OU=Employees,OU=Accounts,OU=xxxxxx,DC=asia,DC=xxxxxx,DC=com";
//$dispname=$_POST['employeeID'];
$dispname="100676";
$filter ="(&(objectClass=user)(displayName=$dispname))";
$attr = array("sn","givenname","employeeid","distinguishedname","displayname","samaccountName","department","manager","mail","title","thumbnailphoto");
$result = ldap_search($ldap_connection,$base_dn,$filter,$attr);
$rescount = ldap_count_entries($ldap_connection,$result);
$data = ldap_get_entries($ldap_connection,$result);
// echo json_encode($data);
if ($data["count"] > 0)
{
for ($i=0; $i<$data["count"]; $i++)
{
echo "<p> sn: " . $data[$i]["sn"][0]."<br/>";
echo "givenname: ". $data[$i]["givenname"][0] ."<br/>" ;
echo "employeeID: " . $data[$i]["employeeid"][0]."<br/>";
echo "distinguishedName: " . $data[$i]["distinguishedname"][0]."<br/>";
echo "displayName: " . $data[$i]["displayname"][0]."<br/>";
echo "sAMAccountName: " . $data[$i]["samaccountname"][0]."<br/>";
echo "department: ". $data[$i]["department"][0]."<br/>";
echo "manager: " .$data[$i]["manager"][0]."<br/>";
echo "mail: ". $data[$i]["mail"][0]."<br/>";
echo "title: " .$data[$i]["title"][0]."<br/>";
echo "photo: " .$data[$i]["thumbnailphoto"][0]."<br/>";
echo "<br/><br/>";
}
}
else
{
echo "<p>No results found!</p>";
}
?>
The kind of output I am getting now :
<p> sn: xxxxxx<br/>givenname: xxxxx<br/>
employeeID: 0050<br/
>distinguishedName: CN=xxxx xxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxxxxx,DC=com<br/>
displayName: Mark Hewettk<br/>sAMAccountName: xxxxxxx<br/>
department: xxxxx<br/>manager: CN=xxxxxx xxxxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxx,DC=com
<br/>
mail: mhewettk#abc.com<br/>
title: xyz<br/>
photo :����%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz���������������������������������������������������������������������������
I do not want to echo the data(I am doing so here to show you guys that it is fetching the correct data), I want it as JSON so that I may use it in my UI.
Kindly help me on how to fetch the data from active directory as JSON ?
JS involved :
$('.leaderboard li').on('click', function () {
$.ajax({
url: "../popupData/activedirectory.php", // your script above a little adjusted
type: "POST",
data: {id:$(this).find('.parent-div').data('id')},
success: function(data){
console.info(data);
data = JSON.parse(data);
$('#popup').fadeIn();
//whatever attributes you want to pull from active directory
error: function(){
alert('failed, possible script does not exist');
}
});
});

How about converting the array you get back from ldap_get_entries to a json object using json_encode
echo json_encode($data, JSON_PRETTY_PRINT);

Related

strangeproblem with http request URL Parameter in web service php

Guys I'm working on the developing an app and I have a very strange problem. I have a database and a web service, I wrote a number of procedures and functions in the database and all well work within the environment MySql, but when I use from URL Request, not show true query (Always run else condition and show me record 'xxxx' that record for response when I understand send data from isn't true and invalid and not show me blank json like '[ ]'), almost all things test, like character set,... (all things that been comments) please help me in the below you're showing my code in the web service and Mysql: php side and Web service:
<?php
if (isset($_REQUEST['action'])) {
$action = $_REQUEST['action'];
} else {
echo "invalid Data";
exit;
}
switch ($action) {
case "getRecord" :
getRecord($_REQUEST['ID'], $_REQUEST['email'], $_REQUEST['mobile']);
break;
.
.
.
.
default:
echo "Your action select is not true!";
}
FUNCTION getRecord($ID, $Email, $Mobile)
{
$con = mysqli_connect("localhost", "root", "root", "myDB");
/*mb_detect_encoding($ID,"ascii");
mb_detect_encoding($Mobile,"ascii");
mb_detect_encoding($Email,"ascii");*/
mb_convert_encoding($ID, 'ascii');
mb_convert_encoding($Email, 'ascii');
mb_convert_encoding($Mobile, 'ascii');
if (mb_check_encoding($ID, "UTF-8")) {
echo "UTF-8 Yes!!!" . PHP_EOL;
}
if (mb_check_encoding($Email, "UTF-8")) {
echo "UTF-8 Yes!!!" . PHP_EOL;
}
if (mb_check_encoding($Mobile, "UTF-8")) {
echo "UTF-8 Yes!!!" . PHP_EOL;
}
if (mb_check_encoding($ID, "ascii")) {
echo "ascii Yes!!!" . PHP_EOL;
}
if (mb_check_encoding($Email, "ascii")) {
echo "ascii Yes!!!" . PHP_EOL;
}
if (mb_check_encoding($Mobile, "ascii")) {
echo "ascii Yes!!!" . PHP_EOL;
}
if (is_int($ID)) {
echo "ID is Integer Yes!!!" . PHP_EOL;
} else {
echo "ID is not Integer!!!" . PHP_EOL;
}
if (is_int($Email)) {
echo "Email is Integer Yes!!!" . PHP_EOL;
} else {
echo "Email is not Integer!!!" . PHP_EOL;
}
if (is_int($Mobile)) {
echo "Mobile is Integer Yes!!!" . PHP_EOL;
} else {
echo "Mobile is not Integer!!!" . PHP_EOL;
}
//////////////////////////////
if (is_string($ID)) {
echo "ID is String Yes!!!" . PHP_EOL;
} else {
echo "ID is not String!!!" . PHP_EOL;
}
if (is_string($Email)) {
echo "Email is String Yes!!!" . PHP_EOL;
} else {
echo "Email is not String!!!" . PHP_EOL;
}
if (is_string($Mobile)) {
echo "Mobile is String Yes!!!" . PHP_EOL;
} else {
echo "Mobile is not String!!!" . PHP_EOL;
}
//$sql = "SET #p0=''$ID''; SET #p1=''$Email''; SET #p2=''$Mobile''; CALL `getRecord`(#p0, #p1, #p2);";
//$sql = "CALL getRecord(''$ID'',''$Email'',''$Mobile'');";
//$sql = "CALL getRecord(" + "'$ID'" + "," + "'$Email'" + "," + "'$Mobile'" + ");";
//$sql = "CALL getRecord(" + "'$ID'" + "," + "'$Email'" + "," + "'$Mobile'" + ");";
//$sql = "CALL getRecord('2261','saleh#gmail.com','+989999999999');";//this state is good word too, and show me true query
$sql = "CALL getRecord('$ID','$Email','$Mobile');";
if (mysqli_connect_errno()) {
echo "Failed to connect MySQL server" . mysqli_connect_error();
}
mysqli_set_charset($con, "ascii");
$resualt = mysqli_query($con, $sql);
$records = array();
while ($row = mysqli_fetch_array($resualt)) {
$record = array();
$record['ID'] = $row['ID'];
$record['Name'] = $row['Name'];
$record['Family'] = $row['Family'];
$record['BirthDate'] = $row['BirthDate'];
$record['Email'] = $row['Email'];
$record['Mobile'] = $row['Mobile'];
$records[] = $record;
}
echo json_encode($records);
mysqli_close($con);
}
Sql side and procedure code :
DELIMITER $$
CREATE PROCEDURE `getRecord` (IN ID VARCHAR(166) CHARACTER SET ascii, IN EMail VARCHAR(166) CHARACTER SET ascii , IN Mobile VARCHAR(166) CHARACTER SET ascii)
BEGIN
DECLARE CheckMe VARCHAR(166);
DECLARE CountRecords INT;
SET CheckMe = ( SELECT Count(*) FROM persons WHERE persons.Email = Email AND persons.Mobile = Mobile);
IF CheckMe = 1 THEN
SELECT * FROM persons WHERE persons.ID = ID;
ELSE
SELECT * FROM persons WHERE persons.ID = 'xxxx';
END IF ;
END $$
DELIMITER ;

Ajax - Sending and Receiving

I have 2 files, A .js and a .php. The .php connects to the MySQL DB and the .js is the front end of the system.
I'm in the middle of trying to set it up so it sends a hash key to the ajax which returns the correct data for the related person from the database.
So far it does work as it send the hash from the URL to the PHP file and returns back the data in the console log.
//AJAX Function
//Grabs Varibles from PHP
var hash = window.location.hash.substr(1);
$(function() {
$('.hashfield').text(hash)
});
$.ajax({
type: "POST",
async: false,
cache: false,
url: "SelectFromSQL.php",
//Sending URL password
data:{ hash: hash, WorkingHash : "yes" },
success: function(data){
//Return of AJAX Data
console.log(data);
},
error:function() {
console.log("FAIL");
}
})
This is within the .js file which sends the hash
<?php
if(isset($_REQUEST['WorkingHash'])){
$hash = $_POST['hash'];
function IDHASH($hash){
echo $hash;
}
IDHASH($hash);
}
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ID, CustomerName, ContactName, Address, City, PostalCode, Country FROM customers WHERE ID=$hash";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["ID"] . "<br>";
echo $row["CustomerName"] . "<br>";
echo $row["ContactName"] . "<br>";
echo $row["Address"] . "<br>";
echo $row["City"] . "<br>";
echo $row["PostalCode"] . "<br>";
echo $row["Country"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
This is the .php file. I need to return the data from the database related to the correct customer ID.
All the data being echoed from the while loop will need it's own variably within a js format
My Goal is to retrieve each entry from the database
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["ID"] . "<br>";
echo $row["CustomerName"] . "<br>";
echo $row["ContactName"] . "<br>";
echo $row["Address"] . "<br>";
echo $row["City"] . "<br>";
echo $row["PostalCode"] . "<br>";
echo $row["Country"] . "<br>";
}
}
instead use
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
print_r(json_encode($row));
}
and in js
javacript
$.ajax({
type: "POST",
async: false,
cache: false,
url: "SelectFromSQL.php",
//Sending URL password
data:{ hash: hash, WorkingHash : "yes" },
success: function(data){
//Return of AJAX Data
data = JSON.parse(data);
console.log(data);
//YOU CAN USE data.ID , data.CustomerName and so on
},
error:function() {
console.log("FAIL");
}
})
How about something like this:
Edit
instead of return data echo it like this:
if ($result->num_rows > 0) {
// echo the data instead of return
echo json_encode($result->fetch_assoc());
}
To access the properties of the object you can in your success function do that :
success: function(data){
// parse your data first
data = JSON.parse(data);
//Return of AJAX Data
console.log(data.CustomerName);
console.log(data.ContactName);
// you can assign them to a variables if you want
var customerName = data.CustomerName;
var ccontactName = data.CustomerName;
}

ajax success doesnt alert anything

I have an AJAX request and if get id succeeds I would like to alert the data.
If I print_r my PHP function I get the correct result.
My ajax:
$.ajax({
type: "GET",
url: "getQuestions.php",
datatype: "json",
data:{
compid: id[4].innerHTML
},
success: function(response){
alert(response);
}
});
My getQuestions.php:
<?php
include "functions.php";
getQuestions($_GET['compid']);
My function getQuestions($compid) in functions.php:
function getQuestions($compid){
$int=intval($compid);
$vastus=array();
$conn = dbconnect();
$sql="SELECT * FROM bet_question WHERE compid = $int";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($vastus,$row);
}
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
return json_encode($vastus);
}
If I do print_r(getQuestions("some valid id")) in getQuestion.php I get valid result and if I do var_dump($_GET['compid']) in getQuestion I'll get the correct id from ajax request.
If I check if the request is sent using inspect elements I get that request is sent with correct params, but the response is empty.
Instead of return you need to use echo and it should be updated as
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($vastus,$row);
}
echo json_encode($vastus);
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
exit;
You don't have to return the data, use echo instead, and set content type:
function getQuestions( $compid ) {
$int=intval($compid);
$vastus=array();
$conn = dbconnect();
$sql="SELECT * FROM bet_question WHERE compid = $int";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($vastus,$row);
}
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
#header( 'Content-Type: application/json' );
echo json_encode( $vastus );
exit;
}
Hope it helps

How to generate a Log file in my machine when batch file is run as cronjob

Im running a Batch file as cronJob in my windows 7 machine,all I wanted is I want to create a log file ,when the cron Job is run along with the data,which it was displaying in the console.
The data ,is the echo statements which are present in the index.php which i have imported in the batch file.
Help me out to solve this issue.
index.php
<?php
echo "Welcome" ;
$fileD = "Login_".date('Y-m-d').".csv";
$fp1 = fopen($fileD, 'a+');
//Getting the files from below mentioned folder
$iterator1 = new FilesystemIterator("C:/wamp/www/logs1");
$iterator2 = new FilesystemIterator("C:/wamp/www/logs2");
$filelist = array();
foreach($iterator1 as $GLOBALS['entry1'])
{
if (strpos($entry1->getFilename(), "p1") === 0)
{
$filelist[] = $entry1->getFilename();
echo $entry1;
}
}
foreach($iterator2 as $GLOBALS['entry2']) {
if (strpos($entry2->getFilename(), "p2") === 0) {
$filelist[] = $entry2->getFilename();
echo "<br>";
echo $entry2;
}
}
$file1 = file_get_contents($entry1);
fwrite($fp1, $file1);
$file1 = file_get_contents($entry2);
fwrite($fp1, $file1);
fclose($fp1);
echo "<br/>";
echo "Done";
echo "<br/>";
//Deletes log file present in the logs folder
$n1= "$entry1";
if(!unlink($n1))
{
echo ("Error deleting file1 $n1");
}
else
{
echo ("Deleted $n1");
}
echo "<br/>";
$n2= "$entry2";
if(!unlink($n2))
{
echo ("Error deleting file2 $n2");
}
else
{
echo ("Deleted $n2");
}
echo "<br/>";
foreach (glob("*.csv") as $filename)
{
echo "$filename size " . filesize($filename) . "\n";
echo "<br>";
}
echo "<br>";
//$insertionDate = substr($filename,6,10);
$servername = "localhost";
$username = "user";
$password = "";
$dbname = "stat";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$file = file_get_contents($fileD);
$count = preg_match_all("/,Login,/", $file, $matches);
echo "Csv first word ";
$insertionDate = substr($file,1,10);
echo "<br/>";
echo "Total Hits:" . $totalLines = count(file($fileD));
echo "<br/>";
echo "Login:" . $count;
// Insert the Total hits and the corresponding success and failure count
$sql = "INSERT INTO hit_s (HitDate, count, category,success,failure,tcount,ocount)
VALUES ('$insertionDate', $totalLines, 'Hits',$success,$fail,$treeCnt,$oCnt)";
if ($conn->query($sql) === TRUE) {
echo "Total hits record inserted successfully \n";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$iterator = new FilesystemIterator("C:/wamp/www/Fed");
$filelist1 = array();
foreach($iterator as $GLOBALS['entry3'])
{
if (strpos($GLOBALS['entry3']->getFilename(), "*.csv") === 0)
{
$filelist1[] = $GLOBALS['entry3']->getFilename();
}
}
echo $GLOBALS['entry3'];
echo "<br/>";
$entry3="$fileD";
$n3= "$entry3";
if(!unlink($n3))
{
echo ("Error deleting $n3");
}
else
{
echo ("Deleted $n3");
}
echo "<br/>";
$conn->close();
?>
In batch file im calling the index.php file like below
C:\wamp\bin\php\php5.4.16\php.exe C:\wamp\www\Fed\csv\index.php
It looks like syslog will work for you:
$access = date("Y/m/d H:i:s");
syslog(LOG_WARNING, "Unauthorized client: $access {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']);

Parsing JSON response from PHP by array index. How?

I would like to know what is the latest JQuery syntax for parsing a JSON response by array index from a HTTP GET or POST request. My server side works great so I am look for way to parse the table row returned by PHP.
Here is my SERVER SIDE PHP code:
function qry_select_account($pk_account) {
// Global variables
Global $db_host, $db_user, $db_pass, $db_name;
// Connect to database server
$dbc = mysql_connect($db_host, $db_user, $db_pass) or die(mysql_error());
// Select target database
mysql_select_db($db_name) or die(mysql_error());
// suchislife801 <--- Selects account information
// Run query
$sql_qry = mysql_query("SELECT * FROM tblaccount
WHERE pk_account = '$pk_account'") or die(mysql_error());
// SQL Criteria AND acc_confirmed = 'y' AND acc_locked = 'n'
// Fetch table row for this user
$row = mysql_fetch_row($sql_qry);
print json_encode($row);
//echo 'Account: ' . $row[0];
//echo '<br />';
//echo 'Passowrd: ' . $row[1];
//echo '<br />';
//echo 'Acc Level: ' . $row[2];
//echo '<br />';
//echo 'Email: ' . $row[3];
//echo '<br />';
//echo 'Language: ' . $row[4];
//echo '<br />';
//echo 'Time Zone: ' . $row[5];
//echo '<br />';
//echo 'Signup: ' . $row[6];
//echo '<br />';
//echo 'Conf Code: ' . $row[7];
//echo '<br />';
//echo 'Confirmed: ' . $row[8];
//echo '<br />';
//echo 'Locked: ' . $row[9];
mysql_free_result($sql_qry);
// Close Connection
mysql_close($dbc);
}
Here is my JQuery code which is not working.
<script type="text/javascript">
$(function(){
$('#test_btn').live('click', function() {
$.getJSON("http://localhost/api.php?call=select_account&p0=suchislife801", function(json){
alert("JSON Data: " + json);
});
});
</script>
You can use jQuery.parseJSON( json ) function.
Make sure that json returned from server is a valid json
You can validate json response from here
Use following to check if error is returned by server
$.getJSON("example.json", function(data) {
alert(date);
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
);
looping through json depends on type of json
if its a map type structure, like following
var map = {
"data1": "value1",
"data2": "value2"
};
you can use following to iterate through
$.each(map, function(key, value) {
alert(key + ': ' + value);
});
Reference: http://api.jquery.com/jQuery.each/

Categories