Friday 27 June 2014

PHP: Get user list from the Active Directory

/**
 * Get a list of users from Active Directory.
 */
$ldap_password = 'PASSWORD';
$ldap_username = 'USERNAME@DOMAIN';
$ldap_connection = ldap_connect(HOSTNAME);
if (FALSE === $ldap_connection){
    // Uh-oh, something is wrong...
}

// We have to set this option for the version of Active Directory we are using.
ldap_set_option($ldap_connection, LDAP_OPT_PROTOCOL_VERSION, 3) or die('Unable to set LDAP protocol version');
ldap_set_option($ldap_connection, LDAP_OPT_REFERRALS, 0); // We need this for doing an LDAP search.

if (TRUE === ldap_bind($ldap_connection, $ldap_username, $ldap_password)){
    $ldap_base_dn = 'DC=XXXX,DC=XXXX';
    $search_filter = '(&(objectCategory=person)(samaccountname=*))';
    $attributes = array();
    $attributes[] = 'givenname';
    $attributes[] = 'mail';
    $attributes[] = 'samaccountname';
    $attributes[] = 'sn';
    $result = ldap_search($ldap_connection, $ldap_base_dn, $search_filter, $attributes);
    if (FALSE !== $result){
        $entries = ldap_get_entries($ldap_connection, $result);
        for ($x=0; $x<$entries['count']; $x++){
            if (!empty($entries[$x]['givenname'][0]) &&
                 !empty($entries[$x]['mail'][0]) &&
                 !empty($entries[$x]['samaccountname'][0]) &&
                 !empty($entries[$x]['sn'][0]) &&
                 'Shop' !== $entries[$x]['sn'][0] &&
                 'Account' !== $entries[$x]['sn'][0]){
                $ad_users[strtoupper(trim($entries[$x]['samaccountname'][0]))] = array('email' => strtolower(trim($entries[$x]['mail'][0])),'first_name' => trim($entries[$x]['givenname'][0]),'last_name' => trim($entries[$x]['sn'][0]));
            }
        }
    }
    ldap_unbind($ldap_connection); // Clean up after ourselves.
}

$message .= "Retrieved ". count($ad_users) ." Active Directory users\n";

Monday 16 June 2014

PHP: Generate PDF from php data retrieve from mysql

<?php

require('fpdf.php');
$fullname = "";
echo $contractno = $_REQUEST['contractno'];
echo $sname = $_REQUEST['sname'];
echo $fname = $_REQUEST['fname'];
echo $mi = $_REQUEST['mi'];
echo $dob = $_REQUEST['dob'];
echo $cpprefix = $_REQUEST['cpprefix'];
echo $cpnum = $_REQUEST['cpnum'];
echo $eadd = $_REQUEST['eadd'];

include ('connect.php');

$str = "SELECT contractno,sname,fname,mi,dob,applno,cpnum,eadd WHERE ((contractno='".$contractno."')AND (sname='".$sname."') AND (fname='".$fname."') AND (mi='".$mi."') AND (dob='".$dob."') AND (applno='".$applno.'"));
echo $result = mysql_query($str,$db);

class PDF extends FPDF
{

        function Header()
        {
            $this->Image('lifehead.jpg',25,10,150);
            $this->SetFont('Arial','B',12);
            $this->Cell(80);
            $this->Ln(20);
        }
}
$pdf=new PDF();
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetFont('Arial','','8');
//for($i=1;$i<=40;$i++)
//(x,y)
$pdf->SetXY(40,10);
$pdf->Cell(10,73,'Planholder', $sname, $fname, $mi);
//$pdf->SetXY(69,10);
//$pdf->Cell(10,73);
$pdf->SetXY(72,10); //TO INDENT
$pdf->Cell(10,73,'                                               Birthdate', $dob);
//$pdf->SetXY(136,10);
//$pdf->Cell(10,73,                                            'Contract Date');

$pdf->SetXY(40,10);
$pdf->Cell(10,95,'Contact number', $contractno);

$pdf->SetXY(42,10);
$pdf->Cell(10,110,'Application Number', $applno);
//$pdf->SetXY(69,10);
//$pdf->Cell(10,110);
$pdf->SetXY(72,10); //TO INDENT
$pdf->Cell(10,110,'                                              Email Address', $eadd);
//$pdf->SetXY(95,10); //TO INDENT
//$pdf->Cell(10,110,'                                              Contract Date');
$pdf->SetXY(40,10);
$pdf->Cell(10,177,'Conforme:');
$pdf->SetXY(48,10);
$pdf->Cell(10,195,'___________________');
$pdf->SetXY(56,10);
$pdf->Cell(10,202,'Planholder');
$pdf->SetXY(58,10);
$pdf->Cell(10,195,'                                              _______________');
$pdf->SetXY(66,10);
$pdf->Cell(10,202,'                                              Date');

$pdf->Output();

?>

Monday 4 February 2013

UK Post Code Distance Calculator using PHP/MySQ


UK Post Code Distance Calculator using PHP/MySQL

March 30th, 2008
Ever wondered how websites can tell you how far it is from one UK post code to another? This tutorial will tell you everything you need to know about adding this cool feature to your website using PHP and MySQL. Warning - although there is complex maths involved, no clever maths knowledge is required.

How it Works

The theory is simple - you need a database of post codes (only the first part of the post code) and their corresponding longitude/latitude values. When calculating the distance we are actually calculating the distance from one long/lat value to another (using rather clever maths).
To see a demo of the UK post code distance calculator in action please visit www.wroes.co.uk/about/stores.php.

Setting up the Database

Firstly, you require a database of post codes with their corresponding longitude/latitude values. Thankfully, this has already been compiled by easypeasy!which can be downloaded in CSV or SQL format. We’ve provided the files here for your convenience.
Download the UK post codes database in CSV/SQL: uk-postcodes.zip (95KB)
Create your database table using these files and your ready to begin. You will see that the database contains the following fields:
  • Post code (first part)
  • Postal town (Uk-Postcodes-Towns.csv file only)
  • X-coordinate (metres)
  • Y-coordinate (metres)
  • Latitude
  • Longitude

Getting the Latitude and Longitude Values

We’re assuming you have 2 full post codes to calculate the distance between. We only need the first part of the post code so we must trim them accordingly. The second part of the post code is always 3 characters (first part can either be 2, 3, or even 4 characters). So, we need to remove all spaces and then trim 3 characters off the end to give us the first part:
<?php

#Convert the post code to upper case and trim the variable
$postcode = strtoupper(trim($postcode));

#Remove any spaces
$postcode = str_replace(" ","",$postcode);

#Trim the last 3 characters off the end
$postcode_first = substr($postcode,0,strlen($postcode)-3);

?>
We have our 2 post codes now ready to compare. We need to query our database to obtain the latitude and longitude values for each post code. Use the following query, replacing with correct field/table names where appropriate:
“SELECT * FROM tblPostCode WHERE fldPostCode = ‘$postcode_first’ LIMIT 1″;
Check to ensure a post code was found and then assign the variables. You may wish to use something like this: (repeating the code for the second post code)
<?php

Does the post code exist?
if ($myrow["fldPostCode"] != ""){

#Assign variables
$code1_lat = $myrow["fldLatitude"];
$code1_long = $myrow["fldLongitude"];

}else{

#post code not found

}

?>

Calculating the Distance

This is where the complex mathematics starts. Don’t worry if you don’t understand this (we certainly don’t)! All you need for this to work is the latitude and longitude values for your 2 post codes (obtained from your database - above).
We’re going to create a function called getDistance() which takes all 4 lat/long values to return the distance in miles. If you’re after kilometres you can either perform the conversion from miles afterwards or modify the function slightly (see first comment below). This function does take into account the curvature of the Earth. Here’s the function:
<?php

function getDistance($lat1, $long1, $lat2, $long2){

#$earth = 6371; #km change accordingly
$earth = 3960; #miles

#Point 1 cords
$lat1 = deg2rad($lat1);
$long1= deg2rad($long1);

#Point 2 cords
$lat2 = deg2rad($lat2);
$long2= deg2rad($long2);

#Haversine Formula
$dlong=$long2-$long1;
$dlat=$lat2-$lat1;

$sinlat=sin($dlat/2);
$sinlong=sin($dlong/2);

$a=($sinlat*$sinlat)+cos($lat1)*cos($lat2)*($sinlong*$sinlong);

$c=2*asin(min(1,sqrt($a)));

$d=round($earth*$c);

return $d;

}

?>
We call the function with the following code:
<?php

#Returns the distance in miles
$distance = getDistance($code1_lat, $code1_long, $code2_lat, $code2_long);

?>

Limitations

The distance calculated is not the real distance if travelling on roads. It calculates a direct route as the crow flies. This is ideal for an approximate calculation, however, if you want more detailed calculations then you may wish to explore available mapping and route calculation software and APIs.
The exact same theory and code can be used when calculating distances from US Zip codes.

Note:

Assuming you are looking for the geographic distance, first you need to get the latitude and longitude of your two postcodes with the Google Maps server-side geocoding services as in the following example:
$url = 'http://maps.google.com/maps/geo?q=EC3M,+UK&output=csv&sensor=false';

$data = @file_get_contents($url);

$result = explode(",", $data);

echo $result[0]; // status code
echo $result[1]; // accuracy
echo $result[2]; // latitude
echo $result[3]; // longitude

Sunday 29 April 2012

Clock Stopwatch Timeout event



  1. Link the external javascript file into header
    <head>
    <script type="text/javascript" src="js/clock.js"></script>
    </head>
  2. load the function getSecs() from javascript file using setTimeout
    <body onload="window.setTimeout('getSecs()',1)">
  3. copy the following code into js/clock.js file:
    1.     
    2.     <!-- Begin
    3.     startday = new Date();
    4.     clockStart = startday.getTime();
    5.     
    6.     function initStopwatch() 
    7.     {
    8.         var myTime = new Date();
    9.         return((myTime.getTime() - clockStart)/1000);
    10.     }
    11.     function getSecs() 
    12.     {
    13.         var tSecs = Math.round(initStopwatch());
    14.         var iSecs = tSecs % 60;
    15.         var iMins = Math.round((tSecs-30)/60);
    16.         var sSecs ="" + ((iSecs > 9) ? iSecs :  + iSecs);
    17.         var sMins ="" + ((iMins > 9) ? iMins :  + iMins);
    18.         document.getElementById("timespent").value = sMins+":"+sSecs;
    19.         var duration = QueryString("Duration");
    20.         if(sMins>=duration)
    21.             window.location="http://localhost/eLearning/examNotice.php";
    22.         window.setTimeout('getSecs()',1000);
    23.         QueryString("CourseID");
    24.     }
    25.     // End -->
    26.     
    27.     function QueryString(key) 
    28.     {  
    29.         //Get the full querystring  
    30.         fullQs = window.location.search.substring(1);  
    31.         //Break it down into an array of name-value pairs  
    32.         qsParamsArray = fullQs.split("&");  
    33.         //Loop through each name-value pair and   
    34.         //return value in there is a match for the given key  
    35.         for (i=0;i<qsParamsArray.length;i++) {  
    36.         strKey = qsParamsArray[i].split("=");  
    37.             if (strKey[0] == key) {  
    38.                 return strKey[1];  
    39.             }  
    40.         }  
    41.     }
    42.      

MYSQL Database Command


  1. Delete empty or null record:
    • DELETE FROM `table name` WHERE Column_name is null;
  2. Two column unique key:
    1. ALTER TABLE MyTableADD UNIQUE KEY `my_unique_key` (`group_id`, `user_id`)

Monday 16 April 2012

How to resize multiple images in Photoshop


 I’m using Photoshop CS3:
  1. Once you have Photoshop opened, click on File > Scripts > Image Processor…(click here for a screenshot)
  2. In the Image Processor window, select the folder your images are in by clickingSelect Folder… (click here for a screenshot)
  3. You can save in the current folder, or choose a different folder. If you save in the current folder, it will create a new folder inside it called JPEG and put the processed images there. It will not overwrite your original images.
  4. File Type – I recommend saving as JPEG with a quality of 10. Your photos will be reduced in file size noticeably and will remain good quality.
  5. If you want to resize your images, which I recommend for posting them online, select Resize to Fit and enter the dimensions you want. Note: you need to keep the aspect ratio of your images. Make sure your original images are the same dimensions (they should be if they’re from the same camera) and divide the height and width separately by the same number to keep the ratio. My photos are originally 2592 x 1944, so I resize them to 1296 x 972. This is half of the original size, keeping the aspect ratio.
  6. Click Run and Photoshop will start processing your images. Wait for it to finish, then you can close it.
  7. http://www.wordplop.com/wp-content/uploads/2008/04/2.jpg

Monday 2 April 2012

Writing conclusion


Writing Conclusions

Conclusions are shorter sections of academic texts which usually serve two functions. The first is to summarise and bring together the main areas covered in the writing, which might be called "looking back"; and the second is to give a final comment or judgement on this. The final comment may also include making suggestions for improvement and speculating on future directions.
In dissertations and research papers, conclusions tend to be more complex and will also include sections on significance of the findings and recommendations for future work. Conclusions may be optional in research articles where consolidation of the study and general implications are covered in the Discussion section. However, they are usually expected in dissertations and essays.

 

Summarising the content

This paper has given an account of and the reasons for the widespread use of X ......
This essay has argued that X is the best instrument to ......
This assignment has explained the central importance of X in Y.
This dissertation has investigated ......

Restatement of aims (research)

This study set out to determine ......
The present study was designed to determine the effect of .......
In this investigation, the aim was to assess ......
The purpose of the current study was to determine ......
This project was undertaken to design ...... and evaluate .....
Returning to the hypothesis/question posed at the beginning of this study, it is now possible to state that .....

Summarising the findings (research)

This study has shown that ......
These findings suggest that in general ......
One of the more significant findings to emerge from this study is that .....
It was also shown that......
This study has found that generally .......
The following conclusions can be drawn from the present study ......
The relevance of X is clearly supported by the current findings.
This study/research has shown that ......
The second major finding was that ........
The results of this investigation show that .......
The most obvious finding to emerge from this study is that ......
X, Y and Z emerged as reliable predictors of ......
Multiple regression analysis revealed that the ......

Suggesting implications

The evidence from this study suggests that ......
The results of this study indicate that ......
The results of this research support the idea that .......
In general, therefore, it seems that ......
Taken together, these results suggest that ......
An implication of this is the possibility that ......
The findings of this study suggest that ......

Significance of the findings (research contribution)

The X that we have identified therefore assists in our understanding of the role of ......
These findings enhance our understanding of ......
This research will serve as a base for future studies and ......
The current findings add substantially to our understanding of ......
The current findings add to a growing body of literature on ......
The study has gone some way towards enhancing our understanding of ......
The methods used for this X may be applied to other Xs elsewhere in the world.
The present study, however, makes several noteworthy contributions to......
The empirical findings in this study provide a new understanding of ……
The findings from this study make several contributions to the current literature. First,……
The present study provides additional evidence with respect to ……
Taken together, these findings suggest a role for X in promoting Y.
The present study confirms previous findings and contributes additional evidence that suggests .... .
Whilst this study did not confirm X, it did partially substantiate .......

Limitations of the current study (research)

Finally, a number of important limitations need to be considered. First, ......
A number of caveats need to be noted regarding the present study.
The most important limitation lies in the fact that ......
The current investigation was limited by ......
The current study was unable to analyse these variables.
The current research was not specifically designed to evaluate factors related to ......
The current study has only examined ......
The project was limited in several ways. First, the project used a convenience sample that ......
However, with a small sample size, caution must be applied, as the findings might not be transferable to ......
The sample was nationally representative of X but would tend to miss people who were ......
A limitation of this study is that the numbers of patients and controls were relatively small.
Thirdly, the study did not evaluate the use of ......
However, these findings are limited by the use of a cross sectional design.
Our findings in this report are subject to at least three limitations. First, these data apply only to …..
An issue that was not addressed in this study was whether…..
One source of weakness in this study which could hare affected the measurements of was that ……
Several limitations to this pilot study need to be acknowledged.  The sample size is ......
The main weakness of this study was the paucity of ……

Recommendations for further work (research)

This research has thrown up many questions in need of further investigation.
Further work needs to be done to establish whether ......
It is recommended that further research be undertaken in the following areas:
Further experimental investigations are needed to estimate ......
What is now needed is a cross-national study involving ......
More broadly, research is also needed to determine .....
It is suggested that the association of these factors is investigated in future studies.
Further research might explore/investigate ......
Further research in this field/regarding the role of X would be of great help in .......
Further investigation and experimentation into X is strongly recommended.
A number of possible future studies using the same experimental set up are apparent.
It would be interesting to assess the effects of ......
More information on X would help us to establish a greater degree of accuracy on this matter.
If the debate is to be moved forward, a better understanding of ...... needs to be developed.
I suggest that before X is introduced, a study similar to this one should be carried out on .....
These findings provide the following insights for future research: .....
Considerably more work will need to be done to determine ......
Future trials should assess a full selective decontamination regimen including
More research is needed to better understand when implementation ends and .......
It would be interesting to compare experiences of individuals within the same … group.
A further study could assess …...
A future study investigating …... would be very interesting.
The issue of X is an intriguing one which could be usefully explored in further research.
Future research should therefore concentrate on the investigation of …...
Large randomised controlled trials could provide more definitive evidence.

Implications/recommendations for practice or policy

These findings suggest several courses of action for ......
An implication of these findings is that both X and Y should be taken into account when ......
The findings of this study have a number of important implications for future practice.
There is, therefore, a definite need for ......
There are a number of important changes which need to be made.
Another important practical implication is that ......
Moreover, more X should be made available to ......
Other types of X could include : a), b). ......
Unless governments adopt X, Y will not be attained.
This information can be used to develop targetted interventions aimed at ......
A reasonable approach to tackle this issue could be to ......
Taken together, these findings do not support strong recommendations to ......