Category Archives: PHP

Google Recaptcha – Defeating spam got a lot easier

Earlier version of the recaptcha was just a pain in the ass. For developers to implement and also for users who had to squint and type distorted text. Remember this?

2015-04-10 09_07_07-Customizing the Look and Feel of reCAPTCHA - reCAPTCHA — Google Developers

 

Well Google changed that with this new version where the user only had to Tick a check box and some magic happened and it checked if the user is authentic. (Its not clear on their website how exactly they do it, but i think they check for data that has been captured by their analytics tools or cookies or something to make sure that your human)

2015-04-10 09_10_56-reCAPTCHA_ Easy on Humans, Hard on Bots

Here also it falls back to a captcha text if it cant determine if your human so there is a fail safe built in.

Anyway the good news for developers is we can quickly add captcha to our pages without going through a tedious process. So I’m going to give the steps down here that I used to implement recaptcha on my free invoicing tool. (Invoicer)

Step 1.

Go to https://www.google.com/recaptcha/intro/index.html and click the get Recaptcha buton.

2015-04-10 09_14_19-reCAPTCHA_ Easy on Humans, Hard on Bots

Step 2.

Enter the Label and domains that this recaptcha needs to be active on, and click register.

2015-04-10 09_15_43-reCAPTCHA_ Easy on Humans, Hard on Bots

Step 3.

On the next screen you will get the instructions on how to add the recaptcha into your page. But Ill list down the steps here as well.

On client side,

add the script file in the head tag.

 <script src='https://www.google.com/recaptcha/api.js'></script>

Add the following code at the end of the form where you want the captcha widget to appear,

 <div class="g-recaptcha" data-sitekey="6LddIgUTAAAAAEky5noUKqsnA3QPysdXQ05WFsnB"></div> 

On server side,

You need to capture the value generated by client side code and post it to google for verification. This bit can be a bit tricky.

How I did it on Google App Engine is to do a url fetch. Think you will be able to do the same by using curl. Or also ajax.

 <?php

/* recaptcha validation */
<pre>$data = ['secret' => 'YOUR OWN SECRET KEY', 'response' => $_REQUEST['g-recaptcha-response']];
$data = http_build_query($data);
$context = [
    'http' => [
        'method' => 'POST',
        'header' => "custom-header: custom-value\r\n" .
            "custom-header-two: custom-value-2\r\n",
        'content' => $data
    ]
];
$context = stream_context_create($context);
$result = file_get_contents('https://www.google.com/recaptcha/api/siteverify', false, $context);

You will get a json response and if the success attribute it true you can proceed with processing the form values.

<pre>$success_status = json_decode($result)->success;

if($success_status) {

}</pre>

 

More information can be found here regarding verification.

The trickiest part is handling it on server side. If you have any problems with that please post on the comments section and I will try and help. 🙂

Advertisements

Invoicer by Suren Dias – Free invoicing tool for freelancers

HI I created this free invoicing tool aimed at freelancers. Its currently at a very early stage. Can only create pdf invoice at the moment from the data that user enters.

Tool – http://invoicer.surendias.com/

Source – https://github.com/surendias/Invoicer

Sorting multidimensional arrays by multiple keys in PHP

This is a very cool method to sort a multidimensional array by multiple keys. I didn't think of this though. :) Found this while searching for a solution on stackoverflow link is given here.
$mylist = array(
    array('ID' => 1, 'title' => 'Boring Meeting', 'event_type' => 'meeting'),
    array('ID' => 2, 'title' => 'Find My Stapler', 'event_type' => 'meeting'),
    array('ID' => 3, 'title' => 'Mario Party', 'event_type' => 'party'),
    array('ID' => 4, 'title' => 'Duct Tape Party', 'event_type' => 'party')
);

# get a list of sort columns and their data to pass to array_multisort
$sort = array();
foreach($mylist as $k=>$v) {
    $sort['title'][$k] = $v['title'];
    $sort['event_type'][$k] = $v['event_type'];
}
# sort by event_type desc and then title asc
array_multisort($sort['event_type'], SORT_DESC, $sort['title'], SORT_ASC,$mylist);

Google Cloud SQL – How to import an existing database

Ok here is a small guide on how to import your existing mysql database into Google Cloud SQL.

Step 1

Export your database into a sql file.

If your on PHPMyAdmin, select your database and click export tab and export the tables as required.

localhost  localhost  survey-plan-searcher  phpMyAdmin 3.4

 

Step 2

Go into Google Cloud Console. And Select your Project.

https://console.developers.google.com/

Step 3

Create a bucket on Google Cloud Storage.

Google Developers Console - Mozilla Firefox_2014-08-10_19-16-33

Step 4

Upload your MySQL database export .sql file into the created bucket.

Google Developers Console - Mozilla Firefox_2014-08-10_19-17-47

Step 5

Go into Cloud SQL section on the Google Cloud Console. And Select your instance.

Google Developers Console - Mozilla Firefox_2014-08-10_19-18-36

Step 6

Click the import button on the top bar.

_2014-08-10_19-22-26

Step 7

Enter the path of the bucket you created on Google Cloud Storage and the .sql file you uploaded.

Google Developers Console - Mozilla Firefox_2014-08-10_19-23-57

Step 8

Important – Click the Show advanced options… link and enter your Google Cloud SQL database name in the given text box. (This is if your SQL file doesn’t specify Use Database statement.) – If you dont do this you will get an error saying “An unknown error occurred” Which is a bit cryptic, but now you know why you get it. 🙂

Google Developers Console - Mozilla Firefox_2014-08-10_19-24-46

Step 9

Click the Ok Button.

Step 10

Click the Operations tab to see the progress.

Google Developers Console - Mozilla Firefox_2014-08-10_19-25-37

Ok Now your database file is imported successfully. You can start working with your database in your app engine application.

How to host your website on Google App Engine for free.

Ok Guys and Girls. Today I am going to teach you how to host your website on Google App Engine for free. This is quite easy, but please note that this method is for a website that doesnt use a Database. So if your website is using a CMS like WordPress this will not work. You can do that as well by using the method given on this link but you have to pay for Google Cloud SQL then.

Ok lets get started.

Step 1

First go to the following link,

https://console.developers.google.com

You will get a screen like following,

Google Developers Console - Google Chrome_2014-06-08_15-42-42Step 2

Click the big red button that says “Create Project”

You will get the following screen,

Google Developers Console - Google Chrome_2014-06-08_15-46-27

On that enter a project name and a project id, for this you can use Your website name as the project name and create a unique project id (you can combine yourname-yourwebsite to get a unique name)

Then click the Create button to create the project. This will take a few moments.

Step 3

Ok now your project is created. Now you just need to upload your website content to the App Engine project you just created.

To do that first you need to download Google App Engine Launcher which is a simple tool available for all platforms. It comes free when you download the Google App Engine SDK which you can do by going to this link.

https://developers.google.com/appengine/downloads#Google_App_Engine_SDK_for_PHP

Download the setup file for your platform and install it. (You need to have python installed on your computer for the Google App Engine Launcher to work, Get Python from here. Make sure you get Python 2.7.6 newer version is sometimes not supported.)

Then you will get an icon like this on your desktop or start menu.

_2014-06-08_15-52-06

Click on that to launch The Google App Engine Launcher.

Greenshot image editor - _2014-06-08_15-52-06

Step 4

Ok on the Google App Engine Launcher.

Go to file->Create New Application

on the window that you get,

Google Developers Console - Google Chrome_2014-06-08_15-59-14

Enter the project id you gave on the Google Cloud Console when you created the new project.

Browse and select the Parent Directory of the website files on your computer. This creates a folder under that parent directory in the project id you gave. So you will have to move the website files into that folder.

Select PHP as the runtime.

Click Create button.

Step 5

This will create App Engine files in the website files folder.

In that you need to edit the App.yaml file. This is where you tell the app engine app where all your files are and how you want them to be launched.

So go to your website project folder on your local computer and open app.yaml file on notepad. Or on the Google App Engine Launcher click the newly created project and Click the Edit Icon.

Greenshot image editor - Google Developers Console - Google Chrome_2014-06-08_15_2014-06-08_16-04-50

I am adding my app.yaml file here to show you how you need to add code sections to load Javascript, Css, images and main url files.

Like I have given you will have to give all the static file folders in your website. Here in my website all traffic is directed to my index.php file. If you have other files you will have to modify that part like following.

For each of your links you have to give like above.

Ok now your ready to upload the files.

Step 6

Go to your Google App Engine Launcher, Select your project and click the Deploy button at the top.

app

It will start uploading the files. Once completed you can go to the following link to see if you website is working properly.

projectid.appspot.com (project id is the unique project id you gave when you created the project on Google Cloud Console.)

Ok If your website is working fine, the Next step is to point your domain to the Google App Engine hosted website.

Step 7

Go to Google Cloud Console (https://console.developers.google.com)

Click your project Name

Google Developers Console - Google Chrome_2014-06-08_16-15-53

You will get your project view. This has lots of functionality, explore at your own risk 😉

For our purpose click the App Engine link on the side bar, under that you get a link called Settings Click on that. After that click the custom domains tab on the top.

_2014-06-08_16-18-46

 

Ok on that its pretty self evident what you need to do, But let me explain each step.

1. Verify you domain

Enter your domain and click verify, it will open a new tab and show you verification options. Easiest way is to select your domain provider and click verify. If your domain registrar is not in the list, click Other and you will get a TXT record which you need to add to your DNS settings. (If you dont know how to edit your DNS better to check with your domain provider. It can mess up your website if you get it wrong.)

2. Select your domain in the second step and it will show you DNS records as the Step 3, which you need to add to your DNS Settings.

Google Developers Console - Google Chrome_2014-06-08_16-26-18

That’s all. It looks like a long process, but its quite simple. Try and let me know how you did. 🙂

Sending Emails With Google App Engine PHP

So here are some tips on how to send email using PHP on Google App Engine. This basically covers how I overcame the problems when I tried to implement this.

Check https://developers.google.com/appengine/docs/php/mail/ before starting to read my version.

Sending HTML – Use htmlBody in the mail options to include the message body this will preserve your html code. other wise it will just print the html code out.

require_once 'google/appengine/api/mail/Message.php';

use google\appengine\api\mail\Message; // make sure this is at top of the page

// ...

$message_body = "...";

$mail_options = (
    "sender" => "admin@example.com",
    "to" => "user@example.com",
    "subject" => "Your example.com account has been activated.",
    "textHTML" => $message_body
);

try {
    $message = new Message($mail_options);
    $message->send();
} catch (InvalidArgumentException $e) {

}

including the Message.php file – If you include the use statement partway down the page it will not work. I had a hard time figuring this out but just php common sense. Make sure you add the use statement on the top of the page before any php code. Then you will be fine.

Also make sure the from address is a Google Apps for Business Account, then things are just plain easy.