How to convert number to words in PHP

For example you need to convert a particular amount number into a word, let say

55892 – “fifty five thousand eight hundred ninety two”

To achieve this we can use below given code:

<?php
$ones = array(
“”,
” one”,
” two”,
” three”,
” four”,
” five”,
” six”,
” seven”,
” eight”,
” nine”,
” ten”,
” eleven”,
” twelve”,
” thirteen”,
” fourteen”,
” fifteen”,
” sixteen”,
” seventeen”,
” eighteen”,
” nineteen”
);
$tens = array(
“”,
“”,
” twenty”,
” thirty”,
” forty”,
” fifty”,
” sixty”,
” seventy”,
” eighty”,
” ninety”
);
$triplets = array(
“”,
” thousand”,
” million”,
” billion”,
” trillion”,
” quadrillion”,
” quintillion”,
” sextillion”,
” septillion”,
” octillion”,
” nonillion”
);
// recursive fn, converts three digits per pass
function convertTri($num, $tri) {
global $ones, $tens, $triplets;
// chunk the number, …rxyy
$r = (int) ($num / 1000);
$x = ($num / 100) % 10;
$y = $num % 100;
// init the output string
$str = “”;
// do hundreds
if ($x > 0)
$str = $ones[$x] . ” hundred”;
// do ones and tens
if ($y < 20)
$str .= $ones[$y];
else
$str .= $tens[(int) ($y / 10)] . $ones[$y % 10];
// add triplet modifier only if there
// is some output to be modified…
if ($str != “”)
$str .= $triplets[$tri];
// continue recursing?
if ($r > 0)
return convertTri($r, $tri+1).$str;
else
return $str;
}
// returns the number as an anglicized string
function convertNum($num) {
$num = (int) $num; // make sure it’s an integer
if ($num < 0)
return “negative”.convertTri(-$num, 0);
if ($num == 0)
return “zero”;
return convertTri($num, 0);
}
// Returns an integer in -10^9 .. 10^9
// with log distribution
function makeLogRand() {
$sign = mt_rand(0,1)*2 – 1;
$val = randThousand() * 1000000
+ randThousand() * 1000
+ randThousand();
$scale = mt_rand(-9,0);
return $sign * (int) ($val * pow(10.0, $scale));
}
// example of usage
echo “-5564 : “.convertNum(-5564).”<br>”;
echo “55892 : “.convertNum(55892);
?>

Session based flash messages

Quite a while ago, I grew tired of trying to come up with new and creative ways to display simple, one-time messages to users without crazy amounts of code for something that was frequently as trivial as “Saved!”.

Sessions are the obvious solution, however, without a single function that could both generate, AND display the messages, it still wasn’t any better.  And as usual, where there’s a will, and some code- there’s a way!


Get Best Multi-Purpose WordPress Theme

Get Best WordPress Theme

Before we get started, make sure that a session is started, otherwise a) no message will be displayed, and b) super fun headers already sent messages.

//Ensure that a session exists (just in case)
if( !session_id() )
{
    session_start();
}

//Actual function

/**
 * Function to create and display error and success messages
 * @access public
 * @param string session name
 * @param string message
 * @param string display class
 * @return string message
 */
function flash( $name = '', $message = '', $class = 'success fadeout-message' )
{
    //We can only do something if the name isn't empty
    if( !empty( $name ) )
    {
        //No message, create it
        if( !empty( $message ) &amp;& empty( $_SESSION[$name] ) )
        {
            if( !empty( $_SESSION[$name] ) )
            {
                unset( $_SESSION[$name] );
            }
            if( !empty( $_SESSION[$name.'_class'] ) )
            {
                unset( $_SESSION[$name.'_class'] );
            }

            $_SESSION[$name] = $message;
            $_SESSION[$name.'_class'] = $class;
        }
        //Message exists, display it
        elseif( !empty( $_SESSION[$name] ) &amp;& empty( $message ) )
        {
            $class = !empty( $_SESSION[$name.'_class'] ) ? $_SESSION[$name.'_class'] : 'success';
            echo '
.$class.‘” id=”msg-flash”>’.$_SESSION[$name].

;
            unset($_SESSION[$name]);
            unset($_SESSION[$name.'_class']);
        }
    }
}
//Set the first flash message with default class
flash( 'example_message', 'This content will show up on example2.php' );

//Set the second flash with an error class
flash( 'example_class', 'This content will show up on example2.php with the error class', 'error' );
//Displaying the messages
<?php flash( 'example_message' ); ?>
<?php flash( 'example_class' ); ?>

You can download the source from here

From: http://www.phpdevtips.com/

Extras: Addicted Upcoming

Remove index.php from url in Codeigniter using .htaccess

codeigniter_logo

CodeIgniter is one of the best and popular php framework available today. Sometimes we need to remove the default index.php that appears in the url of codeigniter application, so that the url becomes more clean and SEO friendly. With the help of .htaccess file it’s very easy to do so.
Paste the following code into your .htaccess file which is on root folder of website, it will remove default index.php from the url:

 

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]

 

Enjoy!!…

Setup HMVC with Codeigniter 3.0

codeigniter_logo

Follow below steps to setup HMVC in codeigniter(CI):

https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc/downloads

1. Download zip from above URL and copy them into application folder of CI

2. Rewrite HTACCESS

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]

3. Create folder called “modules” in application folder i.e. application/modules

4. Create a folder of particular module in modules folder. For e.g. application/modules/admin

5. Create controllers, models and views folder in particular module. For e.g.  in application/modules/admin module

6. Create controller file controllers folder of particular module. For e.g.  application/modules/admin/controllers/Admin.php

<?php

defined(‘BASEPATH’) OR exit(‘No direct script access allowed’);

class Admin extends CI_Controller {

    public function index() {

        $this->load->view(‘admin/dashboard’);

    }

}

7. Following will be the structure:

hmvc-structure

That’s it…

Extras: Addicted Upcoming

Easy SMTP email settings for WordPress

wp-mail-function

If you are facing problems with wp_mail function in sending emails, the solution is to use an SMTP server rather than relying on the webserver.

WordPress’s email function wp_mail is essentially a wrapper for phpmailer, a popular email class for PHP. WordPress has a little known action hook when phpmailer is initialized, phpmailer_init. This allows you to establish the phpmailer instance as using SMTP.

Here is a code snippet example with comments for each setting to configure WordPress to sent SMTP email:

/**
 * This function will connect wp_mail to your authenticated
 * SMTP server. This improves reliability of wp_mail, and 
 * avoids many potential problems.
 */
 
add_action( 'phpmailer_init', 'send_smtp_email' );

function send_smtp_email( $phpmailer ) {

	// Define that we are sending with SMTP
	$phpmailer->isSMTP();

	// The hostname of the mail server
	$phpmailer->Host = "smtp.example.com";

	// Use SMTP authentication (true|false)
	$phpmailer->SMTPAuth = true;

	// SMTP port number - likely to be 25, 465 or 587
	$phpmailer->Port = "587";

	// Username to use for SMTP authentication
	$phpmailer->Username = "yourusername";

	// Password to use for SMTP authentication
	$phpmailer->Password = "yourpassword";

	// Encryption system to use - ssl or tls
	$phpmailer->SMTPSecure = "tls";

	$phpmailer->From = "you@yourdomail.com";
	$phpmailer->FromName = "Your Name";
}

To use this snippet, you will need to adjust the settings according to your email service requirements. Check with your host.

The snippet, once configured, can be added to your theme’s functions.php file.

How to send email using PHPMailer

phpmailer

First, download PHPMailer using the direct link below:

PHPMailer_5.2.0.zip

After you have downloaded the file, unzip and extract it to your public_html. After unzipping the file we have public_html/PHPMailer_5.2.0. Next you will need to edit your web pages to use the PHPMailer code.

Add the PHPMailer code to your site:

<?php
require("class.PHPMailer.php");

$mail = new PHPMailer();

$mail->IsSMTP(); // set mailer to use SMTP
$mail->Host = "mail.hostname.com"; // specify main and backup server
$mail->SMTPAuth = true; // turn on SMTP authentication
$mail->Username = "USERNAME"; // SMTP username
$mail->Password = "PASSWORD"; // SMTP password

$mail->From = "from@example.com";
$mail->FromName = "Mailer";
$mail->AddAddress("josh@example.net", "Josh Adams");
$mail->AddAddress("ellen@example.com"); // name is optional
$mail->AddReplyTo("info@example.com", "Information");

$mail->WordWrap = 50; // set word wrap to 50 characters
$mail->AddAttachment("/var/tmp/file.tar.gz"); // add attachments
$mail->AddAttachment("/tmp/image.jpg", "new.jpg"); // optional name
$mail->IsHTML(true); // set email format to HTML

$mail->Subject = "Here is the subject";
$mail->Body = "This is the HTML message body <b>in bold!</b>";
$mail->AltBody = "This is the body in plain text for non-HTML mail clients";

if(!$mail->Send())
{
echo "Message could not be sent. <p>";
echo "Mailer Error: " . $mail->ErrorInfo;
exit;
}

echo "Message has been sent";
?>

That’s it.

Transfer files from one server to another server using PHP

 

server-to-server-php

Sometimes you need to move/migrate files to another server/hosting, and you/your client only have FTP access to the server. And to download these files and re-upload to another server can take a lot of time using FTP client such as Filezilla. FTP do not have zip – unzip functionality, so you need to upload it one by one. And server to server transfer is a lot faster than downloading and uploading the files.

You can use this simple PHP script to move files from one server to another server.

Note: It’s just a simple examples. you need to build your own auth/security method if needed.

1. Using PHP Copy to move files from server to server.

You can just create a php file in the destination server and load the file once in your browser. For example you add this code in http://destination-url/copy-files.php and in copy-files.php you add this php code:

  1. /**
  2.  * Transfer Files Server to Server using PHP Copy
  3.  * 
  4.  */
  5.  
  6. /* Source File URL */
  7. $remote_file_url = “http://origin-server-url/files.zip&#8221;;
  8.  
  9. /* New file name and path for this file */
  10. $local_file = ‘files.zip’;
  11.  
  12. /* Copy the file from source url to server */
  13. $copy = copy( $remote_file_url, $local_file );
  14.  
  15. /* Add notice for success/failure */
  16. if( !$copy ) {
  17.     echo “Doh! failed to copy $file…\n”;
  18. }
  19. else{
  20.     echo “WOOT! success to copy $file…\n”;
  21. }

2. Using PHP FTP to move files from server to server

Sometimes using PHP Copy didn’t work if the files is somehow protected by this method (hotlink protection maybe?). I did experience that if the source is from Hostgator it didn’t work.

But we can use another method. Using FTP (in PHP) to do the transfer using the code:

  1. /**
  2.  * Transfer (Import) Files Server to Server using PHP FTP
  3.  * 
  4.  */
  5.  
  6. /* Source File Name and Path */
  7. $remote_file = ‘files.zip’;
  8.  
  9. /* FTP Account */
  10. $ftp_host = ‘your-ftp-host.com’; /* host */
  11. $ftp_user_name = ‘ftp-username@your-ftp-host.com’; /* username */
  12. $ftp_user_pass = ‘ftppassword’; /* password */
  13.  
  14.  
  15. /* New file name and path for this file */
  16. $local_file = ‘files.zip’;
  17.  
  18. /* Connect using basic FTP */
  19. $connect_it = ftp_connect( $ftp_host );
  20.  
  21. /* Login to FTP */
  22. $login_result = ftp_login( $connect_it, $ftp_user_name, $ftp_user_pass );
  23.  
  24. /* Download $remote_file and save to $local_file */
  25. if ( ftp_get( $connect_it, $local_file, $remote_file, FTP_BINARY ) ) {
  26.     echo “WOOT! Successfully written to $local_file\n”;
  27. }
  28. else {
  29.     echo “Doh! There was a problem\n”;
  30. }
  31.  
  32. /* Close the connection */
  33. ftp_close( $connect_it );

using FTP you have more flexibility, the code above is using ftp_get to import the files from source server to destination server. But we can also use ftp_put to export the files (send the files) from source server to destination, using this code:

  1. /**
  2.  * Transfer (Export) Files Server to Server using PHP FTP
  3.  * 
  4.  */
  5.  
  6. /* Remote File Name and Path */
  7. $remote_file = ‘files.zip’;
  8.  
  9. /* FTP Account (Remote Server) */
  10. $ftp_host = ‘your-ftp-host.com’; /* host */
  11. $ftp_user_name = ‘ftp-username@your-ftp-host.com’; /* username */
  12. $ftp_user_pass = ‘ftppassword’; /* password */
  13.  
  14.  
  15. /* File and path to send to remote FTP server */
  16. $local_file = ‘files.zip’;
  17.  
  18. /* Connect using basic FTP */
  19. $connect_it = ftp_connect( $ftp_host );
  20.  
  21. /* Login to FTP */
  22. $login_result = ftp_login( $connect_it, $ftp_user_name, $ftp_user_pass );
  23.  
  24. /* Send $local_file to FTP */
  25. if ( ftp_put( $connect_it, $remote_file, $local_file, FTP_BINARY ) ) {
  26.     echo “WOOT! Successfully transfer $local_file\n”;
  27. }
  28. else {
  29.     echo “Doh! There was a problem\n”;
  30. }
  31.  
  32. /* Close the connection */
  33. ftp_close( $connect_it );

To make it easier to understand:

  • ftp_connect is to connect via FTP.
  • ftp_login is to login to FTP account after connection established.
  • ftp_close is to close the connection after transfer done (log out).
  • ftp_get is to import/download/pull file via FTP.
  • ftp_put is to export/send/push file via FTP.

After you import/export the file, always delete the PHP file you use to do this task to prevent other people using it.

ZIP and UNZIP Files using PHP

Of course to make the transfer easier we need to zip the files before moving, and unzip it after we move to destination.

ZIP Files using PHP

You can zip all files in the folder using this code:

  1. /**
  2.  * ZIP All content of current folder
  3.  * 
  4.  */
  5.  
  6. /* ZIP File name and path */
  7. $zip_file = ‘files.zip’;
  8.  
  9. /* Exclude Files */
  10. $exclude_files = array();
  11. $exclude_files[] = realpath( $zip_file );
  12. $exclude_files[] = realpath( ‘zip.php’ );
  13.  
  14. /* Path of current folder, need empty or null param for current folder */
  15. $root_path = realpath( );
  16.  
  17. /* Initialize archive object */
  18. $zip = new ZipArchive;
  19. $zip_open = $zip->open( $zip_file, ZipArchive::CREATE );
  20.  
  21. /* Create recursive files list */
  22. $files = new RecursiveIteratorIterator(
  23.     new RecursiveDirectoryIterator( $root_path ),
  24.     RecursiveIteratorIterator::LEAVES_ONLY
  25. );
  26.  
  27. /* For each files, get each path and add it in zip */
  28. if( !empty( $files ) ){
  29.  
  30.     foreach( $files as $name => $file ) {
  31.  
  32.         /* get path of the file */
  33.         $file_path = $file->getRealPath();
  34.  
  35.         /* only if it’s a file and not directory, and not excluded. */
  36.         if( !is_dir( $file_path ) && !in_array( $file_path, $exclude_files ) ){
  37.  
  38.             /* get relative path */
  39.             $file_relative_path = str_replace( $root_path, , $file_path );
  40.  
  41.             /* Add file to zip archive */
  42.             $zip_addfile = $zip->addFile( $file_path, $file_relative_path );
  43.         }
  44.     }
  45. }
  46.  
  47. /* Create ZIP after closing the object. */
  48. $zip_close = $zip->close();

UNZIP Files using PHP

You can unzip file to the same folder using this code:

  1. /**
  2.  * Unzip File in the same directory.
  3.  * @link http://stackoverflow.com/questions/8889025/unzip-a-file-with-php
  4.  */
  5. $file = ‘file.zip’;
  6.  
  7. $path = pathinfo( realpath( $file ), PATHINFO_DIRNAME );
  8.  
  9. $zip = new ZipArchive;
  10. $res = $zip->open($file);
  11. if ($res === TRUE) {
  12.     $zip->extractTo( $path );
  13.     $zip->close();
  14.     echo “WOOT! $file extracted to $path”;
  15. }
  16. else {
  17.     echo “Doh! I couldn’t open $file”;
  18. }

Other Alternative to ZIP / UNZIP File

Actually, if using cPanel you can easily create zip and unzip files using cPanel File Manager.

cpanel-zip-unzip-file-manager

I hope this tutorial is useful for you who need a simple way to transfer files from server to server.

Extras: Addicted Upcoming

PHP code to check if a string is valid JSON or not

json_logo-555px__1_

A function to check if a string is valid JSON (JavaScript Object Notation) or not. It takes json string as a parameter and returns true if valid, otherwise false.


function isValidJson($string){
$json = json_decode($string);
return (is_object($json) && json_last_error() == JSON_ERROR_NONE) ? true : false;
}

#How to use
if(isValidJson('{"a":1}')){
echo "Valid Json";
}else{
echo 'Invalid Json' ;
}

Upload a file using cURL and PHP

phpcurl
cURL is a great library. It can do just about anything that a normal web browser can do including send a file via a post request.

This makes it really easy to transmit files between computers. In my case, I was looking for an easy way to send images snapped by various webcam systems to a central server with php managing the images.

Here is a simple script to send a file with php/cURL via POST:

<?php
	$target_url = 'http://127.0.0.1/accept.php';
        //This needs to be the full path to the file you want to send.
	$file_name_with_full_path = realpath('./sample.jpeg');
        /* curl will accept an array here too.
         * Many examples I found showed a url-encoded string instead.
         * Take note that the 'key' in the array will be the key that shows up in the
         * $_FILES array of the accept script. and the at sign '@' is required before the
         * file name.
         */
	$post = array('extra_info' => '123456','file_contents'=>'@'.$file_name_with_full_path);
 
        $ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$target_url);
	curl_setopt($ch, CURLOPT_POST,1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
	$result=curl_exec ($ch);
	curl_close ($ch);
	echo $result;
?>

And here is the corresponding script to accept the file:

<?php
$uploaddir = realpath('./') . '/';
$uploadfile = $uploaddir . basename($_FILES['file_contents']['name']);
echo '<pre>';
	if (move_uploaded_file($_FILES['file_contents']['tmp_name'], $uploadfile)) {
	    echo "File is valid, and was successfully uploaded.\n";
	} else {
	    echo "Possible file upload attack!\n";
	}
	echo 'Here is some more debugging info:';
	print_r($_FILES);
	echo "\n<hr />\n";
	print_r($_POST);
        print "</pre>\n";
?>

That’s it.