Super Useful PHP Helper Function

If you use PHP, especially when dealing with an API, you might want to see everything inside a variable. Normally you’d use print_r(); but that would normally return a big long line of unreadable text. Since PHP included formatting as whitespace if you wrapped the output in a <pre> tag you get a nicely indented view that is much more readable.

Here’s how you can do it super easy style, just add this function to your project:

function pretty_print($arg) {
  echo '<pre>';
  print_r($arg);
  echo '</pre>';
}

Then you can do something like:

$var = $_SERVER;
pretty_print($var);

Redirecting users to a custom login page while using WordPress

So your running a community powered website using WordPress, maybe you have BuddyPress installed as well. But you don’t like the login page and want to add your own. This snippet will get you part of the way there. You could modify this for other WP admin pages as well, but you would probably want to do some user role checking. Alternatively you could just hire someone like me to do your custom WordPress development.

For the DIY crowd, just place this in your functions.php and change out the $login_page to your custom login page (example goes to homepage) and any visitors will go to your custom login page.


function redirect_login_page(){

 // Store for checking if this page equals wp-login.php
 $page_viewed = basename($_SERVER['REQUEST_URI']);

 // Where we want them to go
 $login_page  = site_url();

 // Two things happen here, we make sure we are on the login page
 // and we also make sure that the request isn't coming from a form
 // this ensures that our scripts & users can still log in and out.
 if( $page_viewed == "wp-login.php" && $_SERVER['REQUEST_METHOD'] == 'GET') {

  // And away they go...
  wp_redirect($login_page);
  exit();

 }
}

add_action('init','redirect_login_page');

Command Z for developers

If your using GIT, your going to love this:

git reset HEAD~1

That will take you back to your last commit while leaving your working directory (files) alone. This is great if you make a commit and want to fix something, you would just do git reset HEAD~1, make your chages and then add and commit as regular.

Gitting Advanced

# Roll back one commit leaving the working directory intact
git reset HEAD~1

# Roll back your working directory to the last commit
git reset --hard HEAD~1

# Keeps the files AND index (what's been added for commit)
git reset --soft HEAD~1

One more thing…

Need to go back to a specific commit? Just use the commit’s SHA hash instead of HEAD~1, like so:
git reset --hard 9748bc01c6ef45ef7f824c6f2bd6052f0d8b9691

Protip: You can find your commit hash using git log.

Creating Your First Shell (Bash) Script

If you have used a mac for a long time and never opened up the terminal, you are really missing out on a productivity workhorse. The power comes from the simplicity. At it’s core the command line is all about typed input. However, if you find yourself using the same commands over and over, you could really crank up the geek by making your own shell scripts. Here is how to do just that.

Make a spot for your scripts

Finding a place for your scripts is wise so you can keep them separate from system scripts. I keep mine in my home folder in a folder called .bin (Yes, it’s hidden).

Create the folder like so:

mkdir ~/.bin

Next your going to need to set up the path so your shell can find your scripts, you can do that by adding the path to your .bash_profile.

Here is an example using the nano editor in OSX, but feel free to use any text editor you want. Nano is a great command line editor because it is almost everywhere and has a low learning curve unlike vim.

nano ~/.bash_profile

And place this line at the top:

export PATH=$PATH:~/.bin

Close and save the file by pressing ctrl-x (Looks like ^X) and choosing Yes to save as the same name. (Press y and then enter, for the type first read later people)

Create the script and set permissions

Now we need to create a script to live in his/her new home. To keep things simple and make sure the above steps worked we will just do the standard “Hello World” test. Anything following the ‘#’ is a comment and is not ran.

cd ~/.bin # Make sure we are in the right spot
touch hello # Creates a script named hello
chmod 700 hello # Makes executable "Off With His Head"
nano hello # Opens in nano editor

In nano copy any paste the following:

!#/bin/bash
echo Hello $1 

The first line is saying this is a bash script, which can be found at /bin/bash.

The second line is are actual script, the only special thing about it is the $1 sign which is a variable for any input following the script. You could have multiple variables in chronological order by using $2, $3 and so on.

Run the script like a boss

Now we should be able to run the script to desired effect by typing the following:

hello World

If you get any errors make sure your script is in the right place by typing:

cd ~/.bin # go to the spot
ls # show files, it should output back hello

If it is in the right place set the permissions with:

sudo chmod 700 hello # sudo will prompt you for an admin password

Finally check to make sure your path is set correctly:

nano ~/.bash_profile

In the spirit of don’t repeat yourself, lets make a script to make making scripts easier. We will call it ‘makescript’.

cd ~/.bin
touch makescript
chmod 700 makescript
nano makescript

Enter the following and save the file:

#!/bin/bash
cd ~/.bin
touch $1
chmod 700 $1
echo $1 > \#!/bin/bash

Now you can use the following to create any scripts you like:

makescript nameofscript

Use a local copy of jQuery if you can’t connect to CDN

The first line of code will try to include jQuery using google’s CDN which will make it a faster download for a majority of visitors, the second line checks if it was successfully included by checking for the jQuery object, if it is not found it uses a local copy. This makes working locally without an internet connection seamless, and will provide a failover in case google’s CDN goes down, however unlikely that is.

This code came from the HTML5 Boilerplate which is full of useful snippets.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.7.1.min.js"><\/script>')</script>

Automate 404 discovery, the easy PHP way.

For this edition of Quick Codes I am sharing how to send an email whenever someone lands on your 404 File Not Found error page. I found this on CSS-Tricks.com’s 404 Best Practices post and had to share it. Just to clarify this code has not been vetted to ensure security or that it works perfectly, but sometimes it gets the job done just fine. This code is PHP, but the idea could be adapted to any language. For more good ideas don’t forget to check out my post Better 404 error pages by design.

mail("name@domain.com", "404 report", $_SERVER['REQUEST_URI'], "From: example@domain.comn");

UPDATE:

Thanks to a recent comment by Thomas Scholz, I added the addslashes() function to escape any funny stuff inside the request url.

mail("name@domain.com", "404 report", $_SERVER['HTTP_HOST'] . addslashes($_SERVER['REQUEST_URI']), "From: example@domain.comn");

And I also found a good piece of code on codex.wordpress.org which is an excellent resource. View the full page with example code here: Creating an Error 404 Page « WordPress Codex

Redirect iPhone’s with Javascript

Here is a really quick code:

  <script type="text/javascript">
  if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i))) {
    location.href='YOUR_DIRECTORY/';
  }
  </script>

Add this to your html document’s head section. Replace YOUR_DIRECTORY with the folder that contains your iPhone optimized site.

Disable form inputs when submitted with jQuery

Aside

One of the most frustrating things on the internet is when you click a button and the page just sits there. The chances are that many of us will click that button again. This is negative because it causes bad user experience and that most often results in them leaving your site never to return. A quick way to combat this client-side is by disabling the submit button after it has been pressed. Web developers will also need to make sure that any data submitted twice will be taken care of accordingly from the server-side.
Continue reading

Quick Codes: A new series of post on Complimedia (JS + CSS)

Aside

In this new series of post on the Complimedia Blog, I will be finding the best scripts, snippets, tricks, and hacks in the world of web design and posting them for you. You can find the complete series on this page as well.

Today I will be sharing a small javascript that can manipulate css of the containing elements and a super simple fix for web forms.

Lets start with the javascript shall we?

This is a handy little snippet of javascript. I found this script on IE6 No More, a website that is promoting dropping support for IE6 with a small script that can be added to any website. I will improve upon their script in a later tutorial but for now I wanted to share the easy snippet of JS they use to hide the warning.

This tiny onclick event will hide whatever the parent element is(or grandparent, etc…). This has a great many uses but I will leave that up to you to figure out. Lets see the code.

<div>
<a href="#" onclick='javascript:this.parentNode.style.display="none"; return false;' title="Hide this box">Hide Div</a>
</div>

Breaking this down, it is a simple link with an On Click javascript event that will change the parent element’s CSS to display:none which will hide it. Its also worth noting in the above example the only thing that would happen is the Hide Div link would disappear. You can adjust which element to change by adding .parentNode. after the first one so it would be two levels above.

I created a quick demo page with some more uses of this code.


The next bit of CSS is very basic and I use it all the time.

What it does is hides the browser default field focus. You know when you click a text field and a blue outline pops up to show you what your filling out. Well this usually breaks my design so I add this and all is fixed!

textarea, input { outline: 0; }

Before And After

You can see this example at http://lickmytwitter.com