Recently I was playing around with the SSL configurations within my PHP Wrapper Library for Harvest API and noticed that I was getting an access error. As it turns out cURL was behaving properly and trying to verify the SSL Certificate of the server, and as no CA Certificate was associated with the library it threw an exception and would fail. Doing some research on the subject I found myself with 2 viable options either download the server certificate and pass that along with my library or simply turn of validation of the SSL certificate. In my case validation is not important so I decided to turn it off.

The CURLOPT_SSL_VERIFYPEER option

One of the standard cURL options defined in PHP is CURLOPT_SSL_VERIFYPEER. This option is used to specify if when the url is SSL enabled if the certificate should be verified. To disable it simply set the option to false for the cURL instance.

$ch = curl_init();
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );

If you are providing a data feed from your own server instead of accessing one provided by a 3rd party you may want to validate the certificate. In those cases you can find a useful tutorial on how to do so over at unit step.

, , ,

Most if not all PHP developers are aware of the getdate function and how it returns an associated array of the current time and date.

$current_time= getdate();
print_r( $current_time );

Output Format:

Array
(
    [seconds] => 40
    [minutes] => 58
    [hours]   => 21
    [mday]    => 17
    [wday]    => 2
    [mon]     => 6
    [year]    => 2003
    [yday]    => 167
    [weekday] => Tuesday
    [month]   => June
    [0]       => 1055901520
)

However this function is not very useful when you want perform Date Comparisons and Manipulations. Instead you will want to use the DateTime object of PHP.

The DateTime Class

The DateTime Object by default gets instantiated to the current time when being constructed. If however you want to instantiate it at a different date you can pass in a string representation of the date.

$date = new DateTime( ); // same as new DateTime( "now" );
$date2 = new DateTime( '2010-01-01');

It is important to remember that you can use any string in the DateTime constuctor that you would use in the strtotime function. This means you could instantiate the date and time of last Monday, next Friday and etc.

$date = new DateTime( "last Monday" );
$date2 = new DateTime( "next Friday" );

Manipulating Dates

To modify your DateTime objects you can use the add and sub methods that utilize DateInterval objects for representing amounts or you can use the modify method which takes a string as a parameter. I personally find the modify method easier to utilize.

$date = new DateTime();
$date->add( new DateInterval( "P5D" ) );
$date->modify( "+5 days" );

Comparing Date Objects

Comparing Dates is now easy as the DateTime object supports basic equality and comparison functions (==, <, >, etc ). So if you want to check if a date is before another you would simply:

$date = new DateTime( "2003-12-17" );
$date2 = new DateTime( "2005-6-19" );
if( $date < $date2 ) {
  // additional logic
}

Resources

, , , , , ,

Introducing the MDBitz Security and Authentication Framework for PHP. I have always had an issue with any PHP Security or Authentication Framework or library that I have utilized in past projects. That is why I am developing my own comprehensive Security and Authentication Framework.

I am building this framework from the ground up keeping all security risks and precautions in mind, from Session Hijacking, SQl-Injection, and Shared Hosting Vulnerabilities. The project currently is still in its infancy but I am actively working to make it the one source for easily securing your website and content without forcing you to learn a new system to work in.

Features

User Authentication & Timeout

The MDSecurity contains the capability to provide authentication of the user’s IP Address, Browser Agent, and Max Attempts. These are fully configurable allowing you to easily determine what you want to verify. In addition MDSecurity allows you to set both a session timeout and a request timeout allowing you to define how long a session is valid for and when to invalidate the session upon inactivity of the user.

Session Handlers

The MDSecurity framework contains built in Session Handlers that you can configure to modify how PHP saves your users’ session information. Currently you can specify a new file path, or configure your session information to be saved into a database.

Encryption

Built into the library are Encryption functionality that can be utilized both at the Client side (JavaScript) and Server side (PHP). The supported encryption methods are Base 64, md5, sha1, sha256.

For full details on the PHP MDBitz Security and Authentication Framework (MDSecurity) please visit the official site

, , , ,

PHP Database Objects PDOs for short is a light-weight data abstraction layer for PHP. What this means is that it allows you to use an interface for performing data manipulations instead of using db specify functions such as mysql_query. So that if you needed to migrate to a different database you would not have to rewrite your code instead you simply change the connection driver. In addition to portability of the code you also protect against SQL-Injection as the prepare method will call the underlying quote method of the specific driver so that your input gets escaped properly.

Connecting to a database with PDO

To connect to a database you need to instantiate the PDO object. The constructor espects 3 parameters: connection string, username, and password. The connection string specifies the driver, host, and optional database or schema to connect to and has the following format: driver:host=hostname:port;dbname=database

$pdo = new PDO("mysql:host=localhost;dbname=mysql", "username", "password");

When establishing a connection if there is an error connecting an exception will be thrown. In this thrown exception the stack trace will reveal the username and password used to access the server. It is very important that you capture these exceptions and either throw an excpetion that does not share this information or define your own handlers. Below is a full example for connection to a databse with PDO and handling the Exception if the connection fails.

$driver = "mysql";
$host_name = 'localhost';
$user_name = 'root';
$password = 'root';
$db_name = 'MY_DB';
 
try {
    $db = new PDO("$driver:host=$host_name;dbname=$db_name", $user_name, $password);
    echo 'Connected to database';
}
catch(PDOException $e) {
    echo $e->getMessage();
}

Preparing and Executing a Query

There are 2 main ways to prepare queries when using PDOs. The first method is to define your sql with ? placeholders for variables.

$sql = 'SELECT name, phone_num, active
    FROM Users
    WHERE name like ?';
$statement = $pdo>prepare( $sql );

The second option is define the query with named variables by use of the : character. In the below query we defined the named variable :name.

$sql = 'SELECT name, phone_num, active
    FROM Users
    WHERE name like :name';
$statement = $pdo>prepare( $sql );

The PDOStatement object is returned from the prepare function. The next step will be to execute the statements with your variables. If you used the ? method you simply pass an array of variables.

$statement->execute(array('A%'));

While if you used the named parameter way you will pass in an assocaited array of the variables

$statement->execute( array( ":name" => "A%" ) );

Now that you have executed the query me can fetch the results in various different methods.

Fetching and Using the Result

Now that you have executed your query you want your results right? To do this you utilize either the fetch or fetchAll method. Which will return the next result row or an array of all the rows. You can even specify how you want the data returned as: FETCH_ASSOC returns an associated array by the column name and FETCH_BOTH returns it by both the index of the column and the name.

$result = $sth->fetch(PDO::FETCH_ASSOC);
$result = $sth->fetchAll(PDO::FETCH_BOTH);

Now that you have the data simply use it however you need in your application. If you returned it as an associated array you can simply get the property.

echo $result->name;

Closing your Connection

To close your connection you simply need to set all your references to the PDO object to null. If you fail to close the connection it will be closed automatically upon the completion of the script. Good practice is to close it once you are finished.

$pdo = null;

Resources

In PHP we are provided with an integrated logging system for outputting info, warnings, and errors. This is accomplished by use of the syslog function. This function outputs the specified message at the specified priority level to the default system logger. If you want to have it output the log message to a user defined log handler then you simply need to utilize the openlog and closelog functions before and after respectively before you log a message.

Example Log Statements

syslog(LOG_ERR, "message to be logged as an error");
openlog("AppLog", LOG_PERROR, LOG_LOCAL0);
 
// code
 
syslog(LOG_WARNING, "warning priority sample log message");
 
// code
 
closelog();

Resources

, , , , ,