Monday, 3 February 2014

Read a File line by line

Read Line From File

<?php/**
 *
 * Read a line number from a file
 *
 * @param    string    $file    The path to the file
 * @param    int    $line_num    The line number to read
 * @param    string    $delimiter    The character that delimits lines
 * @return    string    The line that is read
 *
 */
function readLine($file$line_num$delimiter="\n")
{
    
/*** set the counter to one ***/
    
$i 1;

    
/*** open the file for reading ***/
    
$fp fopen$file'r' );

    
/*** loop over the file pointer ***/
    
while ( !feof $fp) )
    {
        
/*** read the line into a buffer ***/
        
$buffer stream_get_line$fp1024$delimiter );
        
/*** if we are at the right line number ***/
        
if( $i == $line_num )
        {
            
/*** return the line that is currently in the buffer ***/
            
return $buffer;
        }
        
/*** increment the line counter ***/
        
$i++;
        
/*** clear the buffer ***/
        
$buffer '';
    }
    return 
false;
}
?>
<?php/*** make sure the file exists ***/$file 'my_file.txt';

if( 
file_exists$file ) && is_readable$file ) )
{
    echo 
readLine($file6);
}
else
{
    echo 
"Cannot read from $file";
}
?>
On PHP 5 and later versions
<?php/*** the file to read ***/$file 'foo.txt';

        
/**
 *
 * Read a line number from a file
 *
 * @param    string    $file    The path to the file
 * @param    int    $line_num    The line number to read
 * @return    string    The line that is read
 *
 */
function readLine$file$line_number )
{
        
/*** read the file into the iterator ***/
        
$file_obj = new SplFileObject$file );

        
/*** seek to the line number ***/
        
$file_obj->seek$line_number );

        
/*** return the current line ***/
        
return $file_obj->current();
}

echo 
readLine$file345678 );?>

Calculate Age With PHP

Checking dates in PHP can be problematic as PHP primarily concerns itself with date manipulation which revolves around unix timestamps. This is a good thing, mostly. Unix timestamps however, have not concept of leap years, thus it is difficult, though not impossible, to get an accurate date calculation from them. When dates need to be accurate for legal reasons, it is vital that the leap years are considered. Here several solutions are put forward, each nicer than the previous.

With strtotime()

<?php
/*** make sure this is set ***/date_default_timezone_set('Europe/London');
/**
 *
 * Get the age of a person in years at a given time
 *
 * @param       int     $dob    Date Of Birth
 * @param       int     $tdate  The Target Date
 * @return      int     The number of years
 *
 */
function getAge$dob$tdate )
{
        
$age 0;
        while( 
$tdate $dob strtotime('+1 year'$dob))
        {
                ++
$age;
        }
        return 
$age;
}
?>
<?php
/*** a date before 1970 ***/$dob strtotime("april 20 1961");
/*** another date ***/$tdate strtotime("june 2 2009");
/*** show the date ***/echo getAge$dob$tdate );
?>

Using the DateTime Class

The PHP DateTime class allow a little neater code by providing an Object Oriented interface to date functions. By passing a DateInterval object to the DateTime class the DateTime object can be increment 1 year on each iteration until it reaches the target date. The DateTime::add() method requires PHP >= 5.3.
<?php
/*** set the default timezone ***/date_default_timezone_set('Europe/London');
/**
 *
 * Get the age of a person in years at a given time
 *
 * @param       int     $dob    Date Of Birth
 * @param       int     $tdate  The Target Date
 * @return      int     The number of years
 *
 */
function getAge$dob$tdate )
{
        
$dob = new DateTime$dob );
        
$age 0;
        
$now = new DateTime$tdate );
        while( 
$dob->add( new DateInterval('P1Y') ) < $now )
        {
                
$age++;
        }
        return 
$age;
}
?>
<?php
/*** a date before 1970 ***/$dob "April 20 1961";
/*** another date ***/$tdate "21-04-2009";
/*** show the date ***/echo getAge$dob$tdate );
?>

PHP Date Validation

PHP provides many date manipulation devices and an entire suite of date functionality with the datetime class. However, this does not address date validation, that is, what format a date is received in. The PHP strtotime() function will accept many forms of dates in most human readable strings. The issue with strtotime is that there is no way to account for differing date formats, eg: 12/05/2010. Depending on what country a user is from, this date could have several meanings, such as which is the month, and which is day field. By splitting the date into its respective fields, each segment can be checked with the PHP checkdate function. The function below validates a date by splitting the date in year, month, day and using these as arguments to checkdate.

<?php
    /**
    *
    * Validate a date
    *
    */
    function validateDate( $date, $format='YYYY-MM-DD')
    {
        switch( $format )
        {
            case 'YYYY/MM/DD':
            case 'YYYY-MM-DD':
            list( $y, $m, $d ) = preg_split( '/[-\.\/ ]/', $date );
            break;

            case 'YYYY/DD/MM':
            case 'YYYY-DD-MM':
            list( $y, $d, $m ) = preg_split( '/[-\.\/ ]/', $date );
            break;

            case 'DD-MM-YYYY':
            case 'DD/MM/YYYY':
            list( $d, $m, $y ) = preg_split( '/[-\.\/ ]/', $date );
            break;

            case 'MM-DD-YYYY':
            case 'MM/DD/YYYY':
            list( $m, $d, $y ) = preg_split( '/[-\.\/ ]/', $date );
            break;

            case 'YYYYMMDD':
            $y = substr( $date, 0, 4 );
            $m = substr( $date, 4, 2 );
            $d = substr( $date, 6, 2 );
            break;

            case 'YYYYDDMM':
            $y = substr( $date, 0, 4 );
            $d = substr( $date, 4, 2 );
            $m = substr( $date, 6, 2 );
            break;

            default:
            throw new Exception( "Invalid Date Format" );
        }
        return checkdate( $m, $d, $y );
    }


   echo validateDate( '2007-04-21' ) ? 'good'. "\n" : 'bad' . "\n";
        echo validateDate( '2007-21-04', 'YYYY-DD-MM' )  ? 'good'. "\n" : 'bad' . "\n";
        echo validateDate( '2007-21-04', 'YYYY/DD/MM' )  ? 'good'. "\n" : 'bad' . "\n";
        echo validateDate( '21/4/2007', 'DD/MM/YYYY' )  ? 'good'. "\n" : 'bad' . "\n";
        echo validateDate( '4/21/2007', 'MM/DD/YYYY' )  ? 'good'. "\n" : 'bad' . "\n";
        echo validateDate( '20070421', 'YYYYMMDD' )  ? 'good'. "\n" : 'bad' . "\n";
        echo validateDate( '04212007', 'YYYYDDMM' )  ? 'good'. "\n" : 'bad' . "\n";

?>

Verify Age limit With PHP Datetime

Verify Age Limit With PHP Datetime

This small script shows how to check a person is of a given age. Buy using the PHP DateTime class, php is able to account for dates at a system level.

<?php/**
*
* Check minimum age. Defaults to 18 years
*
*/
function validate_age$dob$min_age=18 ){
        
$dob     = new DateTime$dob );
        
$min_age = new DateTime'now - ' $min_age 'years' );
        return 
$dob <= $min_age;
}
// the person must be at least 21 years of age$age 21;// persons date of birth (dd-mm-yyyy)$dob '20-4-1981';
if( 
validate_age$dob$age ) === false ){
    echo 
'Person is not 21 years old';
}else{
    echo 
'Person is 21 or over';
}
?>

Wednesday, 18 December 2013

PHP Get a part of an array

Extract a slice of the array
Get a part of an array


<?php
$input 
= array("a""b""c""d""e");
$output array_slice($input2);      // returns "c", "d", and "e"$output array_slice($input, -21);  // returns "d"$output array_slice($input03);   // returns "a", "b", and "c"

// note the differences in the array keys
print_r(array_slice($input2, -1));print_r(array_slice($input2, -1true));?>

array_slice — Extract a slice of the array

Description ¶

array array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys= false ]] )
array_slice() returns the sequence of elements from the array array as specified by the offset and lengthparameters.

Parameters ¶

array
The input array.
offset
If offset is non-negative, the sequence will start at that offset in the array. If offset is negative, the sequence will start that far from the end of the array.
length
If length is given and is positive, then the sequence will have up to that many elements in it. If the array is shorter than the length, then only the available array elements will be present. If length is given and is negative then the sequence will stop that many elements from the end of the array. If it is omitted, then the sequence will have everything from offset up until the end of the array.
preserve_keys
Note that array_slice() will reorder and reset the numeric array indices by default. You can change this behaviour by setting preserve_keys to TRUE.

Return Values ¶

Returns the slice.

PHP sort a multi dimensional array with values


array_multisort — Sort multiple or multi-dimensional arrays

We have an array of rows, but array_multisort() requires an array of columns, so we use the below code to obtain the columns, then perform the sorting.

$resultData = array(0=>array('name'=>'test1', 'email'=> 'test1@test.com', 'phone'=>990000001),
                               1=>array('name'=>'test2', 'email'=> 'test2@test.com', 'phone'=>990000002),  
                               2=>array('name'=>'test3', 'email'=> 'test3@test.com', 'phone'=>990000003),
foreach ($resultData as $key => $row) {
     $mid[$key]  = $row['name'];
}
array_multisort($mid, SORT_DESC, $resultData);
 

Friday, 6 December 2013

E-Mail Attachments With PHP's mail() Function

Below is a full working example of how to include one or more attachments to an outbound e-mail utilizing PHP's mail() function. Usage Example


<?php
$to = 'test@example.com';
$from = 'source@example.com';
$subject = 'See Attachments';
$message = 'Please review the following attachments.';

// Define a list of FILES to send along with the e-mail. Key = File to be sent. Value = Name of file as seen in the e-mail.
$attachments = array(
 '/tmp/WEDFRTS' => 'first-attachment.png',
 '/tmp/some-other-file' => 'second-attachment.png'
);

// Define any additional headers you may want to include
$headers = array(
 'Reply-to' => 'source@example.com',
 'Some-Other-Header-Name' => 'Header Value'
);

$status = mailAttachments($to, $from, $subject, $message, $attachments, $headers);
if($status === True) {
 print 'Successfully mailed!';
} else {
 print 'Unable to send e-mail.';
}


<?php
function mailAttachments($to, $from, $subject, $message, $attachments = array(), $headers = array(), $additional_parameters = '') {
 $headers['From'] = $from;

 // Define the boundray we're going to use to separate our data with.
 $mime_boundary = '==MIME_BOUNDARY_' . md5(time());

 // Define attachment-specific headers
 $headers['MIME-Version'] = '1.0';
 $headers['Content-Type'] = 'multipart/mixed; boundary="' . $mime_boundary . '"';

 // Convert the array of header data into a single string.
 $headers_string = '';
 foreach($headers as $header_name => $header_value) {
  if(!empty($headers_string)) {
   $headers_string .= "\r\n";
  }
  $headers_string .= $header_name . ': ' . $header_value;
 }

 // Message Body
 $message_string  = '--' . $mime_boundary;
 $message_string .= "\r\n";
 $message_string .= 'Content-Type: text/plain; charset="iso-8859-1"';
 $message_string .= "\r\n";
 $message_string .= 'Content-Transfer-Encoding: 7bit';
 $message_string .= "\r\n";
 $message_string .= "\r\n";
 $message_string .= $message;
 $message_string .= "\r\n";
 $message_string .= "\r\n";

 // Add attachments to message body
 foreach($attachments as $local_filename => $attachment_filename) {
  if(is_file($local_filename)) {
   $message_string .= '--' . $mime_boundary;
   $message_string .= "\r\n";
   $message_string .= 'Content-Type: application/octet-stream; name="' . $attachment_filename . '"';
   $message_string .= "\r\n";
   $message_string .= 'Content-Description: ' . $attachment_filename;
   $message_string .= "\r\n";

   $fp = @fopen($local_filename, 'rb'); // Create pointer to file
   $file_size = filesize($local_filename); // Read size of file
   $data = @fread($fp, $file_size); // Read file contents
   $data = chunk_split(base64_encode($data)); // Encode file contents for plain text sending

   $message_string .= 'Content-Disposition: attachment; filename="' . $attachment_filename . '"; size=' . $file_size.  ';';
   $message_string .= "\r\n";
   $message_string .= 'Content-Transfer-Encoding: base64';
   $message_string .= "\r\n\r\n";
   $message_string .= $data;
   $message_string .= "\r\n\r\n";
  }
 }

 // Signal end of message
 $message_string .= '--' . $mime_boundary . '--';

 // Send the e-mail.
 return mail($to, $subject, $message_string, $headers_string, $additional_parameters);
}