PHP articles, scripts, tips and tricks
There are 17 articles published in this category. Please try the search if you can't fint what you're looking for.

Live ajax search using the Google search API

Monday, May 19, 2008

I realized the bogus-search-results script from Live Ajax Search jQuery Plug-in may not have been very satisfying to you visitors, so I thought I'd show you how to use the Google search API to create a real live ajax search on your site.

This example requires PHP and if you're running any version below 5.2 you'll need Michal Migurski's JSON-class as well.

The PHP (and HTML erm..)

The Google search API is basically just a URL you pass a search-query to and it returns a JSON with results.
I won't go in to too specific details about the API, if you wish to know more please refer to the documentation.

Create a search-results.php file and put the following code in it:

require_once 'JSON.php';

# Your site URL
$site '';

# Make sure a search-query was entered
if(isset($_GET['q'])) {
# Are we on the first page?
$start = isset($_GET['start']) ? $_GET['start'] : 0;

# The URL to the Google search API
$url '' .urlencode($_GET['q']) .'%20site:' .$site .'&rsz=large&start=' .$start;

# Initiate CURL
$ch curl_init();
curl_setopt($chCURLOPT_REFERER'http://' .$site);
$body curl_exec($ch);

# Decode the JSON returned (you need the JSON-class if json_decode is undefined)
$body json_decode($body);

# Build array
$i    0;
$search_results = array();

# Loop through all results
foreach($body->responseData->results as $r) {
$search_results['results'][$i]['title'] = $r->title;
$search_results['results'][$i]['url'] = $r->url;
$search_results['results'][$i]['content'] = $r->content;

# Loop through all the pages of results
if(isset($body->responseData->cursor->pages)) {
$body->responseData->cursor->pages as $p) {
$search_results['pages'][] = $p->start;

# Make sure some results were returned
if(isset($search_results['results'])) {
        <h2>Search results for &quot;<?php echo @$_GET['q']; ?>&quot;</h2>

        <ol<?php echo @$_GET['start'] > ' start="' .($_GET['start'] + 1) .'"' '' ?>>
        <?php foreach($search_results['results'] as $sr) { ?>
                <h3><a href="<?php echo $sr['url']; ?>"><?php echo $sr['title']; ?></a></h3>

                <p><?php echo $sr['content']; ?><br /><a href="<?php echo $sr['url']; ?>">Read more</a></p>
        <?php ?>

        <?php if(isset($search_results['pages'])) { ?>
            <?php $i 0; foreach($search_results['pages'] as $p) { $i++; ?>
                    <?php if((!isset($_GET['start']) && $p == 0) || (@$_GET['start'] == $p)) { ?>
                        <strong><?php echo $i?></strong>
                    <?php } else { ?>
                        <a href="/search/?q=<?php echo @$_GET['q']; ?>&amp;start=<?php echo $p?>"><?php echo $i?></a>
                    <?php ?>
            <?php ?>
        <?php ?>
    else {
            <p><strong>Sorry, there were no results</strong></p>

As the search-results.php-file doesn't contain any DOCTYPE, html, head or body-elements it is obviously not valid HTML. How you implement the search-results on your own site differs depending on what type of site-structure you've got set up. Regardless you should probably be able to figure it out.

If you do include some sort of head/foot-templates in the search-results make sure not to include them if it's an ajax-call (isset($SERVER['HTTPXREQUESTEDWITH'])).

I'm going to assume the search-results.php will be included from a search.php-file in the root of your site. So visiting /search.php would display the search-results (provided a query is set) along with whatever else your site consists of, but visiting just /search-results.php will only output the results.

The HTML form

Now all you need to do is set up a form that submits a get-request to search.php:

<form method="get" action="/search.php">

        <label for="q">Search</label> 
        <input type="text" name="q" id="q" /> 
        <input type="submit" value="Find" />


The Ajax-magic

And now hijax that form:

<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript" src=""></script>
<script type="text/javascript">
    $('#q').liveSearch({ajaxURL: '/search-results.php?q='});


I've set up an example-page and you can also download the example-files.



Seems curl_init isn't available from my host (bummer). The example should still work for you locally though,and hopefully live as well (unless you suffer from the same limitations).

Prefix CSS-selectors PHP Class

Thursday, April 24, 2008

Recently at work I had to combine a site's existing design and a PHPBB-template.
If you've ever worked with PHPBB (front or back-end) you'll know it's no dream.

The hardest part with combining PHPBB (or any other third-party-software) with your own code is to make sure your CSS-rules (well JS as well I suppose) don't collide.

PHPBB styles h1:s, you style h1:s, PHPBB styles a:s, you style a:s. It's a right mess when both are trying to style elements on such a general level.

As most websites nowadays, most of PHPBB's themes has a wrapper-div around the entire website so I had an idea to manipulate all of PHPBB's CSS-code before output and add that wrapper-div's ID-name in front of every selector.

So instead of PHPBB styling all the h1:s in a document, it would only style (in this case) #wrap h1:s (#wrap is the name of the wrapper-div in the prosilver-theme).

Recent versions of PHPBB include a similar type of CSS-compression as I've explained before in CSS compression and constants PHP-class so you have access to every line of CSS code in a variable before it's outputted. The merging of CSS happens in PHPBB3/style.php. Look at the very bottom and you'll see something like echo $theme['themedata']; The themedata-index in the $theme-array is what contains all of the CSS for that theme. What you want to do here is run my function on that variable before output:

So instead of:

echo $theme['theme_data'];

You want:

require_once 'CSSSelectorPrefixer.php';
echo prefixCSSSelectors($theme['theme_data'], '#wrap');

The function will then add #wrap at the beginning of every selector in the string.

One problem with this though is that #wrap isn't the root-element of the document, the html-element is. So any styling on body or html will have no effect as they will be changed to #wrap body and #wrap html. I believe this is what you want in most cases as you've probably styled both elements in your own CSS.

The function will also remove duplicate #wrap:s (if the PHPBB-style contained something like #wrap a the function will turn it in to #wrap #wrap a, but before it returns the new code it will remove all duplicate #wrap:s (or whatever you set)).

This really simplified the design-move and hopefully it will help someone looking to do the same thing.

You can as usual get the code from my Google Code repository.


Javascript compression PHP class

Monday, January 21, 2008

In addition to my CSS compressor and constants parser I've also written a very simple Javascript compressor class that uses Nicolas Martin's PHP port of Dean Edward's Javascript packer.

It works in exactly the same way as the CSS-compressor. Create a new instance, pass the directory(ies) you want to look for .js-files in and then call the pack-method.

$jsc = new JSCompressor('js/');
echo $jsc->pack();

Reducing the number of HTTP requests the browser needs to make is essential for performance. Together with full packing of all the code, file-size is often reduced by up to 70% and the number of HTTP requests always down to 1.

Download the demo and have fun!

Live form-validation jQuery plug-in

Sunday, January 20, 2008

This plug-in adds valid/invalid icons next to form-controls and validates them as user types.

It requires PHP for the validation so your server needs to have PHP installed.
An easy way to check if PHP is installed is to create a file (foo.php), put:


in it, upload it to your server and then go to the file in your browser and see what it says.
There should be a load of information if you have PHP installed.

The form-validator requires you use some common names for your form-inputs.
There's only three fields specified at the moment; 'name', 'email' and 'message'. But if you're not completely unfamiliar with PHP you should have no problem adding more of your own.
Also, if you prefer 'content' or 'comment' or something instead of 'message', simply open the FormValidator PHP-class, find the line that defines the message-validation and rename to whatever you like.
Anything passed to the FormValidator that isn't defined in the class will always return true.

Now, to validate a form using jQuery you will obviously need your HTML form (the plug-in looks for input[type="text"] and textarea) set-up, and a .js-file that initiates the plug-in:

$(document).ready(function() {
    $('#contact form').liveValidation({
        validIco: 'gfx/validIco.gif',        // url to valid icon
        invalidIco: 'gfx/invalidIco.gif',    // url to invalid icon
        action: 'AjaxFormValidator.php'        // url to php-file

You can download a zip with the 2 required PHP-files, a couple of valid/invalid icons, an example PHP-file as well as jQuery and the live validation plug-in here. Or you can always get the latest version of the plug-in here together with the two needed PHP-files: FormValidator and AjaxFormValidator.

Have fun!

CSS Constants and Compression PHP Class

Tuesday, January 15, 2008

I've mentioned my take on CSS-constants before but I haven't come around to actually creating the back-end needed, until now.

Download CSSCompressor and demo-files

The way I see CSS-constants differs a bit from what I've seen over the internet before, which is basically just about storing property-values in variables. That's all good and very basic to implement using any server-side language. What I wanted, tho, was a replacement for classes (CSS-classes that is), so this is how I see constants:

100% Valid XHTML Database Output with Markdown and HTMLEntities()

Wednesday, November 07, 2007

Editors not knowing HTML and messing up your markup can be a big problem for you if you care about validation.

There are numerous WYSIWYG editors out there, but most of them produce absolute crap code, and if you want valid and semantic XHTML they simply will not work.

Markdown is an absolutely brilliant text-to-HTML converter that everybody can learn in minutes.
In fact, you don't have to do anything special at all to produce semantically correct, valid XHTML 1.0 Strict (or HTML if you prefer).

The syntax for adding basic HTML-elements such as headings, lists and images takes about 2 minutes to learn, and is very similar to the way you add meaning to your emails and IM messages, using underscore for emphasis etc.

The problem with Markdown if you use it for user-input (as well as your own) is that it allows any type of HTML-code to be inserted. Of course this is not optimal for comments and other data anybody can submit.

Together with the PHP-function htmlentities(), however, you can always be sure to get 100% valid output.

Download NiceString and demo-files

Markdown Heading Level PHP Function

Tuesday, August 07, 2007

If you use Markdown-syntax for articles/comments or whatever like I do you know that the #-symbol defines a heading.
But depending on where an article is displayed on a page you may want to adjust the heading-levels.
On for example the maximum allowed heading-level for an article on the index-page is 4 (<h4>). This is because the title of the article on the index-page is a <h3>.

I've created a little php-function that adjusts markdown heading-levels to whatever the user wants, so that the same article can be displayed on different pages where heading-levels aren't the same.

Ajax/Hijax Rating Exempel

Wednesday, April 18, 2007

Ajax Scan

Tuesday, October 03, 2006

Ajax-Scan is a php/javascript (ajax) directory-listing script. It works like "explorer"on windows.

Ajax-Scan is still a bit under construction, but when i'm happy with it i'll release the code.


The Ultimate Website Pt. 2

Sunday, April 02, 2006

Please note: "Ultimate" is only ultimate for so long. And I don't exactly do it like this anymore, but I still believe it's an OK beginners-guide to building a dynamic, easy-to-update web site.

If you haven't read part 1 of this article, i suggest you do so before you continue reading.

So, we have the main-structure for the "Ultimate Website". But it doesn't look very fancy does it? Here's where the CSS comes in.

The Ultimate Website Pt. 1

Wednesday, March 29, 2006

Please note: "Ultimate" is only ultimate for so long. And I don't exactly do it like this anymore, but I still believe it's an OK beginners-guide to building a dynamic, easy-to-update web site.

After having programmed PHP, (X)HTML and CSS for a few years now, I've finally come up with a website-structure that I'm satisfied with. A website that uses valid markup, dynamic PHP and a completely CSS-driven design. So it can be used over, and over again with very little changes.

Simple contact script

Wednesday, March 29, 2006

A very simple contact-script you can easily include on your page.


  • Comments are off
  • Filed under PHP

Simple Guestbook script

Wednesday, March 29, 2006

A very simple PHP and MySQL-guestbook, for beginners who want to study basic code, without too much un-necessaries. Or if you just want a guestbook for your website :)


  • Comments are off
  • Filed under PHP

Exscale Counter 1.5

Friday, March 10, 2006

Source code

This version is only available in english, and does not show hours, days or months with 0 visits.



The counter gets pretty fookin slow after you've had about 20-30 000 hits (depending on your server of course) so i may need to fix it. You can still download it tho.

2006-03-10 Small update

Removed tblactivevisitors from the db, now active visitors are based on unique IPs over the past 5 minutes from tblvisitors. Tidier code, although you can no longer keep track of what pages the active visitors are on.
This could easily be added though, but i don't think i will as every click (update (F5) etc) is added to the table, and an extra column keeping the page would obviously take up extra space.


The PHP has been re-programmed pretty much from the ground up, completely new markup and CSS.

Source code

  • Comments are off
  • Filed under PHP


Wednesday, February 01, 2006

A function that lists all dirs and files (including subdirs/files) in a directory.

Source included.

  • Comments are off
  • Filed under PHP

Calculator 1.0

Wednesday, February 01, 2006

A simple calculator written in PHP that uses eval.

Source included.

  • Comments are off
  • Filed under PHP


Sunday, January 01, 2006

A simple four-in-a-row game, badly programmed in PHP. But it works :)

Source included

  • Comments are off
  • Filed under PHP

Post It

From June 02 to April 23

  1. Mogrify is what you're looking for if you want to convert multiple images to multiple other images in ImageMagick
  2. Tommorrow, finally, the inFamous demo will be friggin availble on PSN!! Suweeeeeeeeet
  3. Fuck canvas is cool, I've started playing around with old 3D-shit again :)

March 2015

1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31

Recent Comments

  1. Andreas on jQuery Drag to Select Plug-in:
    @Steven Black - Woops :) I'll have ...
  2. Andreas on jQuery Drag to Select Plug-in:
    @Helder Silva - I've actually used ...
  3. Paul on jQuery Drag to Select Plug-in:
    Found a bug: (1) Do a drag selectio...
  4. Steven Black on jQuery Drag to Select Plug-in:
    Unless I'm missing something, the d...

Style Switcher

The style switcher allows you to change the look and feel of
Only CSS and JavaScript are changed. The XHTML stays the same.

For more information about the styles, check the styles page.


Random Quote

Tu has cortado mi pelo demasiadas vezes - Ante

Random Images

Answer This!

Do you find the "scroll-pagination" annoying? (If you don't know what it is, scroll to the bottom of the first-page)

Blog Roll