File Encryption/Decryption With PHP


Often we find the need to protect certain files so that if they are ever subject to unauthorized accessed, the contents can be safe. Encrypting info in a database is pretty straightforward, however encrypting files in a directory is not always. Here are two functions to encrypt and decrypt whole files using PHP and Mcrypt.

function encrypt_file($source,$destination,$passphrase,$stream=NULL) {
	// $source can be a local file...
	if($stream) {
		$contents = $source;
	// OR $source can be a stream if the third argument ($stream flag) exists.
	}else{
		$handle = fopen($source, "rb");
		$contents = fread($handle, filesize($source));
		fclose($handle);
	}
 
	$iv = substr(md5("\x1B\x3C\x58".$passphrase, true), 0, 8);
	$key = substr(md5("\x2D\xFC\xD8".$passphrase, true) . md5("\x2D\xFC\xD9".$passphrase, true), 0, 24);
	$opts = array('iv'=>$iv, 'key'=>$key);
	$fp = fopen($destination, 'wb') or die("Could not open file for writing.");
	stream_filter_append($fp, 'mcrypt.tripledes', STREAM_FILTER_WRITE, $opts);
	fwrite($fp, $contents) or die("Could not write to file.");
	fclose($fp);
 
}

Below is the function to perform decryption.

function decrypt_file($file,$passphrase) {
 
	$iv = substr(md5("\x1B\x3C\x58".$passphrase, true), 0, 8);
	$key = substr(md5("\x2D\xFC\xD8".$passphrase, true) .
	md5("\x2D\xFC\xD9".$passphrase, true), 0, 24);
	$opts = array('iv'=>$iv, 'key'=>$key);
	$fp = fopen($file, 'rb');
	stream_filter_append($fp, 'mdecrypt.tripledes', STREAM_FILTER_READ, $opts);
 
	return $fp;
}

Encryption Example:

encrypt_file('/path/to/source/file', '/path/to/destination/file', 'MySuperSecretPassword');

Decryption Example:

// Output to inline PDF
$decrypted = decrypt_file('/path/to/file','MySuperSecretPassword');
header('Content-type: application/pdf');
fpassthru($decrypted);
 
// Output to a string for email attachments, etc.
$decrypted = decrypt_file('/path/to/file','MySuperSecretPassword');
$contents = stream_get_contents($fp);

(Just to make sure, you need to change $passphrase into your very own password and keep it secret.)

Source: Monkey Logic

Dynamically using Iframe Maps with PHP GeoCoding and Google Maps API


Dynamically using Iframe Maps with PHP GeoCoding and Google Maps API

Dynamically using Iframe Maps with PHP GeoCoding and Google Maps API

In a recent project, EnlightenMental Productions needed to dynamically display a Google Map Iframe code based on the user’s current selection.  Each time an address was chosen, the <iframe> map would update to display the current address selected.

In order to do this, we needed to query the Google Maps API to get the longitude and latitude based on an address (1234 Somewhere Street City State Zipcode).  Using an article we found online (www.timshowers.com) and making a few minor adjustments, we created a basic PHP script that will generate a dynamic <iframe>.

<?php // First, setup the variables you will use on your
// Your Iframe will need a Width and Height set
// as well as the address you plan to Iframe
// Don't forget to get a Google Maps API key

$latitude = '';
$longitude = '';
$iframe_width = '400px';
$iframe_height = '400px';
$address = 'ENTER YOUR ADDRESS HERE';
$address = urlencode($address);
$key = "YOUR GOOGLE MAPS API KEY";
$url = "http://maps.google.com/maps/geo?q=".$address."&output=json&key=".$key;
$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER,0);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]); // Comment out the line below if you receive an error on certain hosts that have security restrictions
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

$data = curl_exec($ch);
curl_close($ch);
$geo_json = json_decode($data, true);

// Uncomment the line below to see the full output from the API request
// var_dump($geo_json);

// If the Json request was successful (status 200) proceed
if ($geo_json['Status']['code'] == '200') {

$latitude = $geo_json['Placemark'][0]['Point']['coordinates'][0];
$longitude = $geo_json['Placemark'][0]['Point']['coordinates'][1]; ?>

<iframe width="<?php echo $iframe_width; ?>" height="<?php echo $iframe_height; ?>" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="

http://maps.google.com/maps

?f=q
&source=s_q
&hl=en
&geocode=
&q=<?php echo $address; ?>
&aq=0
&ie=UTF8
&hq=
&hnear=<?php echo $address; ?>
&t=m
&ll=<?php echo $longitude; ?>,<?php echo $latitude; ?>
&z=12
&iwloc=
&output=embed"> </ iframe >

<?php

} else { echo "<p>No Address Available</p>";}

?>

The above code will output an Iframe into your site and use the dynamic address you’ve selected.

Simple jQuery tabs


This tutorial looks into creating a really simple tabbed interface using just plain HTML and CSS with the functionality and interface manipulated using jQuery. Tabbed interfaces are great for maximizing the amount of space you have on your site.

Lets take a look at whats going on. We start with the document ready function. The first line of code hides all the tab containers, we then show the first one, and add the class ‘active’ to the first ‘li’ in the tab headers. Then whenever a tab is clicked it simply remove the class ‘active’ from all the tabs, then add it to the tab thats been clicked. We then take the href from the clicked tab and show it. Simple as that! You can get the complete file by grabbing the download and the demos at the bottom also.

The Code

$(document).ready(function(){
$('#tabs div').hide();
$('#tabs div:first').show();
$('#tabs ul li:first').addClass('active');

$('#tabs ul li a').click(function(){
$('#tabs ul li').removeClass('active');
$(this).parent().addClass('active');
var currentTab = $(this).attr('href');
$('#tabs div').hide();
$(currentTab).show();
return false;
});
});

The HTML

<div id="tabs">
<ul>
<li><a href="#tab-1">This is Tab 1</a></li>
     <li><a href="#tab-2">Tab Two</a></li>
     <li><a href="#tab-3">Tab Three</a></li>
     <li><a href="#tab-4">Tab Four</a></li>
   </ul>   <div id="tab-1">
     <h3>This is a really simple tabbed interface</h3>
     <p><img src="/jquery-gallery/images/t1.png" width="120" height="120" class="thumbs"/> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur enim. Nullam id ligula in nisl tincidunt feugiat. Curabitur eu magna porttitor ligula bibendum rhoncus. Etiam dignissim. Duis lobortis porta risus. Quisque velit metus, dignissim in, rhoncus at, congue quis, mi. Praesent vel lorem. Suspendisse ut dolor at justo tristique dapibus. Morbi erat mi, rutrum a, aliquam nec, mattis semper, leo. Maecenas blandit risus vitae quam. Vivamus ut odio. Pellentesque mollis arcu nec metus. Nullam bibendum scelerisque turpis. Aliquam erat volutpat. <br/>
        </p>
   </div>   <div id="tab-2">
     <h3>Tab 2</h3>
     <p><img src="/jquery-gallery/images/t2.png" width="120" height="120" class="thumbs"/> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur enim. Nullam id ligula in nisl tincidunt feugiat. Curabitur eu magna porttitor ligula bibendum rhoncus. Etiam dignissim. Duis lobortis porta risus. Quisque velit metus, dignissim in, rhoncus at, congue quis, mi. Praesent vel lorem. Suspendisse ut dolor at justo tristique dapibus. Morbi erat mi, rutrum a, aliquam nec <br/>
        </p>
   </div>

   <div id="tab-3">
     <h3>Tab 2</h3>
     <p><img src="/jquery-gallery/images/t2.png" width="120" height="120" class="thumbs"/> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur enim. Nullam id ligula in nisl tincidunt feugiat. Curabitur eu magna porttitor ligula bibendum rhoncus. Etiam dignissim. Duis lobortis porta risus. Quisque velit metus, dignissim in, rhoncus at, congue quis, mi. Praesent vel lorem. Suspendisse ut dolor at justo tristique dapibus. Morbi erat mi, rutrum a, aliquam nec <br/>
        </p>
   </div>

   <div id="tab-4">
     <h3>Tab 2</h3>
     <p><img src="/jquery-gallery/images/t2.png" width="120" height="120" class="thumbs"/> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur enim. Nullam id ligula in nisl tincidunt feugiat. Curabitur eu magna porttitor ligula bibendum rhoncus. Etiam dignissim. Duis lobortis porta risus. Quisque velit metus, dignissim in, rhoncus at, congue quis, mi. Praesent vel lorem. Suspendisse ut dolor at justo tristique dapibus. Morbi erat mi, rutrum a, aliquam nec <br/>
        </p>
   </div>

 </div>

Simple pagination system in your WordPress plugins


May be you are developing a plugin or a theme and it has something to do with handing some pagination of your custom tables data. Here’s how we can simply manage it, I am not going to build all the admin panel stuffs, but just showing you the process.

Step 1:

Lets get the page number from the url query string. If we don’t find anything, we’ll set the page number to 1.

$pagenum = isset( $_GET['pagenum'] ) ? absint( $_GET['pagenum'] ) : 1;

Step 2:

Now we need to set per page entry limit and the page offset. We will use the limit and offset to get data from our MySQL query. If you are confused about the offset, may be you’ve seen it on PHPMyAdmin like this: "SELECT * FROM `table_name` LIMIT 0, 10". Here, we are getting the first 10 entries from our database. If we want get the next 10 entries, our limit will be "LIMIT 10, 10". So the first digit for the limit is the offset. It tells us from where we’ll get our next entries.

$limit = 10;
$offset = ( $pagenum - 1 ) * $limit;

So, by this two lines we are setting the limit and our offset dynamically.

Step 3:

Now we need to get the entries from our database table with the help of our limit and offset variable and need to show them as you like, may be in a table.

$entries = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}table_name LIMIT $offset, $limit");

So, now if you change the url “pagenum” paramater from your browser, you can see that we are getting the entries by our page number. So it’s like we have completed our pagination system :D

Step 4:

As we have completed the pagination system working, we just need to show the pagination links now and we’ll be done. WordPress gives us a nice function "paginate_links" to generate a cool pagination navigation link.
At first, we need to get the count of total number of entries in our table and calculate how many pages will need to show the whole entries.

$total = $wpdb->get_var( "SELECT COUNT(`id`) FROM {$wpdb->prefix}table_name" );
$num_of_pages = ceil( $total / $limit );

Now, we can use that nifty function paginate_links to generate our pagination links.

$page_links = paginate_links( array (
    'base'=> add_query_arg( 'pagenum', '%#%' ),
    'format'=> '',
    'prev_text'=> __( '&laquo;', 'aag' ),
    'next_text'=> __( '&raquo;', 'aag' ),
    'total'=> $total,
    'current'=> $pagenum
) );
if( $page_links ) {
    echo'<div class="tablenav"><div class="tablenav-pages" style="margin: 1em 0">'. $page_links. '</div></div>';
}

So, we are passing our current page number and total number of pages to that function and we are getting a nice and cool pagination system.

Here’s a sample code for generating a table with data from your posts table.

<?php
global $wpdb;
$pagenum = isset( $_GET['pagenum'] ) ? absint( $_GET['pagenum'] ) : 1;
$limit = 5;

$offset = ( $pagenum - 1 ) * $limit;
$entries = $wpdb->get_results( "SELECT * FROM {$wpdb->prefix}posts LIMIT $offset, $limit" );
echo '<div class="wrap">';
?>

<table class="widefat">
    <thead>
        <tr>
            <th scope="col" class="manage-column column-name" style="" >Post Title</th>
            <th scope="col" class="manage-column column-name" style="">Date</th>
        </tr>
    </thead>

    <tfoot>
        <tr>
            <th scope="col" class="manage-column column-name" style="" >Post Title</th>
            <th scope="col" class="manage-column column-name" style="">Date</th>
        </tr>
    </tfoot>

    <tbody>
        <?php if( $entries ) { ?>

            <?php
            $count = 1;
            $class = '';
            foreach( $entries as $entry ) {
                $class = ( $count % 2 == 0 ) ? ' class="alternate"' : '' ;
            ?>

            <tr<?php echo $class; ?>>
                <td><?php echo $entry->post_title; ?></td>
                <td><?php echo $entry->post_date; ?></td>
            </tr>

            <?php
                 $count++;
             }
            ?>

        <?php } else { ?>
        <tr>
            <td colspan="2" >No posts yet</td>
        </tr>
        <?php } ?>
    </tbody>
</table>

<?php

$total = $wpdb->get_var( "SELECT COUNT(`id`) FROM {$wpdb->prefix}posts" );
$num_of_pages = ceil( $total / $limit );
$page_links = paginate_links( array(
    'base' => add_query_arg( 'pagenum', '%#%' ),
    'format' => '',
    'prev_text' => __( '&laquo;', 'aag' ),
    'next_text' => __( '&raquo;', 'aag' ),
    'total' => $num_of_pages,
    'current' => $pagenum
) );

if( $page_links ) {
    echo '<div class="tablenav"><div class="tablenav-pages" style="margin: 1em 0">' . $page_links . '</div></div>';
}
echo'</div>';

?>

Hope this solution will help you.

Why use PHP?



Using PHP scripting and MySQL™ database enables programmers to create applications
that will run on just about any computer, regardless of operating system. PHP has thousands of programming functions to facilitate
almost any task.

If the computer can run web server software, the PHP / MySQL™ application is portable
across operating systems and environments … PC, Mac, Linux, Unix, Windows, Lindows, Internet,
Intranet, etc. This means I can develop a project on my Windows PC, and send it to my friend in
Slovakia who can run it on his Linux box.

PHP / MySQL™ is most often used to create dynamic web sites. On
this web site, one script drives about 60 pages of content. Additional scripts are used here to
process form data … but that too could be done through the main script using included files.

PHP / MySQL™ projects include forums or communities, organizers,
project management tools, calendars, shopping carts, mailing lists, and all sorts of useful
applications. Source code for many open source projects is free, while advanced projects often
require a registration fee for commercial use.

Data can be exported from MySQL™ for use in spreadsheets or databases on your PC.
Similarly, data residing in existing PC spreadsheets and databases can be imported to an online
database. The portability of data opens up all sorts of uses, especially for workgroups and for
those who need to access data from both home and work.

Tips for using PHP with MySQL™

Most web hosts suck. Start your hosting experience with a proven and reliable web host that already hosts millions of domains, offers cPanel®, and regularly upgrades phpMyAdmin. If a web host offers an old
version of PHP and an old version of phpMyAdmin they
probably don’t care if the system runs at peak performance, nor whether users have current
software.

Never use a hyphen (-) in the name of a MySQL™ database, table, or column name, even if hyphens are
technically allowed. Doing so will crash your project with MySQL™ errors when when a double quoted PHP string interprets the hyphen as a minus sign.

Generally speaking, name your variables and MySQL™ components using ONLY lower case alphanumeric
characters and the underscore (_) character. Variable names and MySQL™ components should begin with a letter, not a number.
Upper case table names and field names may not be usable on other systems, depending on their
configuration.

Creating MySQL™ column
names such as “first_name” instead of “FirstName” will enhance readability and
facilitate replacing the underscore character with a space when displaying column names.

PHP reserved words

Do not use PHP reserved words or MySQL™ reserved
words
™ reserved words as the name of a PHP variable or a MySQL™ database, table, or column. Usage of reserved words
is likely to cause unexpected results, and cause you (or someone else) to waste a lot of time trying
to track down the problem.

Learn to use the define() function in order to create variables that are automatically global in
scope (available within user defined functions). Alternatively, consider creating configuration
variables as an array which can subsequently be declared as global is scope within individual, user
defined functions. Syntax for your configuration variables might use a syntax such as:

Learn to use the define() function in order to create variables that are automatically global in
scope (available within user defined functions). Alternatively, consider creating configuration
variables as an array which can subsequently be declared as global is scope within individual, user
defined functions. Syntax for your configuration variables might use a syntax such as:

$opts = array();
$opts[‘host’] = ‘localhost’;
$opts[‘user’] =
‘someone’;

Saving PHP scripts or “include files” using the
filename extension “.inc” will result in the server displaying that file as if it were a
text file (if requested directly by the web browser). Consequences can be significant if you were to
expose your database logon inside something like “db_logon.inc”.

Turning your Windows box into a WAMP PC

Don’t install the latest versions of Apache and PHP
on 64-bit Windows 7. They will appear to work on 64-bit Windows 7 but won’t play well together. Use
Apache 2.0x not 2.2. Pick a PHP version which is about
a year old. This can save you about 3 days of swearing. Presumably the same is true for 64-bit
Vista. Obscure bugs can exist in PHP’s .DLL files for the latest versions of PHP which are run largely under Linux. It takes a long
time for Windows related bugs to crop up, be reported, and be fixed.

Installing PHP and MySQL™ on a Windows PC is less intimidating than it was a few
years ago. You will learn more about PHP and MySQL™ if you install the
applications individually after visiting the Downloads page at both PHP.net scripting and MySQL.com. Due to differences between Linux and Windows file systems, you may
sometimes need your scripts to respond differently based on where they’re being run (PC vs. web
server). Consider setting a unique variable in your PC’s Apache httpd.conf file, possibly something
like ‘SetEnv WAMP 1’ which can later be evaluated in a PHP script with:

if(isset($_SERVER[‘WAMP’])){

// running on pc

}

With Apache running on a Windows PC, there may be times when it would be helpful for the script
to automatically determine whether it is being run from the WAMP development environment or
production LAMP environment. I encounter this often when a directory path on the web server is
different from the directory structure on the PC. Consider editing the Apache httpd.conf file on the
WAMP PC, adding a unique environmental variable that is unlikely to be exist on any other server.
Subsequently PHP’s $_SERVER variables can easily be checked.

In my PC’s Apache httpd.conf file, I added: SetEnv WAMP 1 and subsequently in PHP scripts I can determine the runtime location with:
if(isset($_SERVER[‘WAMP’])){ // }

If your web host allows you to alter the PHP configuration using the .htaccsss file, you can set your timezone in your .htaccess with something like SetEnv TZ America/Denver

If your web host allows you to alter the PHP configuration using the .htaccsss file, you can add custom variables to the $_SERVER array, for example SetEnv MY_DATABASE dbname would populate the PHP variable $_SERVER[‘MY_DATABASE’]