Posts

Home Facebook

Fixed: Cannot send session cache limiter – headers already sent

Okay, so many of you guys still ask me about how to fix these warning messages in our Facebook scripts. Today I'm going to give you two possible fixes that you can do. By the way, here's the warning message we want to remove:

Fix it by adding a session_start()

You can fix it by adding a session_start() on top of your PHP file, just right after your first line <?php tag. It looks like this:

Fix it by moving Facebook instance

You can fix it by moving the Facebook class and instance code on top of your PHP file. It would look like this:

If none of them worked, you can read more here.
Home CakePHP

CakePHP 2.x Pagination Tutorial: Helper, Conditions, Limit, Sorting and More!

CakePHP Pagination is one of the fastest thing you can code with this amazing framework. In this post I’m gonna show you how you can create a pagination script in matter of few minutes, or even seconds! Cool? Let’s get started.

This post is part of my CakePHP tutorial series, before you proceed to this, make sure you already installed your CakePHP poperly, know the CakePHP classes and naming conventions, and much better if you can code the CakePHP CRUD operations.

Video Demo

Here’s a video demo of what will be our code ouput.

Controller Code

On our controller, we are going to have a query the cakePHP way, we are going to have the following conditions:

  • Won’t include the record with an ID of 6 (‘conditions’ => array(‘User.id !=’ => ’6′))
  • We will limit to 3 records per page (‘limit’ => 3)
  • Order the result by ID (‘order’ => array(‘id’ => ‘desc’)) in descending order

So here’s the code that will be added in our UsersController.php

public function view() {

    // we prepare our query, the cakephp way!
    $this->paginate = array(
        'conditions' => array('User.id !=' => '6'),
        'limit' => 3,
        'order' => array('id' => 'desc')
    );
    
    // we are using the 'User' model
    $users = $this->paginate('User');
    
    // pass the value to our view.ctp
    $this->set('users', $users);
    
}

The $users variable gives us an array that look like this:

cakephp-pagination

View Code

On our view.ctp, our data is presented with a table. The table header contains the paginator sort() method for sorting the data using any fields you want (and you won’t have to create another query!)

The $this->Paginator object (pagination helper) also has lots of methods for paging, please see the ‘pagination section’ on the code block below.

Also we used the <div class=’paging’> which uses the CakePHP generic CSS. You can change that if you want and be creative with your paging UI design.

<?php
// so we use the paginator object the shorter way.
// instead of using '$this->Paginator' everytime, we'll use '$paginator'
$paginator = $this->Paginator;

if($users){

    //creating our table
    echo "<table>";

        // our table header, we can sort the data user the paginator sort() method!
        echo "<tr>";
        
            // in the sort method, ther first parameter is the same as the column name in our table
            // the second parameter is the header label we want to display in the view
            echo "<th>" . $paginator->sort('id', 'ID') . "</th>";
            echo "<th>" . $paginator->sort('firstname', 'Firstname') . "</th>";
            echo "<th>" . $paginator->sort('lastname', 'Lastname') . "</th>";
            echo "<th>" . $paginator->sort('username', 'Username') . "</th>";
        echo "</tr>";
        
        // loop through the user's records
        foreach( $users as $user ){
            echo "<tr>";
                echo "<td>{$user['User']['id']}</td>";
                echo "<td>{$user['User']['firstname']}</td>";
                echo "<td>{$user['User']['lastname']}</td>";
                echo "<td>{$user['User']['username']}</td>";
            echo "</tr>";
        }
        
    echo "</table>";

    // pagination section
    echo "<div class='paging'>";

        // the 'first' page button
        echo $paginator->first("First");
        
        // 'prev' page button, 
        // we can check using the paginator hasPrev() method if there's a previous page
        // save with the 'next' page button
        if($paginator->hasPrev()){
            echo $paginator->prev("Prev");
        }
        
        // the 'number' page buttons
        echo $paginator->numbers(array('modulus' => 2));
        
        // for the 'next' button
        if($paginator->hasNext()){
            echo $paginator->next("Next");
        }
        
        // the 'last' page button
        echo $paginator->last("Last");
    
    echo "</div>";
    
}

// tell the user there's no records found
else{
    echo "No users found.";
}
?>

Thanks for reading this tutorial code for pagination in CakePHP!

Home CakePHP

CakePHP Classes and Naming Conventions

1.0 Introduction

After installing CakePHP on your server, we now have to learn how to create CakePHP classes and its naming conventions. CakePHP uses Model–view–controller (MVC) software architecture which is really great. If you have no idea what MVC is, I think Wikipedia can give you a great overview. Also, you’re going to get the hang of it in this post.

2.0 Creating CakePHP MVC Files

In this example, we are going to use a database with “users” table and create code for the model, view and controller files. Let’s have fun!

2.1 Preparing the user’s table

Our users table will have only 5 fields which include: id, firstname, lastname, username, password.

CakePHP Classes and Naming Conventions

CakePHP requires a naming convention for our tables. It must be in plural form always. Like right now, we are going to have a table that stores data of users, it means that the name of our table must be “users“, NOT the singular “user” or something.

2.2 Creating a Model

A CakePHP model class manages your application data, rules of validity (for example, a username is required, or a password must consist of letters and numbers) and interactions (queries, etc.).

To create our CakePHP model, go to your app/Model directory, I found mine in C:wampwwwCakePhpProjappModel

On that directory, we will create a model file named “User.php

cakephp-model-naming-convention

CakePHP requires us to create a model file with singular name and with a .php extention, that’s how we come up with the filename “User.php”

If your model has more than one word, for example you have a table “user_permissions”, our Model filename will be camel cased and will look like “UserPermission.php”

Inside that file, we are going to have the Model basic code:

<?php
class User extends AppModel {

    public $name = 'User';
    
}
?>

2.3 Creating a View

A view in CakePHP is the output representation of data retrieved from the model and manipulated by the controller. It can be in the form of HTML, XML, JSON or even PDF!

To create our CakePHP view, we have to go to the app/View/ directory and create a directory called “Users”.

cakephp-view-directory

And then after creating the directory, we will now create the actual “view”, as an example, we are going to have “hello_user.ctp” and leave it as an empty file for now.

cakephp-ctp-file

CakePHP requires us to name a view with a .ctp extension. A view’s name is the same as its function in the controller. We’re going to see it later.

2.4 Creating a Controller

A CakePHP controller class is like the middleman between the Model and View. Controllers are used to manage the logic around a model, and it uses the View for that logic’s output.

To create a model, we are going to create a file named “UsersController.php”

cakephp-controller-file

We are going to have the controller’s basic code:

<?php
class UsersController extends Controller {
    

    
}
?>

3.0 Making MVC Work

Now that we have the required directory, files and basic code inside them, we are going to make this MVC thing work.

3.1 Playing with the controller

First, open your controller, add the following code:

   public function hello_user(){
    
        $user = $this->User->findById(1);
        $this->set('user', $user);

    }

What just happened? As I said earlier, the view name (hello_user.ctp) will be the function name in the controller.

In this function, we tried to retrieve the record details of a user with an ID of 1.

$user = $this->User->findById(1);

To use the $user in the View, we have to use the $this->set() method. Yes, in CakePHP, passing variable values to view requires a $this->set() method.

3.2 Using the Model

For our model, we’ll leave it as is for now. It is used implicitly here in our example. How? Did you see the code $this->User in the controller? Yes, the “User” part of that code is the Model.

3.3 Viewing the View

Lastly, our view “hello_user.ctp” will present the data retrieved, we are going to have this code inside:

<?php
echo "Hello, " . $user['User']['firstname'] . "!";
?>

We retrieved the firstname like that. The $user variable gave us an array value, findById() method gave us this:

array(
    'User' => array(
        'password' => '*****',
        'id' => '1',
        'firstname' => 'Mike',
        'lastname' => 'Dalisay',
        'username' => 'ninjazhai'
    )
)

4.0 Run Code

Now here’s the exciting part, running our code. Go to your browser and type localhost/CakePhpProj/users/hello_user/

You should see something like.

cakephp-classes-name-convention-output

You might want to check out how to perform CRUD in CakePHP.

If you have any comment, suggestion or issues, just drop a comment below. :)

Home CakePHP

How To Use CakePHP Framework, A Getting Started Guide!

1.0 Introduction

Using CakePHP Framework is one of my most favorite things to do. This is the first PHP framework I worked with, and until now, I’m still delighted by it. Now it is time for me to share my knowledge in CakePHP web development.

I think you are here because you already know what CakePHP is, but for those who has no idea yet, and don’t want to read more on CakePHP.org, here’s a brief description: CakePHP makes building web applications simpler, faster and require less code.

I think there are really few blog posts out there with regards to beginner CakePHP tutorials. Most of them are also outdated. We will keep this CakePHP posts as updated as possible. So to the future reader of these posts, please drop something in the comment section below if you think there is something outdated!

We will start with the most basic thing to advanced. Hopefully I can finish this tutorial series in the shortest time possible.

2.0 Install CakePHP on Your Server

Below are few steps to make CakePHP alive in your hosting server, see sections 2.1 to 2.4 below.

By the way, if you’re a super beginner and using a windows PC (localhost), you can follow this tutorial first to set up your localhost: 3 Steps to Install WAMP on Windows

2.1 Download CakePHP (Step 1)

So… what do you expect the first step will be? Of course, we will download the framework. Download the latest CakePHP version here: http://cakephp.org/

As of this writing, the version is CakePHP 2.3.6 stable.

Extract the ZIP file.

2.2 Put CakePHP on Your Hosting (Step 2)

I don’t know, but I think most of you guys are using a localhost (your PC or something). Okay, so I’ll assume you are all using your localhost. If you’re not, just give a comment so we can try help you with your issue.

After you download and extract the Framework files, you have to put it in your root directory. I’m using windows 8 and running with WAMP server, so in my case, my root directory is in:

C:\wamp\www\

Now after putting the extracted folder, my CakePHP directory is in:

C:\wamp\www\cakephp-cakephp-b81c198\

Of course, we want to change the dirty name “cakephp-cakephp-b81c198″ to our “project name”.

So we have to rename it and for this tutorial, we will name it “CakePhpProj”, awesome name right? If you don’t think so, you can choose the project name of your choice. Now we should have:

C:\wamp\www\CakePhpProj

2.3 Run CakePHP

Too early to run? You’re correct. This is just a test run. We just want to confirm if CakePHP can respond at this stage.

So to run CakePHP: Go to your browser > type “localhost/CakePhpProj“

You might see something beautiful like this:

using-cakephp-first-run

You might be disappointed or intimidated by now, but don’t worry, I’m at your side! Proceed to the next step below.

2.4 Configure CakePHP

Alright, so we’re going to address the issues on the previous screenshot, one at a time!

2.4.1 URL rewriting is not properly configured on your server.- Let’s start with this problem, this error is rare if you’re using a real hosting. But if you’re using localhost, here’s the fix:

1. On you notification area (lower right corner), click the WAMP icon.
2. Hover your mouse to the “Apache” folder
3. Hover your mouse to the “Apache modules” folder
4. Find and click “rewrite_module”, WAMP will automatically restart and check that apache module.

mod-rewrite-cakephp

After the fix, re-run our project on the browser, it should look like this now:

cakephp-fix-rewrite-mod

2.4.2 Please change the value of ‘Security.salt’ - To solve this, you have to to got the core.php file and just change the security salt string!

In my case, I have to open it in C:\wamp\www\CakePhpProj\app\Configcore.php

Find the word “salt” (Ctrl+F on your editor, I’m using notepad++)

You should see the line of code that looks like:

Configure::write(‘Security.salt’, ‘DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi’);

Change the value to something like:

Configure::write(‘Security.salt’, ‘nowthisismyawesomesaltthatnoonecaneverknowxfs2gu’);

Then re-run the browser:

cakephp-fixed-security-salt

2.4.3 Please change the value of ‘Security.cipherSeed’ - The solution is the same with 2.4.2, just change the value and re-run!

cakephp-fixed-security-cypherseed

2.4.4 Your database configuration file is NOT present. – Now we have to make a database for our CakePHP application. If you need help doing that, here’s a guide: How To Create MySQL Database With PhpMyAdmin

After creating a database, we have to go again to the Config directory, in my case:

C:\wamp\www\CakePhpProj\app\Config

Now you should see a file named “database.php.default” and rename it to just “database.php“

After renaming it, we have to open it with our editor and supply the database details! In the $default array, what usually we have to change are the: database host, login (username), password and database

You would see something like this in default:

public $default = array(
    'datasource' => 'Database/Mysql',
    'persistent' => false,
    'host' => 'localhost',
    'login' => 'user',
    'password' => 'password',
    'database' => 'database_name',
    'prefix' => '',
    //'encoding' => 'utf8',
);

So we’re going to change it to:

public $default = array(
    'datasource' => 'Database/Mysql',
    'persistent' => false,
    'host' => 'localhost',
    'login' => 'root',
    'password' => '',
    'database' => 'my_project_database',
    'prefix' => '',
    //'encoding' => 'utf8',
);

Now, re-run our project page in the browser, it should look like this:

cakephp-installation-fix

3.0 Services

Still having hard time? I can personally help you do this for only $5!

That’s it for this post, enjoy and continue your CakePHP web development! Here is a continuation of this post: CakePHP Classes and Naming Conventions

Thanks for reading this How To Use CakePHP Framework, A Getting Started Guide!

How to Run a PHP Script? Step By Step Guide!


Hello and welcome to the start of codeofaninja.com's series of web development articles!

Contents of this post include:

1.0 Overview
2.0 Install XAMPP

3.0 Run Your First PHP Script
3.1 Go to XAMPP server directory
3.2 Create hello.php
3.3 Code inside hello.php
3.4 Open New Tab
3.5 Load hello.php
3.6 Output

4.0 Manage Database with PhpMyAdmin
4.1 Create a Database
4.2 Create a Table
4.2 Insert Data
4.4 Useful Videos

5.0 Run PHP Script with Database
5.1 Go to XAMPP server directory
5.2 Create read_one.php
5.3 Code Inside read_one.php
5.4 Open Your Browser
5.5 Load read_one.php
5.6 Output

6.0 Online Resources
7.0 What's Next?
8.0 Related Tutorials
9.0 Some Notes

1.0 Overview

Setting up a development environment for PHP programming is easy. Download the code editor you prefer, I personally like atom.io text editor.

Next is to install XAMPP, the most popular PHP development environment. This package contains Apache, PHP & MariaDB or MySQL database applications.

Many people emailed me with a main question: Mike, how to run a PHP script? This post is my answer to you guys and to those people who will need this in the future.

In the following tutorial, we will learn how to install XAMPP, how to run a PHP script, manage database with PhpMyAdmin and run a sample PHP script that fetches a record from the database.

2.0 Install XAMPP

Go to this link and download XAMPP for your operating system. XAMPP is available for Windows, Linux or Mac.

Here's a video about how you can install and use XAMPP.

3.0 Run Your First PHP Script

The following is an example about how to run a PHP script. What this program does is show a "Hello World!" text on the screen or webpage.

3.1 Go to XAMPP server directory

I'm using Windows, so my root server directory is "C:\xampp\htdocs\".

3.2 Create hello.php

Create a file and name it "hello.php"

3.3 Code Inside hello.php

Open hello.php and put the following code.

<?php
echo "Hello World!";
?>

3.4 Open New Tab

Run it by opening a new tab in your browser

3.5 Load hello.php

On you browser window, type http://localhost/hello.php

3.6 Output

You should see the following output.
run-php-script-1
Great job, you just run a PHP script!

4.0 Manage MySQL with PhpMyAdmin

MySQL is an open-source relational database management system (RDBMS). MySQL is a popular choice of database for use in web applications.

phpMyAdmin is a free and open source tool written in PHP intended to handle the administration of MySQL with the use of a web browser. In the following examples, we will see how easy we can handle MySQL with PhpMyAdmin.

4.1 Create a Database

  1. Go to http://localhost/phpmyadmin/
  2. Click the "New" link on the upper left corner (under recent tables)
  3. Fill out the "Database Name" field with "my_first_database".
  4. Click the "Create" button

1-create-first-database

4.2 Create a Table

  1. Click "my_first_database" on the left side of the screen
  2. On the "Create Table" section, fill out the Name with "products" and Number of Columns with "6"
  3. Click "Go" button

2-create-table

  1. Fill out the fields with id, name, etc.
  2. Mimic everything in the following image
  3. Click the "Save" button

3-create-fields-of-table

4.3 Insert Data

Click the "products" table.

4-click-table-to-insert-data

Click the "Insert" tab.

5-click-table-to-insert-data-2

Fill out the form, mimic the data on the following image. Click the "Go" button.

6-fill-out-form-to-insert-data

Great job! We now have a database, a table inside the database and a record inside the table.

7-data-was-inserted

4.4 Useful Videos

1. Create a database and import MySQL file.

2. Create a database and create table.

5.0 Run PHP Script with Database

In the following steps, we will run a PHP script that fetches one record from the MySQL database.

5.1 Go to XAMPP server directory

Go to your "C:\xampp\htdocs\" directory

5.2 Create read_one.php

Create a file and name it "read_one.php"

5.3 Code Inside read_one.php

The numbers 1-8 in the following code are called "code comments". It explains each part of our simple code below. Open read_one.php and put the following code.

<?php 
// 1. database credentials
$host = "localhost";
$db_name = "my_first_database";
$username = "root";
$password = "";

// 2. connect to database
$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);

// 3. prepare select query
$query = "SELECT id, name, description, price FROM products WHERE id = ? LIMIT 0,1";
$stmt = $con->prepare( $query );

// 4. sample product ID
$product_id=1;

// 5. this is the first question mark in the query
$stmt->bindParam(1, $product_id);

// 6. execute our query
$stmt->execute();

// 7. store retrieved row to the 'row' variable
$row = $stmt->fetch(PDO::FETCH_ASSOC);

// 8. show data to user
echo "<div>Name: " . $row['name'] . "</div>";
echo "<div>Description: " . $row['description'] . "</div>";
echo "<div>Price: $" . $row['price'] . "</div>";
?>

5.4 Open Your Browser

Run it by opening you your browser

5.5 Load read_one.php

On you browser window, type http://localhost/read_one.php

5.6 Output

You should see the following output.
run-php-script-2
Awesome! You are now ready to learn more about web programming and development.

6.0 Online Resources

Here in codeofaninja.com, we want to simplify learning for you to actually build something. But it is also important for you to read and study more. The following are my suggestions where to learn more.

You can always go back to the list above while you go along our series of web programming tutorials.

7.0 What's Next?

Today we have learned how to run a PHP script.

Before we learn more of PHP & MySQL programming, let us learn how to use a front-end framework that will beautify the user-interface of simple applications that we will build.

Up next: Learn Bootstrap Tutorial for Beginners

8.0 Related Tutorials

9.0 Some Notes

#1 Found An Issue?

If you found a problem with this code, please write a comment below. Please be descriptive about your issue. Please provide the error messages, screenshots (or screencast) and your test URL. Thanks!

Before you write a comment, remember to read this guide and our code of conduct.

#2 Become a true Ninja!

We constantly add new tutorials and improve our existing tutorials and source codes. Be one of the first to know an update by subscribing to our FREE newsletter. CLICK HERE TO SUBSCRIBE FOR FREE!

#3 Thank You!

Please share this post if you think this is a useful tutorial about how to run a PHP script. Thanks for learning here in codeofaninja.com!

Home jQuery

Simple PHP Pagination Script to Handle Your Growing Data

PHP Pagination is another very important feature when building any web application.

When you grow your data, it must not be displayed on a single page – it can cause a browser hang or very long vertical scroll-bar, so in short, it is not good for the user experience.

Simple PHP Pagination Script to Handle Your Growing Data

Contents:
1.0 Video Demo
2.0 Pagination in 5 Easy Steps
2.1 Retrieving the Records
2.2 First and Previous Page
2.3 Number Page Buttons
2.4 Next and Last Page Buttons
2.5 User Input Page Number
3.0 Download Source Code

1.0 Video Demo

Our final output.

2.0 Pagination in 5 Easy Steps

We are going the build this PHP paging script, in just 5 easy steps, see 3.1 to 3.5 below:

2.1 Retrieve the Records (Step 1)

This code will connect us to a MySQL database. Create "libs" folder. Open that folder. Create "db_connect.php" file and place the following code.

<?php
$host = "CHANGE_TO_YOUR_HOST";
$db_name = "CHANGE_TO_YOUR_DATABASE_NAME";
$username = "CHANGE_TO_YOUR_DATABASE_USERNAME";
$password = "CHANGE_TO_YOUR_DATABASE_PASSWORD";

try {
	$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}

//to handle connection error
catch(PDOException $exception){
	echo "Connection error: " . $exception->getMessage();
}
?>

Next, we will show the records in an HTML table.

<?php
// include for database connection
include 'libs/db_connect.php';

// page is the current page, if there's nothing set, default is page 1
$page = isset($_GET['page']) ? $_GET['page'] : 1;

// set records or rows of data per page
$recordsPerPage = 3;

// calculate for the query LIMIT clause
$fromRecordNum = ($recordsPerPage * $page) - $recordsPerPage;

// select all data
$query = "SELECT 
            id, firstname, lastname, username 
        FROM 
            users 
        ORDER BY 
            id desc
        LIMIT 
            {$fromRecordNum}, {$recordsPerPage}";
            
            /*
            page and its LIMIT clause looks like:
            1 = 0, 5
            2 = 5,10
            3 = 10,15
            4 = 15, 20
            5 = 20, 25
            */
        
$stmt = $con->prepare( $query );
$stmt->execute();

//this is how to get number of rows returned
$num = $stmt->rowCount();

//check if more than 0 record found
if($num>0){

    //start table
    echo "<table id='tfhover' class='tftable' border='1'>";
    
        //creating our table heading
        echo "<tr>";
            echo "<th>Firstname</th>";
            echo "<th>Lastname</th>";
            echo "<th>Username</th>";
        echo "</tr>";
        
        //retrieve our table contents
        //fetch() is faster than fetchAll()
        //http://stackoverflow.com/questions/2770630/pdofetchall-vs-pdofetch-in-a-loop
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        
            //extract row, this will make $row['firstname'] to just $firstname only
            extract($row);
            
            //creating new table row per record
            echo "<tr>";
                echo "<td>{$firstname}</td>";
                echo "<td>{$lastname}</td>";
                echo "<td>{$username}</td>";
            echo "</tr>";
        }
        
    echo "</table>";//end table

    // ***** Paging section will be here ***** 
}

2.2 First and Previous Page Buttons (Step 2)

The code below will show the "First" and "Previous" page buttons.

// ***** for 'first' and 'previous' pages
if($page>1){
    // ********** show the first page
    echo "<a href='" . $_SERVER['PHP_SELF'] . "' title='Go to the first page.' class='customBtn'>";
        echo "<span style='margin:0 .5em;'> << </span>";
    echo "</a>";
    
    // ********** show the previous page
    $prev_page = $page - 1;
    echo "<a href='" . $_SERVER['PHP_SELF'] 
            . "?page={$prev_page}' title='Previous page is {$prev_page}.' class='customBtn'>";
        echo "<span style='margin:0 .5em;'> < </span>";
    echo "</a>";
    
}
?>

2.3 Number Page Buttons (Step 3)

We are going to have some simple calculations here. The goal of this code is to display some page numbers that users can click.

<?php
// ********** show the number paging

// find out total pages
$query = "SELECT COUNT(*) as total_rows FROM users";
$stmt = $con->prepare( $query );
$stmt->execute();

$row = $stmt->fetch(PDO::FETCH_ASSOC);
$total_rows = $row['total_rows'];

$total_pages = ceil($total_rows / $recordsPerPage);

// range of num links to show
$range = 2;

// display links to 'range of pages' around 'current page'
$initial_num = $page - $range;
$condition_limit_num = ($page + $range)  + 1;

for ($x=$initial_num; $x<$condition_limit_num; $x++) {
    
    // be sure '$x is greater than 0' AND 'less than or equal to the $total_pages'
    if (($x > 0) && ($x <= $total_pages)) {
    
        // current page
        if ($x == $page) {
            echo "<span class='customBtn' style='background:red;'>$x</span>";
        } 
        
        // not current page
        else {
            echo " <a href='{$_SERVER['PHP_SELF']}?page=$x' class='customBtn'>$x</a> ";
        }
    }
}

?>

2.4 Next and Last Page Buttons (Step 4)

This will show the buttons with characters “>” and “>>” (meaning ‘next’ and ‘last’)

<?php
// ***** for 'next' and 'last' pages
if($page<$total_pages){
    // ********** show the next page
    $next_page = $page + 1;
    echo "<a href='" . $_SERVER['PHP_SELF'] . "?page={$next_page}' title='Next page is {$next_page}.' class='customBtn'>";
        echo "<span style='margin:0 .5em;'> > </span>";
    echo "</a>";
    
    // ********** show the last page
    echo "<a href='" . $_SERVER['PHP_SELF'] . "?page={$total_pages}' title='Last page is {$total_pages}.' class='customBtn'>";
        echo "<span style='margin:0 .5em;'> >> </span>";
    echo "</a>";
}
?>

2.5 Enter a Page Number (Step 5)

This will show a text-box where the user can enter a page number and submit it by hitting the enter key or clicking the ‘Go’ button.

<?php
// ***** allow user to enter page number
echo "<form action='" . $_SERVER['PHP_SELF'] . "' method='GET'>";
    echo "Go to page: ";
    echo "<input type='text' name='page' size='1' />";
    echo "<input type='submit' value='Go' class='customBtn' />";
echo "</form>"; 
?>

3.0 Download Source Code Examples

You can download all the code used in this tutorial for only $9.99 $5.55!

If you want to paginate with jQuery, here’s a post I made: Pagination with jQuery and PHP

Thank you for learning from our post about: Simple PHP Pagination Script!

Home PHP

Apache .htaccess RewriteRule Examples with PHP for Clean URLs

Our code for today will make your website URLs clean and attractive. Clean URLs are user and SEO friendly, it does not contain any query string like:

...page.php?param1=something&id=1111

Thus, giving our users and search engines (like Google) an idea what your link is all about once it was shared to social media or indexed by Google or Bing.

.htaccess rewriterule examples - first example is smashing magazine

We are going to use .htaccess (hypertext access) rewrite rules to achieve these clean URLs. The .htaccess file provide a directory level configuration that is supported by several web servers such as Apache.

Our post for today covers the following contents:

1.0 Existing Apache .htaccess Rewriterule Examples

2.0 Four Apache .htaccess Rewriterule Example Codes
2.1 URL with two parameters: letter and number
2.2 URL with one parameter: name of the PHP file
2.3 URL with one parameter: numbers
2.4 URL with one parameter: numbers with underscore

3.0 Complete .htaccess Code Used
4.0 Apache .htaccess RewriteRule Resources

1.0 Existing or Live Apache .htaccess Rewriterule Examples

Below are other example websites with clean URLs.

Of couse you know this blog, don't you?

Of couse you know this blog, don't you? :))

Chris' blog

Chris' blog

David’s blog

David’s blog

2.0 Four Apache .htaccess Rewriterule Examples

Our .htaccess and PHP files are placed in the "htaccess-clean-urls" folder.

.htaccess uses regular expressions to identify which PHP file will be loaded on the browser, based on the parameter(s) given.

We have 4 example codes below. Please note that "localhost" refers to "yoursite.com". I was using my local server when I did these examples so please keep it in mind.

2.1 URL with two parameters: letter and number

This URL:

http://localhost/htaccess-clean-urls/parameter_letter_and_number.php?param=post¶m2=143

Is equivalent to this clean URL:

http://localhost/htaccess-clean-urls/post/143

.htaccess code used:

RewriteRule ^([a-z]+)\/([0-9]+)\/?$ parameter_letter_and_number.php?param=$1&param2=$2 [NC]

PHP page used: parameter_letter_and_number.php

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>Clean URL with .htaccess by https://codeofaninja.com/</title>
        
        </style>
    </head>
<body>

<h1>Parameter: Letter and Number ONLY. This is parameter_letter_and_number.php</h1>
<?php 
echo "PARAMETER VALUE 1: " . $_REQUEST['param'];
echo "<br />";
echo "PARAMETER VALUE 2: " . $_REQUEST['param2'];
?>

</body>
</html>

Output screenshot:

.htaccess RewriteRule Example - parameter and number

2.2 URL with one parameter: name of the PHP file

This URL:

http://localhost/htaccess-clean-urls/login.php
http://localhost/htaccess-clean-urls/register.php

Is equivalent to this clean URL:

http://localhost/htaccess-clean-urls/login/
http://localhost/htaccess-clean-urls/register/

.htaccess code used:

RewriteRule ^([a-z]+)\/?$ $1.php [NC]

PHP pages used:

login.php

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>login - Clean URL tutorial with .htaccess and PHP by https://codeofaninja.com/</title>
        
        </style>
    </head>
<body>

<h1>Login. This is login.php</h1>

</body>
</html>

register.php

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>register - Clean URL with .htaccess and PHP by https://codeofaninja.com/</title>
        
        </style>
    </head>
<body>

<h1>Register. This is register.php</h1>

</body>
</html>

Output Screenshots:

login page clean url

register page rewriterule example

2.3 URL with one parameter: numbers

This URL

http://localhost/htaccess-clean-urls/parameter_number.php?param=5254

Is equivalent to this clean URL:

http://localhost/htaccess-clean-urls/5254/

.htaccess code used:

RewriteRule ^([0-9]+)\/?$ parameter_number.php?param=$1 [NC]

PHP page used: parameter_number.php

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>parameter is number - Clean URL with .htaccess and PHP by https://codeofaninja.com/</title>
        
        </style>
    </head>
<body>

<h1>Parameter: Number ONLY. This is parameter_number.php</h1>
<?php echo "PARAMETER VALUE: " . $_REQUEST['param']; ?>

</body>
</html>

Output Screenshot:

htaccess rewriterule number example

2.4 URL with one parameter: numbers with underscore

This URL:

http://localhost/htaccess-clean-urls/parameter_number_and_underscore.php?param=143_5254

Is equivalent to this clean URL:

http://localhost/htaccess-clean-urls/143_5254/

.htaccess code used:

RewriteRule ^([0-9_]+)\/?$ parameter_number_and_underscore.php?param=$1 [NC]

PHP page used: parameter_number_and_underscore.php

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>parameter is number and underscore- Clean URL with .htaccess and PHP by https://codeofaninja.com/</title>
        
        </style>
    </head>
<body>

<h1>Parameter: Number and Underscore ONLY. This is parameter_number_and_underscore.php</h1>
<?php echo "PARAMETER VALUE: " . $_REQUEST['param']; ?>

</body>
</html>

Output Screenshot:

htaccess rewriterule example - number and underscore

3.0 Complete .htaccess Code Used

The following codes are the ones we used in the examples above, put into one .htaccess file.

<IfModule mod_rewrite.c>

    RewriteEngine on

    RewriteRule ^([a-z]+)\/([0-9]+)\/?$ parameter_letter_and_number.php?param=$1&param2=$2 [NC]
    
    RewriteRule ^([a-z]+)\/?$ $1.php [NC]
    
    RewriteRule ^([0-9]+)\/?$ parameter_number.php?param=$1 [NC]
    
    RewriteRule ^([0-9_]+)\/?$ parameter_number_and_underscore.php?param=$1 [NC]
    
</IfModule>

4.0 .htaccess RewriteRule Resources

If you want to learn more, here's a mod_rewrite or regex cheat sheet.
An In Depth Guide to mod_rewrite for Apache
Apache mod_rewrite

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

If you have some questions or want to add more Apache .htaccess RewriteRule examples, please drop it in the comments section below! I will update this post once you did, thanks for your contribution!

shopping-cart-in-php-sessions
Home PHP

PHP and MySQL Shopping Cart Tutorial – Using SESSIONS To Store Cart Data

shopping-cart-in-php-sessions

Previously, we learned how to build a Shopping Cart with PHP & MySQL where we used a database to store cart items. Today, we will learn another version of it. We will use PHP session variables to store cart items.

Read more