Get Current URL in PHP

I know for most people, this has been done a million times… But it’s the little things that sometimes help.

So this is how you would grab the current request URL and feed it into a local variable so you can play with it.

<?php
$url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
?>

It just says, if we have an “https” request, then concatenate https onto the front of the servername with the request URI. If we have an “http” request, do the same.

Super easy.

Quick Debugging Function

Sometimes it helps to have a variable checking function that simply spits out what values are contained in your variables. If you run into undefined errors (even object errors) its a good idea to check your variables and make sure your passing the correct values. Here’s a quick function to output most of your main sources of information. It’s handy to call this function before the lines that are causing the error but as close to the error cause as possible.

function check_vars() {
	echo "COOKIE variables: n<pre>";
    print_r($_COOKIE);

	echo "</pre><br />SESSION variables: n<pre>" ;
    print_r($_SESSION);

	echo "</pre><br />GET variables: n<pre>";
    print_r($_GET);

	echo "</pre><br />POST variables: n<pre>" ;
    print_r($_POST);

    echo "</pre><br />SERVER variables: n<pre>" ;
    print_r($_SERVER);
	echo "</pre>";
}

Simply include this function and call it immediately before your errors and you should see what’s available in your scripts!

Create Custom Write Panels in WordPress

I recently needed to modify my portfolio items to display a bit differently than my blog posts. I also decided I didn’t want to hack a solution together and instead have a simple form in the backend where I could add portfolio pieces easily. I chose to make a custom write panel to accomplish this.

Custom write panels like the one shown above are common in many wordpress themes nowadays. Many theme developers rely on them to give the user easy access to control more complex features of a site. In this tutorial I’ll walk you through a simple example of custom write panel code found here.

We’re going to follow the order that WordPress would look at this. Below you can see a simple call that “hooks” into the admin menu. WordPress knows when it reaches this “hook” it will run a function called “create_portfolio_images”.

add_action( 'admin_menu', 'create_portfolio_images' );

Now WordPress looks for this function within this file. Sure enough it finds it.

function create_portfolio_images() {
	global $key_images;

	if( function_exists( 'add_meta_box' ) ) {
		add_meta_box( 'new-portfolio-images', ucfirst( $key_images ) . ' Images', 'display_portfolio_images', 'post', 'normal', 'high' );
	}
}

Now we see that we need something called “$key_images” in the global scope. We define it in the block of code at the top of the page. We also define what fields we’ll be outputting to the admin menu, but that comes a bit later.

$key_images = "portfolio";

Now that we’ve defined what this admin panel is called. We can look at the above function called “create_portfolio_images”. It’s pulling in our key, then if a function called “add_meta_box” exists, we’ll call the function on another function called “display_portfolio_images”. This is where we start to get fancy.

function display_portfolio_images() {
	global $post, $meta_boxes_images, $key_images;
	?>

	<div class="form-wrap">

	<?php
	wp_nonce_field( plugin_basename( __FILE__ ), $key_images . '_wpnonce', false, true );

	foreach($meta_boxes_images as $meta_box) {
		$data = get_post_meta($post->ID, $key_images, true);
		?>

		<div class="form-field form-required">
		<label for="<?php echo $meta_box[ 'name' ]; ?>"><?php echo $meta_box[ 'title' ]; ?></label>
		<input type="text" name="<?php echo $meta_box[ 'name' ]; ?>" value="<?php echo htmlspecialchars( $data[ $meta_box[ 'name' ] ] ); ?>" />
		<p><?php echo $meta_box[ 'description' ]; ?></p>
		</div>

	<?php } ?>

	</div>
	<?php
}

Now that we’ve called the function to display our admin panel to the user, we need some information about the form fields we’ll be showing. To get this, we define an array at the top of the page to list out each of our form fields.

$meta_boxes_images = array(
	"portfolio_image1" => array(
		"name" => "portfolio_image1",
		"title" => "Portfolio Image 1",
		"description" => "Using the "<em>Add an Image</em>" button, upload an image and paste the URL here. These Images are generally 900x340."),
	"portfolio_image2" => array(
		"name" => "portfolio_image2",
		"title" => "Portfolio Image 2",
		"description" => "Using the "<em>Add an Image</em>" button, upload an image and paste the URL here. These Images are generally 900x340."),
	"portfolio_image3" => array(
		"name" => "portfolio_image3",
		"title" => "Portfolio Image 3",
		"description" => "Using the "<em>Add an Image</em>" button, upload an image and paste the URL here.  These Images are generally 900x340."),
	"portfolio_image4" => array(
		"name" => "portfolio_image4",
		"title" => "Portfolio Image 4",
		"description" => "Using the "<em>Add an Image</em>" button, upload an image and paste the URL here.  These Images are generally 900x340."),
	"portfolio_imag5" => array(
		"name" => "portfolio_image5",
		"title" => "Portfolio Image 5",
		"description" => "Using the "<em>Add an Image</em>" button, upload an image and paste the URL here.  These Images are generally 900x340.")
);

Now that we have our data about the form fields we’ll show to the admin, its time to add our second action. So far we have something to display our new admin panel and show some form fields. Now we want the form fields to save our data when the user hits the “update” or “publish” buttons. We’ll do that by adding another “hook” into WordPress.

add_action( 'save_post', 'save_portfolio_images' );

We’ll say that when we “save the post” we’ll run another function called “save_portfolio_images”. This will do some security screening and save the new post data to your post_meta area of our posts.

function save_portfolio_images( $post_id ) {
	global $post, $meta_boxes_images, $key_images;

	foreach( $meta_boxes_images as $meta_box ) {
		$data[ $meta_box[ 'name' ] ] = $_POST[ $meta_box[ 'name' ] ];
	}

	if ( !wp_verify_nonce( $_POST[ $key_images . '_wpnonce' ], plugin_basename(__FILE__) ) )
		return $post_id;

	if ( !current_user_can( 'edit_post', $post_id ))
		return $post_id;

	update_post_meta( $post_id, $key_images, $data );
}

When it’s all put together, it should look something like this:

<?php
$key_images = "portfolio";
$meta_boxes_images = array(
	"portfolio_image1" => array(
		"name" => "portfolio_image1",
		"title" => "Portfolio Image 1",
		"description" => "Using the "<em>Add an Image</em>" button, upload an image and paste the URL here. These Images are generally 900x340."),
	"portfolio_image2" => array(
		"name" => "portfolio_image2",
		"title" => "Portfolio Image 2",
		"description" => "Using the "<em>Add an Image</em>" button, upload an image and paste the URL here. These Images are generally 900x340."),
	"portfolio_image3" => array(
		"name" => "portfolio_image3",
		"title" => "Portfolio Image 3",
		"description" => "Using the "<em>Add an Image</em>" button, upload an image and paste the URL here.  These Images are generally 900x340."),
	"portfolio_image4" => array(
		"name" => "portfolio_image4",
		"title" => "Portfolio Image 4",
		"description" => "Using the "<em>Add an Image</em>" button, upload an image and paste the URL here.  These Images are generally 900x340."),
	"portfolio_imag5" => array(
		"name" => "portfolio_image5",
		"title" => "Portfolio Image 5",
		"description" => "Using the "<em>Add an Image</em>" button, upload an image and paste the URL here.  These Images are generally 900x340.")
);

function create_portfolio_images() {
	global $key_images;

	if( function_exists( 'add_meta_box' ) ) {
		add_meta_box( 'new-portfolio-images', ucfirst( $key_images ) . ' Images', 'display_portfolio_images', 'post', 'normal', 'high' );
	}
}

function display_portfolio_images() {
	global $post, $meta_boxes_images, $key_images;
	?>

	<div class="form-wrap">

	<?php
	wp_nonce_field( plugin_basename( __FILE__ ), $key_images . '_wpnonce', false, true );

	foreach($meta_boxes_images as $meta_box) {
		$data = get_post_meta($post->ID, $key_images, true);
		?>

		<div class="form-field form-required">
		<label for="<?php echo $meta_box[ 'name' ]; ?>"><?php echo $meta_box[ 'title' ]; ?></label>
		<input type="text" name="<?php echo $meta_box[ 'name' ]; ?>" value="<?php echo htmlspecialchars( $data[ $meta_box[ 'name' ] ] ); ?>" />
		<p><?php echo $meta_box[ 'description' ]; ?></p>
		</div>

	<?php } ?>

	</div>
	<?php
}

function save_portfolio_images( $post_id ) {
	global $post, $meta_boxes_images, $key_images;

	foreach( $meta_boxes_images as $meta_box ) {
		$data[ $meta_box[ 'name' ] ] = $_POST[ $meta_box[ 'name' ] ];
	}

	if ( !wp_verify_nonce( $_POST[ $key_images . '_wpnonce' ], plugin_basename(__FILE__) ) )
		return $post_id;

	if ( !current_user_can( 'edit_post', $post_id ))
		return $post_id;

	update_post_meta( $post_id, $key_images, $data );
}

add_action( 'admin_menu', 'create_portfolio_images' );
add_action( 'save_post', 'save_portfolio_images' );
?>

This will save your new custom admin panel, otherwise known as a “write panel” in WordPress.

 

WordPress Custom Single Page Template

I needed to display my portfolio items in a different template than my blog posts. The problem is I post my portfolio items by adding another post and categorizing it as a portfolio item. WordPress generally treats all single posts the same, it refers to single.php and follows the template listed there. So I needed to “trick” WordPress into showing a different template if I’m viewing a portfolio item. This can be done with the following, very elegant, line of code:

add_filter('single_template', create_function('$t', 'foreach( (array) get_the_category() as $cat ) { if ( file_exists(TEMPLATEPATH . "/single-{$cat->category_nicename}.php") ) return TEMPLATEPATH . "/single-{$cat->category_nicename}.php"; } return $t;' ));

Simply cut and paste this to your functions.php file and it will automatically search for a file named “single-{your_category_name_here}.php”. Let’s assume I have a category named “elephants,” and I need to display a custom single page template for elephants. I cut and paste the above code into my “functions.php” file. Then I create another file in my theme folder named “single-elephants.php” and include the code for my new template. WordPress will now automatically include my new template when someone tries to view a post categorized as “elephants.”

Find out more here.

Quick Tips on Hacking

With all the media coverage recently, I thought I just throw out some quick tips to getting started…

Ports

  • 21 – FTP
  • 53 – DNS
  • 80 – HTTP
  • 110 – POP3
  • 135 – Windows RPC
  • 137 – Windows NetBIOS

Tools

AnonOps

Happy fun times with all these tools, there are some very expensive commercial tools for network security professionals available. However, I would play around with some free tools first and find out if it’s for you before purchasing/pirating any of that software.

Measuring User Scroll with jQuery

It’s super easy to measure the amount a user scrolls down with jQuery. In fact, it’s not hard to grab a percentage of the page the user has scrolled either. Which means you can add some interactive portions to your page depending on how much the user has scrolled down your site. It’s just another way to grab user attention and define a rich interactive environment for your users.

To take action on user scroll do something like this:

$(document).scroll(function(e){

	// do something on user scroll here

});

To get the amount the user has scrolled:

var scrollAmount = $(window).scrollTop();

To get the height of the page:

var documentHeight = $(document).height();

To get the percentage of the page height the user has scrolled:

var scrollPercent = (scrollAmount / documentHeight) * 100;

Let’s say I wanted to do something when a user gets halfway down my page:

$(document).scroll(function(e){

	// grab the scroll amount and the window height
    var scrollAmount = $(window).scrollTop();
    var documentHeight = $(document).height();

    // calculate the percentage the user has scrolled down the page
    var scrollPercent = (scrollAmount / documentHeight) * 100;

	if(scrollPercent > 50) {
		// run a function called doSomething
		doSomething();
	}

	function doSomething() { 

		// do something when a user gets 50% of the way down my page

	}

});

Just wanted to share some helpful (and simple) ways to monitor user interaction.

Programming Zebra Stripes

Recently, I needed to use a programming trick to make a for loop alternate every other time. This can be done using a little trick called “zebra striping.”

It’s simple, set a variable to zero before the loop, then within the loop run the variable through an equation of 1 – variable. This will effectively make the loop either a zero or one every time the loop is run. See example code below…

<?php

$alt = 0;

for($i = 0; $i < 20; $i++) {

	// do some stuff here

	$alt = 1 - $alt;
}

?>

Just thought I’d share a helpful little snippet.

Scrolling Animation

Our class wanted some dynamic and animated elements to exist on our portfolio website. Since we are already basing the site on the parallax effect and scrolling, I thought we could tie the animation to the scroll event.

I’m sure this has been done before, I’m just introducing my take on animation much the way they made the very first movies.

Start with two alternating images. Try two positions of a stickman walking. If you don’t fee like making it, I have a downloadable demo here.

Load the images into a page and we’ll begin writing some javascript.

First off, lets just make the images alternate when you scroll. jQuery has a nice function for this, aptly named “scroll.” Basically all the code says is when the user scrolls run a function called walk. Inside the function we alternate between showing two different classes. This allows us to piece together an animation.

// set a global alternating variable
alternating = 0;

// when the user scrolls
$(document).scroll(function(e){

	// run a function called walk
	walk();

	function walk() { 

		// if the alternating variable is zero, show the walk class
		if(alternating == 0) {
			$(".walk2").hide();
			$(".walk").show();

		// otherwise show the walk2 class
		} else {
			$(".walk").hide();
			$(".walk2").show();
		}

		// if alternating is 1, change it to zero. if it's 0, change it to 1
		alternating = 1 - alternating;

	}

});

This isn’t very useful yet, all it does is alternate between two images…let’s make it run across the page.

// set a global alternating variable
alternating = 0;

// when the user scrolls
$(document).scroll(function(e){

	// grab the scroll amount and the window height
    var scrollAmount = $(window).scrollTop();
    var documentHeight = $(document).height();

    // calculate the percentage the user has scrolled down the page
    var scrollPercent = (scrollAmount / documentHeight) * 100;

	// run a function called walk
	walk();

	function walk() { 

		// set the position left = to the scroll percent
		$(".common").css({
							'left' : scrollPercent + '%'
						});

		// if the alternating variable is zero, show the walk class
		if(alternating == 0) {
			$(".walk2").hide();
			$(".walk").show();

		// otherwise show the walk2 class
		} else {
			$(".walk").hide();
			$(".walk2").show();
		}

		// if alternating is 1, change it to zero. if it's 0, change it to 1
		alternating = 1 - alternating;

	}

});

It’s beyond the scope of this post, but it would be interesting to animate more than two frames of something and have scroll become another interaction point for your users. It’s a simple example, but this technique has a lot of possibilities.

Demo

Download

Microsoft Tag – URL Shortcodes

For anyone out there who has had some trouble finding the shortcodes for Microsoft’s Tag URL tags, below is a list.

Short Codes

Postal Code Geo:

{!PostalCode}

Latitude:

{!Lat}

Longitude:

{!Long}

Device ID:

{!deviceID}

These URL shortcodes can be used when creating your tags to give you some information about who the scanner is and where they were scanning. Let’s say I send out a bunch of tags stuck to boxes of my product. I can have these URL tags point to my server, deliver something to the user and at the same time grab some information about the user from the URL information they pass back to me. Let’s say I want to make a tag that delivers me a device ID and the postal code where the tag was scanned.

Full URL

I would create a tag with the following URL:

https://iwearshorts.com/tag/boxscan.php?deviceID={!deviceID}&postalCode={!PostalCode}

Then create the actual page to capture the information and give the user the desired experience. This technology represents a remarkable improvement over the older QR technology because it allows us to make our tags dynamic, offers analytics, and represents a more attractive barcode to the user. More on Tag as this technology becomes more mature and better uses are discovered for it.

Capture

To capture the information I might do something like this:

<?php
	if(isset($_GET['deviceID']) && isset($_GET['postalCode'])) {
		// get the interger values and display the stuff
		$deviceID = intval($_GET['deviceID']);
		$postalCode = intval($_GET['postalCode']);

		if(!empty($deviceID) && !empty($postalCode)) {
			$message = "We were able to capture your device ID: <em>" . $deviceID . "</em> and your postal code: <em>" . $postalCode . "</em>";
		} else {
			$message = "Unable to capture the device ID";
		}
	} else {
		$message = "No GET data available.";
	}
?>

iSteg for Mac

Cool and easy to use tool for encrypting/decrypting hidden messages in images. It’s not the most versatile, but it does allow for encrypting and hiding zipped files (so you could hide multiple file types), its great for sending encrypted messages with low fingerprint and it’s easy to use on a mac.

Just download the program here, install it and away you go!

Here’s a demo to make sure its working!

And here’s the image to make sure it’s working (password = test):

If everything was installed right you should get a short message when you inspect it!

If you are looking for a quick read on steganography download, a great pdf can be found here. Also a link to the source here.