Posts

4th TIP Student Congress with the Alumni – 2014

Hey guys! I'm sorry to disappoint you but I'm not going to publish some codes today. I was invited to be a guest speaker at our institute's student congress with the alumni - for the second time. It was held yesterday, January 23, 2014 in the Technological Institute of the Philippines, QC.

Read more

Home PHP

Generating JSON String with PHP

Today I'm going to share this code I used to generate a JSON string with data from MySQL database.

For those not yet familiar, JSON is a lightweight data interchange format (like XML but it is lightweight).

It has been used by companies like Google and Facebook in their APIs.

Recently, I needed a JSON string to get data from the web to the Android app I'm working on.

The PHP file gets a parameter company_id to select few data related to a company.

Please note that this is not a production ready code, but is very useful to get you started and can serve as quick reference.

Read more

Optimize Image for Web Using Photoshop and Thoughts on Faster Web Pages

This post is supposed to be a quick-tip on how you can optimize your images for web pages. But it feels like I also want to give some thoughts about website speed. There are many websites saying that your images must be optimized for the web, that should be updated and say, "your images must be optimized for web and mobile devices" in which the amazing Adobe Photoshop can help us with.
Home Lists+

12 jQuery Questions and Answers You Should Be Reading on StackOverflow

Hi guys! Below are twelve of the jQuery related questions and answers on StackOverflow that I found very useful during development. I opted to compile them here because I feel good reading those brilliant questions and answers by coders from around the world. Enjoy!

  1. How would I know if an element is hidden?
  2. Sometimes you want some elements of your page to be visible, and if it is not visible, you want to tell the user about it. For example, a user must have a selection of data first before proceeding to new operation. If he has no selection (div is hidden), you can do a prompt that he must select something.

  3. How do I get selected text in select box?
  4. Ah, a drop-down list? Link # 2 above shows you how to get the user drop down list selection.

  5. How to redirect a page?
  6. Useful if you want to your users to see a page after an AJAX request, or you just want them to be redirected. I’ve written another example here, jQuery: Redirect onClick

  7. How would I know if a checkbox is checked or unchecked?
  8. For example, you want to enable a delete button if the user selected at least one data to delete, else, the delete button is disabled. I’ve written another example here: Check or Uncheck Checkboxes with jQuery And Get Selected with PHP

  9. How to select a child element?
  10. Teaches us how to select a child element and do it with faster performance (see the comment by Paul Irish).

  11. event.preventDefault() vs. return false
  12. I use return false; when I want to prevent a page refresh after clicking a submit button and doing an AJAX request.

  13. Example of using jQuery .closest() method.
  14. I use jQuery .closest() method on selecting an element within a table with several rows. I probably have to write an example in another blog post, ha!

  15. How would I know the existence of an element?
  16. Useful if you want to perform something if an element exists in your page. The faster way is using if ($(selector).length) {}

  17. How would I know which radio button is selected?
  18. This is how you will know if a user is a male or female, using jQuery!

  19. How to select multiple classes?
  20. Sometimes you want to to something to multiple classes at once. There’s another example here.

  21. How to select an element by its name, not by class or id?
  22. If you’re more familiar with an element’s name or don’t want to add a class or id name, you can use this cool technique.

  23. What if Google hosted jQuery is blocked?
  24. In some countries, Google’s domain name is banned. So if you are using a Google hosted jQuery library, you’re site won’t work. Link # 12 above shows you the fall back.

This can be the first part of the list, you can add more in the comments section below, or on our Facebook, Twitter or Google+!
And as always, thanks for reading!

Home PHP

Email Activation Code in PHP

Email activation or verification is one requirement when you’re building an app with a membership feature. Our Email Activation Code in PHP will help you with that!

This is one way to detect if there’s really a person behind the submitted email address. An email address is considered invalid if no person was able to open it and click the activation link.

Although nowadays, there are some alternative ways to verify the validity of an email address or user. Some systems prefer the old school method, like what this post covers.

Email Activation Code in PHP

OAuth

The alternative way I was talking about is by using a social network login. Facebook, Twitter, Google+ and even Microsoft is providing something called an OAuth (Open Authorization) login.

In simple scenario, have you ever seen a "Login with Facebook" button? We see one in StackOverflow login:

oauth-login-email-validation

Unfortunately, we don't cover OAuth login in this post.

Basic Flow

The following steps shows the basic flow how email activation works.

  1. User fills up your sign up or registration form and submit it to the system.
  2. System generates unique activation code which acts like a “key”
  3. System sends a link with the activation code to the email provided during the sign up form.
  4. User opens his email inbox, found the system email and click the link with the activation code. This is like using the “key” to “unlock the door” which represents your application.
  5. User was sent to a link saying ‘email was activated’

Where are these happening?

To give you a clearer picture where in our code the steps above happens:

Steps 1 to 3 happens in sign_up.php.

Step 4 happens in the user’s email provider such as GMail, Y! Mail, etc. User should receive something like this:

email-verification-link-sent

Step 5 happens in our activate.php

Let’s Code!

Alright, so the technologies used in this code are mostly PHP and MySQL.

Create your database and name it 'email_activation_db'. Here’s the database table structure that can be used, we name it as the ‘users’ table.

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `nickname` varchar(32) NOT NULL,
  `email` varchar(264) NOT NULL,
  `verified` int(11) NOT NULL COMMENT '0=no, 1=yes',
  `verification_code` varchar(264) NOT NULL,
  `created` datetime NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO `users` (`id`, `nickname`, `email`, `verified`, `verification_code`, `created`, `modified`) VALUES
(135, '', 'ninjazhai30@gmail.com', 1, '2e729fe3ded03c139b289213db2b3159', '2016-08-13 16:42:28', '2016-08-13 08:42:46');

libs/db_connect.php – for database connection, this file has the following code:

<?php
$host = "localhost";
$db_name = "email_activation_db";
$username = "root";
$password = "";

try {
	$con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
    echo "Connection error: " . $exception->getMessage();
}
?>

sign_up.php – where the sign up form and processing of user input is located. The following code is inside sign_up.php file.

<?php
// if the sign up form was submitted
if($_POST){

	$email = isset($_POST['email']) ? $_POST['email'] : "";

	// posted email must not be empty
	if(empty($email)){
		echo "<div>Email cannot be empty.</div>";
	}

	// must be a valid email address
	else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
		echo "<div>Your email address is not valid.</div>";
	}

	else{

		include 'libs/db_connect.php';

		// check first if record exists
		$query = "SELECT id FROM users WHERE email = ? and verified = '1'";
		$stmt = $con->prepare( $query );
		$stmt->bindParam(1, $email);
		$stmt->execute();
		$num = $stmt->rowCount();

		if($num>0){
			echo "<div>Your email is already activated.</div>";
		}

		else{

			// check first if there's unverified email related
			$query = "SELECT id FROM users WHERE email = ? and verified = '0'";
			$stmt = $con->prepare( $query );
			$stmt->bindParam(1, $email);
			$stmt->execute();
			$num = $stmt->rowCount();

			if($num>0){

				// you have to create a resend verification script
				echo "<div>Your email is already in the system but not yet verified.</div>";
			}

			else{

				// now, compose the content of the verification email, it will be sent to the email provided during sign up
				// generate verification code, acts as the "key"
				$verificationCode = md5(uniqid("yourrandomstringyouwanttoaddhere", true));

				// send the email verification
				$verificationLink = "https://codeofaninja.com/demos/php-examples/email-activation-php-script/activate.php?code=" . $verificationCode;

				$htmlStr = "";
				$htmlStr .= "Hi " . $email . ",<br /><br />";

				$htmlStr .= "Please click the button below to verify your subscription and have access to the download center.<br /><br /><br />";
				$htmlStr .= "<a href='{$verificationLink}' target='_blank' style='padding:1em; font-weight:bold; background-color:blue; color:#fff;'>VERIFY EMAIL</a><br /><br /><br />";

				$htmlStr .= "Kind regards,<br />";
				$htmlStr .= "<a href='https://codeofaninja.com/' target='_blank'>The Code of a Ninja</a><br />";


				$name = "The Code of a Ninja";
				$email_sender = "no-reply@codeofaninja.com";
				$subject = "Verification Link | The Code Of A Ninja | Subscription";
				$recipient_email = $email;

				$headers  = "MIME-Version: 1.0\r\n";
				$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
				$headers .= "From: {$name} <{$email_sender}> \n";

				$body = $htmlStr;

				// send email using the mail function, you can also use php mailer library if you want
				if( mail($recipient_email, $subject, $body, $headers) ){

					// tell the user a verification email were sent
					echo "<div id='successMessage'>A verification email were sent to <b>" . $email . "</b>, please open your email inbox and click the given link so you can login.</div>";


					// save the email in the database
					$created = date('Y-m-d H:i:s');

					//write query
					$query = "INSERT INTO
								users
							SET
								email = ?,
								verification_code = ?,
								created = ?,
								verified = '0'";

					$stmt = $con->prepare($query);

					$stmt->bindParam(1, $email);
					$stmt->bindParam(2, $verificationCode);
					$stmt->bindParam(3, $created);

					// Execute the query
					if($stmt->execute()){
						// echo "<div>Unverified email was saved to the database.</div>";
					}else{
						echo "<div>Unable to save your email to the database.";
						//print_r($stmt->errorInfo());
					}

				}else{
					die("Sending failed.");
				}
			}


		}

	}

}

// show your sign up or registration form
echo "<form action='" . $_SERVER['PHP_SELF'] . "' method='post'>";
	echo "<input type='email' name='email' placeholder='Enter your email address to subscribe' required />";
	echo "<input type='submit' value='Subscribe' />";
echo "</form>";
?>

For sending the verification email, we used the PHP mail() function but you can also use a library like PHPMailer if you want to use SMTP such as of GMail.

activate.php – it has one job, update the the unverified to verified email address.

<?php
include 'libs/db_connect.php';

// check first if record exists
$query = "SELECT id FROM users WHERE verification_code = ? and verified = '0'";
$stmt = $con->prepare( $query );
$stmt->bindParam(1, $_GET['code']);
$stmt->execute();
$num = $stmt->rowCount();

if($num>0){

	// update the 'verified' field, from 0 to 1 (unverified to verified)
	$query = "UPDATE users
				set verified = '1'
				where verification_code = :verification_code";

	$stmt = $con->prepare($query);
	$stmt->bindParam(':verification_code', $_GET['code']);

	if($stmt->execute()){
		// tell the user
		echo "<div>Your email is valid, thanks!. You may now login.</div>";
	}else{
		echo "<div>Unable to update verification code.</div>";
		//print_r($stmt->errorInfo());
	}

}else{
	// tell the user he should not be in this page
	echo "<div>We can't find your verification code.</div>";
}
?>

Live Demo

Please note that this demo is live. If you enter your email and click the subscribe button, you will receive an email with the activation link. If you click it, you will be subscribed here in our code blog.

Download Email Activation Code in PHP

You can get the source code by following the whole, well detailed tutorial above.

But isn’t it more convenient if you can just download the complete source code we used, and play around it?

The source code of this tutorial is part of our 30+ useful Web Programming source code package. Each item in the package has its own tutorial like the one above.

If you are just starting out to learn web programming and serious about learning more, this is the right package for you. Click green button below to see the what is included in the package and download it there.


Need email activation code only? But the code now using the green button below.

Related Source Code

You can download our PHP Login System & User Management Module as well. This source code is about PHP Login System.

It will help you understand how to login and logout functionality works. Sign up email verification, user registration, and forgot password features are included as well.

Thanks for studying our email activation code in PHP!

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 Lists+

Creating Social Media Icons for Your Website using CSS

In almost every website we see today, there are links to their social media accounts. I think it is a standard now. It’s like, you’re not cool if you don’t have a Facebook and Twitter account!

Recently, I was using Google drive to host my CSS and image files. Now, I removed it. Why?

Because Google drive slows down my website! During the use of Google drive hosted CSS and images, the average load time of this wesbite is around 10-20 seconds for new visitors.

After I removed it, it is now around less than 5 seconds!

Creating Social Media Icons for Your Website using CSS

My new social media icons. :)

I decided not to use any third party CSS code. I wanted to create my own social media icons, and I did! (see the screenshot above or the lower right corner of this page for live demo)

I think the icons I made are so cute that I thought of sharing it to you guys (I appreciate a tweet, like or +1 before you use it!). It loads fast, contains few lines of CSS and HTML code, and it doesn’t use any images! Here’s how I did it, below are the CSS and HTML code I used.

HTML code:

<div id="socialMediaIcons">

    <a class="facebook" href="https://www.facebook.com/CodeOfANinja" title="Facebook" target="_blank">f</a>
    
    <a class="twitter" href="http://twitter.com/ninjazhai" title="Twitter" target="_blank">t</a>
    
    <a class="googleplus" href="https://plus.google.com/b/101266899643014043497/101266899643014043497/posts" title="Google+" target="_blank">g+</a>
    
    <a class="rss" href="https://www.codeofaninja.com/feeds/posts/default?alt=rss" title="RSS" target="_blank">r</a>
    
    <a class="email" href="http://feedburner.google.com/fb/a/mailverify?uri=TheCodeOfANinja" title="Email" target="_blank">@</a>
    
</div>

CSS code:

#socialMediaIcons{
    margin: 0 auto;
    text-align:center;
}

#socialMediaIcons a{
    border-radius: 3px;
    color:#fff;
    font-family: arial;
    font-size:1em;
    height:2.5em;
    padding:1em;
    text-align:center;
    width:2.5em;
    -moz-border-radius: 3px;
    -webkit-border-radius: 3px;
}

#socialMediaIcons a:hover{
    color:#fff;
    text-decoration:none;
}

.facebook { background:#4c66a4; padding:2px 10px; }
.twitter { background:#33bcef; padding:2px 10px; }
.googleplus { background:#D2412E; padding:2px 3px; }
.rss { background:#fa9b39; padding: 2px 6px; }
.email { background:#00D8CC; padidng: 2px 6px; }

And… that’s how I created my new social media icons using CSS!