Tag Archives: php

Inserting recaptcha to your form

Captcha is good to reduce spam. One of most popular captcha used is recaptcha.

This is how it looks like. Familiar?

captcha

To implement it is very easy. Will take less than 10 minutes of your time.

1. Get your public and private key

https://www.google.com/recaptcha/admin/create

2. Include class file

Download recaptcha library file for PHP (with some sample files)

3. Insert code in form page

1
2
3
4
5
6
7
8
<form method="post" action="verify.php">
        <?php
          require_once('recaptchalib.php');
          $publickey = "your_public_key"; // you got this from the signup page
          echo recaptcha_get_html($publickey);
        ?>
        <input type="submit" />
</form>

4. Insert code to validate code in process page

1
2
3
4
5
6
7
8
9
10
11
12
13
14
require_once('recaptchalib.php');
  $privatekey = "your_private_key";
  $resp = recaptcha_check_answer ($privatekey,
                                $_SERVER["REMOTE_ADDR"],
                                $_POST["recaptcha_challenge_field"],
                                $_POST["recaptcha_response_field"]);
 
  if (!$resp->is_valid) {
    // What happens when the CAPTCHA was entered incorrectly
    die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
         "(reCAPTCHA said: " . $resp->error . ")");
  } else {
    // Your code here to handle a successful verification
  }

PHP code protection

I’m looking for PHP encoding application to encrypt some of my PHP code. Reasons – to avoid it from being accidently altered and to avoid from people looking into the code (especially those with some important db and system config in it)

Here are some solutions for PHP encoding

  1. PHP Obfuscator – free (native windows, open source)
  2. zend guard
  3. ioncube (usd199)
  4. SourceGuardian (usd199)
  5. PHPshadow (EUR50 per domain)
  6. more..

Some other related discussion on license/code protection:

  1. stackoverflow
  2. webmasterworld
  3. PADL (a php class) – PHP Application Distribution License System

Run PHP file with cron

This is the script to paste in cron to run a PHP file

php -f /home/username/public_html/cron-daily.php

Anyway I haven’t tried to put the script outside public_html directory. Logically PHP cannot run outside web root folder unless you set it to run outside web root folder in apache.

And you can use this script to run PHP by full URL. Even script on other server

lynx -dump http://yourdomain.com/yourscript.php >/dev/null 2>&1

Add xx month or xx day to a date

To add xx day or xx month to a date using this method.

1
2
3
4
5
6
7
8
9
10
11
12
$mktime = explode("-",$rs_loan['datestart']);
 
$x = 5;
 
//to add $x to day
$newdate = date("Y-m-d",mktime(0,0,0,$mktime[1],$mktime[2]+$x,$mktime[0]));
 
//to add $x to month
$newdate = date("Y-m-d",mktime(0,0,0,$mktime[1]+$x,$mktime[2],$mktime[0]));
 
//to add $x to year
$newdate = date("Y-m-d",mktime(0,0,0,$mktime[1],$mktime[2],$mktime[0]+$x));

Append 0’s in front of a running number

Sometimes we need to fix a number to say 5 digits. e.g. 00012. Here’s the code to append the 0’s in front of the numbers so that you can just save the number without 0’s in front in your database.

1
2
$anum = 123;
echo str_pad($anum, 5, '0', STR_PAD_LEFT);

Result will be displayed as 00123

Alternative to explode function (PHP)

When you have a set of string in an array or strings separated by comma (or any other character), you can use these two alternative. I prefer the second one 🙂

1
2
3
4
5
6
7
8
9
10
 
//code with explode
$list = explode(",",$astring);
foreach ($astring as $value) {
  echo $value;
  echo "<br />";
}
 
//code with str_replace
echo str_replace(",", "<br />", $astring);

Function to create and read csv file

Found this function from bin-co. Haven’t tested the function but I think it might be useful for me in the future.

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//Get the result of the query as a CSV stream.
//http://www.bin-co.com/php/scripts/csv_import_export/
function CSVExport($query) {
    $sql_csv = mysql_query($query) or die("Error: " . mysql_error()); //Replace this line with what is appropriate for your DB abstraction layer
 
    header("Content-type:text/octect-stream");
    header("Content-Disposition:attachment;filename=data.csv");
    while($row = mysql_fetch_row($sql_csv)) {
        print '"' . stripslashes(implode('","',$row)) . "\"\n";
    }
    exit;
}
 
//Import the contents of a CSV file after uploading it
//http://www.bin-co.com/php/scripts/csv_import_export/
//Aruguments : $table - The name of the table the data must be imported to
//                $fields - An array of fields that will be used
//                $csv_fieldname - The name of the CSV file field
function CSVImport($table, $fields, $csv_fieldname='csv') {
    if(!$_FILES[$csv_fieldname]['name']) return;
 
    $handle = fopen($_FILES[$csv_fieldname]['tmp_name'],'r');
    if(!$handle) die('Cannot open uploaded file.');
 
    $row_count = 0;
    $sql_query = "INSERT INTO $table(". implode(',',$fields) .") VALUES(";
 
    $rows = array();
 
    //Read the file as csv
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $row_count++;
        foreach($data as $key=>$value) {
            $data[$key] = "'" . addslashes($value) . "'";
        }
        $rows[] = implode(",",$data);
    }
    $sql_query .= implode("),(", $rows);
    $sql_query .= ")";
    fclose($handle);
 
    if(count($rows)) { //If some recores  were found,
        //Replace these line with what is appropriate for your DB abstraction layer
        mysql_query("TRUNCATE TABLE $table") or die("MySQL Error: " . mysql_error()); //Delete the existing records
        mysql_query($sql_query) or die("MySQL Error: " . mysql_error()); // and insert the new ones.
 
        print 'Successfully imported '.$row_count.' record(s)';
    } else {
        print 'Cannot import data - no records found.';
    }
}

Replace line break with

This code is used to replace line break saved in database to
in html display

$astring = str_replace(chr(13) . chr(10), "", $astring);

Updated: Actually there is a built in function for this as follow

echo nl2br($astring);