So I just got started with LDAP, and was reading this tutorial on LDAP with PHP.
http://www.devshed.com/c/a/PHP/Using-PHP-With-LDAP-part-1/4/
There, once the result set is obtained. There were two commands/functions I came across...
<?php // print number of entries found
echo "Number of entries found: " . ldap_count_entries($conn, $result) . "<p>"; ?>
and
<?php // get entry data as array
$info = ldap_get_entries($conn, $result);
// iterate over array and print data for each entry
for ($i=0; $i<$info["count"]; $i++) { echo "dn is: ". $info[$i]["dn"] ."<br>";
echo "first cn is: ". $info[$i]["cn"][0] ."<br>";
echo "first email address is: ". $info[$i]["mail"][0] ."<p>";
} ?>
So, in what ways do ldap_count_entries and $info["count"] differ?
Thanks in advance!
As far as I know, the difference is mainly between whether you have to retrieve the results from the server or not.
To get $info['count'] you have to retrieve the complete result from the server via ldap_get_entries which might be a lengthy thing depending on the size of the result and the connection to your LDAP-Server.
To check whether it's worth the effort you can get the size of the resultset with ldap_count entries and depending on that result your application can decide what to do.
Related
I am trying to count how many times I echoed a text but I want to display the number (count) at the top of the page.
I have an array of data called transactions. I want to echo all the transactions but also include the total number of transactions at the top of the page like this:
"10 transactions found!
Transaction 1 ....
Transaction 2 ...
....
Transaction 10 ..."
I have this below but the issue is that the "number of transactions found" will be echoed after all the transactions data but I want it at the top".
function count_transactions($array_transactions) {
if(isset($array_transactions)){
$count = 0;
foreach($array_transactions['data']['txs'] as $value){
echo "<p>Transactions id: " . $value['txid'] . "</p>";
$count++;
}
echo $count . "transactions found!";
}
}
I was thinking that I can use array_push() to push all transactions data into an array and then echo each value in the array after the count is completed. However, this way I would need another foreach loop which will slow down the page if a lot of data is in the transaction array. Is there an easier way to echo $count at the top without using another foreach loop?
I think it would simplify things to just use the count() function.
function count_transactions($array_transactions) {
if (isset($array_transactions['data']['txs'])) {
// Count goes at the top
echo count($array_transactions['data']['txs']) . "transactions found!";
// Then the list
foreach($array_transactions['data']['txs'] as $value){
echo "<p>Transactions id: " . $value['txid'] . "</p>";
}
}
}
Also, when you check isset, it seems better to check that the specific sub-array you're about to iterate is set. $array_transactions will always be set - it's a required function argument.
Store the text in a variable and echo after the loop is done
function count_transactions($array_transactions) {
if(isset($array_transactions)){
$count = 0;
$text = "";
foreach($array_transactions['data']['txs'] as $value){
$text .= "<p>Transactions id: " . $value['txid'] . "</p>";
$count++;
}
echo $count . "transactions found!";
echo $text;
}
}
Depending on what the array looks like you may be able to use implode, array_column and count.
function count_transactions($array_transactions) {
if(isset($array_transactions)){
echo count($array_transactions['data']['txs']). "transactions found!";
echo "<p>Transactions id: " . implode("</p><p>Transactions id: ", array_column($array_transactions, "txid")) . "</p>";
}
}
But this will only work if the array is uniformed.
Background Information
I'm trying to figure out how to query our active directory server for information about users / groups via a php web application. (let's call it the "widget app". Ultimately, I'm going to use this information to try to "see" what fields / data is available in AD to check / use as a part of authentication besides just username and password. For example, I only want to allow people in specific AD groups ... etc.
I'm using this as an example:http://php.net/manual/en/ldap.examples-basic.php
Problem
Unfortunately, I'm getting zero results... even when I use my AD username as the filter.
this is what my results look like:
Connecting ...connect result is Resource id #26
Binding ...Bind result is 1
Searching for (sn=myusername*) ...Search result is Resource id #27
Getting entries ...
Data for 0 items returned:
What I've tried so far:
We have another web application that's running on the same web server as the widget app. This other application is set up so that apache will prompt for AD credentials. I know it works because when I try to authenticate myself on this secondary application, my AD credentials are authenticated and i'm given the authorization I need to use the application.
So I started to poke around the apache conf and tried to make sure my PHP code is using the same values.
The Code
Here's the PHP code that's currently failing:
public function ldap_test() {
echo "<h3>LDAP query test</h3>";
echo "Connecting ...";
$ds=ldap_connect("10.11.11.1111"); // must be a valid LDAP server!
echo "connect result is " . $ds . "<br />";
if ($ds) {
echo "Binding ...";
//$r=ldap_bind($ds);
$r=ldap_bind($ds,"CN=testvalue1,OU=Services,OU=Accounts,DC=td,DC=ab,DC=org", "somepasswordvalue");
// read-only access
echo "Bind result is " . $r . "<br />";
echo "Searching for (sn=myusername*) ...";
// Search surname entry
$sr=ldap_search($ds, "CN=testvalue1,OU=Services,OU=Accounts,DC=td,DC=ab,DC=org", "somepasswordvalue", "(sAMAccountName=myusername*)");
echo "Search result is " . $sr . "<br />";
echo "Number of entries returned is " . ldap_count_entries($ds, $sr) . "<br />";
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"] . "<br />";
echo "first cn entry is: " . $info[$i]["cn"][0] . "<br />";
echo "first email entry is: " . $info[$i]["mail"][0] . "<br /><hr />";
}
echo "Closing connection";
ldap_close($ds);
} else {
echo "<h4>Unable to connect to LDAP server</h4>";
}
}
Apache configuration that I used to build my PHP code: (this config works and properly prompts me for my AD credentials and authenticates properly)
<AuthnProviderAlias ldap ldap-test>
AuthLDAPBindDN "CN=testvalue1,OU=Services,OU=Accounts,DC=td,DC=ab,DC=org"
AuthLDAPBindPassword somepasswordvalue
AuthLDAPURL "ldap://10.11.11.111/ou=Accounts,dc=td,dc=ab,dc=org?sAMAccountName?sub?(objectClass=*)"
AuthLDAPMaxSubGroupDepth 5
</AuthnProviderAlias>
This is the first time I've tried to do AD authentication in PHP and I'm not the one who manages our AD implementations so I'm fairly green.
If you have any suggestions for me please feel free.
Thanks
The problem was that I was filtering by a common name. Notice this:
AuthLDAPBindDN "CN=testvalue1,OU=Services,OU=Accounts,DC=td,DC=ab,DC=org"
So to fix it , i just had to remove this from the filter and it worked.
AuthLDAPBindDN "OU=Services,OU=Accounts,DC=td,DC=ab,DC=org"
So I've been bashing my head on this problem for some time and i just cant find an example to get it working for my own piece of code. Now i am hoping that some of you got a solution for me, or at least point me in the right direction. So the problem is the following:
A person can upload certain files and information to a database. The uploading of the files, so the file name, is in the same database row as its name, location etc. So for example: a person has several required fields such as name, location and upload file which together form one row in the database. This works all fine and the files are being uploaded to a folder named: uploads/participant-database (entire name is: mytestsite.nl:2222/CMD_FILE_MANAGER/domains/mytestsite.nl/public_html/Recap/wp-content/uploads/participants-database).
However, the problem is, that the person also can search for the database data (and retrieve it) by using a checkbox search system. Based on the persons given checkbox options, certain data (that matches the selection) is being showed. The question however is: how can i assign the downlaod links to the right database values? Ill make it a bit clearer with some images below:
Picture with the displaying / retrieving of the database information
The code which retrieves the database information is as follows (i just took 1 filter to give the query idea because else it would be a to big piece of code):
if(!empty($_POST['columns_location']) && !empty($_POST['columns_theme'])) { // empty() checks if the value is set before checking if it's empty.
// Runs mysql_real_escape_string() on every value encountered.
$clean_criteria_location = array_map('mysql_real_escape_string', $_REQUEST['columns_location']);
// Convert the array into a string.
$criteria_location = implode("|",$clean_criteria_location);
// Runs mysql_real_escape_string() on every value encountered.
$clean_criteria_theme = array_map('mysql_real_escape_string', $_REQUEST['columns_theme']);
// Convert the array into a string.
$criteria_theme = implode("|",$clean_criteria_theme);
$tmp = $wpdb->get_results("
SELECT
name_of_living_lab, location_of_living_lab, type_of_living_lab, theme_of_living_lab, stage_of_living_lab, living_lab_document
FROM
wp_participants_database
WHERE
location_of_living_lab REGEXP ('$criteria_location') AND theme_of_living_lab REGEXP ('$criteria_theme')
ORDER BY
name_of_living_lab ASC
");
}
The code that displays the results is as follows:
echo "<table>
<tr>";
echo "<th>Name of Living Lab</th>";
echo "<th>Location of Living Lab</th>";
echo "<th>Type of Living Lab</th>";
echo "<th>Theme of Living Lab</th>";
echo "<th>Stage of Living Lab</th>";
echo "<th>Living Lab document</th>";
echo "</tr>";
if(count($tmp)>0){
for($i=0;$i<count($tmp);$i++){
echo "<tr>";
foreach($tmp[$i] as $key=>$value){
echo "<td>";
$b=unserialize($value);
if(is_array($b)){
array_filter($b);
$counttwo = 0;
foreach($b as $y){
if ($counttwo++ > 1) echo ", ";
echo $y;
}
}
else{
echo $value;
}
echo "</td>";
}
echo "</tr>";
}
}
echo '</table>';
Now the question is, how do i assign the right links to the queried results? So in the picture example you can see a document table (which is a result of the query) and this text in it should be clickable and downloadable with THAT stored document. So i guess the $tmp result value should be checked for only the database column: documents and then the link should be created which connects the database value to the right document. Though, i have absolutely no idea how to do this (even after quite some research).
I hope you guys can help me or can give me some pointers! Thank you in advance!
***UPDATE***
The new display code (which doesn't work since it outputs the text 2 times) with the added suggestions of #dHaRa uMaraniYa :
if(count($tmp)>0){
for($i=0;$i<count($tmp);$i++){
echo "<tr>";
foreach($tmp[$i] as $key=>$value){
echo "<td>";
if($key =='DOC'){
echo ''.$value.'';
}
$b=unserialize($value);
if(is_array($b)){
array_filter($b);
$counttwo = 0;
foreach($b as $y){
if ($counttwo++ > 1) echo ", ";
echo $y;
}
}
else{
echo $value;
}
echo "</td>";
}
echo "</tr>";
}
}
echo '</table>';
Select living_lab_document as DOC
$tmp = $wpdb->get_results("
SELECT
name_of_living_lab, location_of_living_lab, type_of_living_lab, theme_of_living_lab, stage_of_living_lab, living_lab_document as DOC
FROM
wp_participants_database
WHERE
location_of_living_lab REGEXP ('$criteria_location') AND theme_of_living_lab REGEXP ('$criteria_theme')
ORDER BY
name_of_living_lab ASC
");
and check that if
if($key =='DOC'){
echo ''.$value.'';
}
else
{
echo $value;
}
I have parts website that I need to update the search script for. I have an Excel sheet with 3 columns, Part No, Part Name, and Page Number. I just want to create a simple search box and when an entry is made and you click submit it searches through the txt list and displays/echos/prints on the web page any lines of the txt file that correspond, be it part number or description name. It is to help people locate a part and then link them to the page of a catalog it can be found on - so the page number is a link to the page.
This search script below does exactly what I need it to do, I did not write it, it was written by a former employee - it connects to a mySQL db - BUT I cannot do that anymore, the mySQL is on a shared hosting service and the minimum character search is set to 4 and cannot be modified. I need to be able to search 3 character words such as 'oil', 'brm', 'rod'.
I've been trying for a few days to find an alternative method. I would like to be able to connect or search the txt or Excel file that contains the list of part numbers and the page they can be found on and NOT have it connect to the mySQL db.
I don't know how to modify this to have it connect to a txt file instead of the mySQL db.
Is that even possible? Do I need to use a different kind of script?
I appreciate any guidance. Thank you!
<?php
if ($_POST['action'] =="search") {
function make_page_url($pageno) {
return "../vwcatalog/2013/" . $pageno . ".html";
}
echo "<tr><td>Search Results : (HINT-If Nothing Is Listed Below, Try the Table of Contents at the Bottom of the Page<br>
Search Hint: If necessary, try using singular words, instead of plural, i.e.; 'seat' - instead of 'seats'.)</td></tr>\n";
$dbsearchlink=mysql_connect($db["host"],$db["user"],$db["pass"])
or die("Failed to make database connection: " . mysql_error());
mysql_select_db($db["used"])
or die("Failed to select database: " . mysql_error());
$query=sprintf("select partno,description,pageno from part_to_page where year=2013 and match(partno,description) against ('%s')",
mysql_real_escape_string($_POST['searchfor']));
$result=mysql_query($query) or die("Query failed: " . mysql_error());
echo "<tr><td><table>\n";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$url=make_page_url($row['pageno']);
echo "\t<tr>";
echo "<td>" . $row['partno'] . "</td>";
echo "<td><a href=$url>" . $row['description'] . "</a></td>";
echo "</tr>\n";
}
echo "</table></td></tr>\n";
mysql_free_result($result);
mysql_close($dbsearchlink);
}
?>
Why not just switch the query
if(strlen($_POST['searchfor']) < 4){
$query=sprintf("select partno,description,pageno from part_to_page where year=2013 and ( partno LIKE '\%%s\%' OR description LIKE '\%%s\%')",
mysql_real_escape_string($_POST['searchfor']),
mysql_real_escape_string($_POST['searchfor']));
} else {
$query=sprintf("select partno,description,pageno from part_to_page where year=2013 and match(partno,description) against ('%s')",
mysql_real_escape_string($_POST['searchfor']));
}
I have a table with about 500,000 rows, and need to query it to retrieve results. Basically the user just inputs a case number, and then I want to execute the following query and display the results using a while loop
if (!empty($_POST["casenum"])) {
$result2 = mysql_query("SELECT Box_Content.case_number, Transfer.number, Transfer.location, Box.number FROM Box_Content, Transfer, Box WHERE Box_Content.box_id = Box.id and Box.transfer_id = Transfer.id and Box_Content.case_number = '".$_POST['casenum']."'");
while ($row = mysql_fetch_array($result2)) {
echo "Case number: ".$casenum." text ";
echo "<br />";
}
} else {
echo "<h4>WARNING!!! Search criteria entered not valid. Please search again.</h4>";
}
What am I doing wrong here?
EDIT:
It works now if only one row is returned, but for two rows, it seems to be trying to print the entire table...
$casenum = $_POST["casenum"];
echo "<br />The case number entered is: $casenum<br />";
if (!empty($_POST["casenum"]))
{
$result2 = mysql_query("SELECT Box_Content.case_number, Transfer.number as transfer_number, Transfer.location as transfer_location, Box.number as box_number FROM Box_Content, Transfer, Box WHERE Box_Content.box_id = Box.id and Box.transfer_id = Transfer.id and Box_Content.case_number = '" . $_POST['casenum'] . "'");
while($row = mysql_fetch_array($result2))
{
print_r ($row);
echo "<br />";
echo "<b>Case number: </b>" . $row['case_number'] ."<br />";
echo "<b>Transfer number: </b>" . $row['transfer_number'] ."<br />";
echo "<b>Transfer location: </b>" . $row['transfer_location'] ."<br />";
echo "<b>Box number: </b>" .$row['box_number'] ."<br />";
}
}
else
{
echo "<h4>WARNING!!! Search criteria entered not valid. Please search again.</h4>";
}
var_dump($_POST);
Try:
while ($row = mysql_fetch_array($result2)) {
echo "Case number: ". $row['Box_Content.case_number'] ." text ";
echo "<br />";
}
$row['case_number'] will output the case_number retrieved for each row in your resultset.
However, you should look into doing one of two things:
Start using best practices.
Start using a non-deprecated SQL library (mysqli, PDO).
This query is susceptible to SQL injection:
"SELECT Box_Content.case_number, Transfer.number, Transfer.location, Box.number
FROM Box_Content, Transfer, Box
WHERE Box_Content.box_id = Box.id and Box.transfer_id = Transfer.id
and Box_Content.case_number = '".$_POST['casenum']."'"
Use mysql_real_escape_string($_POST['casenum']) to patch this.
Reference: http://php.net/manual/en/function.mysql-real-escape-string.php
The mysql_* functions have long been deprecated due to unprepared statement operations. Look into either mysqli or PDO for your project instead.
What am I doing wrong here?
1) $casenum isn't set in your code... (Please tell me it is nothing and you don't have register superglobals turned on?!) You would probably want $row['case_number']
2) But anyway, that's not really what you are doing wrong... Your biggest mistake is using user input without any kind of validation or sanitization...
Imagine if $_POST["casenum"] was equal to...
' or 1=2 union select user,password,email,salt from users
You seem to be using $casenum from nowhere.
Try:
while($row = mysql_fetch_assoc($result2))
echo "Case number: ".$row['number']." text <br />";
When using the mysql_fetch functions assoc will bring back named indexed data, num will bring back numberic indexed data and array will bring back both, so try to use one or the other.
Then when you do $row = mysql_fetch_assoc($result2) your essentially saying for each row of data returned store it as a (in this case associative) array in $row, so you can then access your data via the standard array commands ($row['foo']).