How to highlight code syntax in a blog content

Jquery

Posted on 01 Oct 15 by Vickey
  379

If you are a blog  writer and you write computer code or computer languages in your blog and you want to make your code highlighted then you can use 'highlight.js'. Which code you want to make highlight put in pre tag. Here is an example below

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.8.0/styles/default.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/8.8.0/highlight.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<pre>
	<code>
		function __construct() 
		{
			parent::__construct();
			
		}
		function __destruct() 
		{
	       parent::__destruct() ;
	   	}
	</code>
</pre>

 

Search and replace code in all files of a directory by using php

php

Posted on 18 Sep 15 by Vickey
  537

In a editor normally we use find and replace operation. If i want to change a variable name in my file i use find and replace option and replace it by new variable name at each place. The same thing we can use for more then one files by using php script. If you want to replace a big part of a code you can use this method. For example once because of some virus insfection there was a big part of a code added in my all files and it was very difficult to remove this from each files so i created a script for this.
First i created a text file 'code.txt' and copy paste the code in this file which i want to remove from my all files.

$dir =  "/var/www/html/code.txt";

I stored this file at my web root directory and create a new file name as 'replace_code.php' and write the below script in this file

$path_to_string     =   "/var/www/html/code.txt";  // add unwanted code here

$dir =  "/var/www/html/myprojects/libraries/"; // here are my all files from which i want to remove unwanted code

$string             =   file_get_contents($path_to_string);

if (is_dir($dir)){
    
    if ($dh = opendir($dir)){
        while (($file = readdir($dh)) !== false){
           $ext = pathinfo($file, PATHINFO_EXTENSION);
            if($ext=='php'){
                $path_to_file = $dir.$file;
                if(file_exists($path_to_file)){
                $file_contents = file_get_contents($path_to_file);
                $file_contents = str_replace($string,"",$file_contents);
                file_put_contents($path_to_file,$file_contents);
                echo "File Path==>" . $path_to_file; echo "
";
               
                }
            }
        }
        closedir($dh);
    }
}
else{
    echo "There is no directory with this name". $dir;
}

and by running this script i finally removed all unwanted code from my all files. Please let me know if you have any question or comments on this script

How to read excel sheet in php

php

Posted on 09 Sep 15 by Vickey
  1612

For reading excel file in php download the PHPExcel library and include it in your php file where you want to read the sheet

require_once('PHPExcel/IOFactory.php');
require_once('PHPExcel.php');

If you want to read single sheet from a file then you can use the below code

function readSheet($sheet_path){

    $obj_excel = PHPExcel_IOFactory::load($sheet_path);

	$get_sheets='';
    $get_sheetData = "";

 	$sheet = $obj_excel->getSheetByName('Sheet1');
 	$get_sheetData=$sheet->toArray(null,true,true,true);
	echo "<pre>"; print_r($get_sheetData); 
}
readSheet('test.xls');

if you want to read all sheets then you can use

	function readSheet($sheet_path){

	    $obj_excel = PHPExcel_IOFactory::load($sheet_path);

		$get_sheets='';
	    $get_sheetData = array();
	 	$get_sheets = $obj_excel->getAllSheets();
	    foreach($get_sheets as $sheet){

	          $get_sheetData[]=$sheet->toArray(null,true,true,true);
	      
	    }
		echo "<pre>"; print_r($get_sheetData); 
	}

 

How to create Image Thumbnail component in cakephp

Cakephp

Posted on 04 Sep 15 by Vickey
  1478

Components provide us reusable code and logic that can be used into a controller. In cakephp we have number of core components like session, cookie, Auth and we can also create our custom component as per our requirement. In this blog I am going to create a component for creating a thumbnail image from a large image.

Step 1:- Create a file 'ImagethumbComponent' under /app/Controller/Component and add code

class ImagethumbComponent extends Component{

	function generateThumb( $src_path, $thumb_path, $thumb_width,$image_file_name ) 
	{
	
  		$src_dir 	= 	opendir( $src_path );

    	$img_path_info 	= 	pathinfo($src_path . $image_file_name);
    	if(strtolower($img_path_info['extension']) == 'jpg') 
		{
      		$image 	= 	imagecreatefromjpeg( "{$src_path}{$image_file_name}" );
		} 
		else if(strtolower($img_path_info['extension']) == 'png')
		{
	 		$image 	= 	imagecreatefrompng( "{$src_path}{$image_file_name}" );
		} 
		
		else if( strtolower($img_path_info['extension']) == 'gif'){
	 		$image 	= 	imagecreatefromgif( "{$src_path}{$image_file_name}" );
		} 
	 
	    $imgwidth = imagesx( $image );
	    $imgheight = imagesy( $image );
	    $new_thumb_width = $thumb_width;
	    $new_thumb_height = floor( $imgheight * ( $thumb_width / $imgwidth ) );
	    $temp_img = imagecreatetruecolor( $new_thumb_width, $new_thumb_height );
	    imagecopyresized( $temp_img, $image, 0, 0, 0, 0, $new_thumb_width, $new_thumb_height, $imgwidth, $imgheight );
	  
		if(strtolower($img_path_info['extension']) == 'jpg') 
		{
	      imagejpeg( $temp_img, "{$thumb_path}{$image_file_name}" );
		} 
		else if(strtolower($img_path_info['extension']) == 'png')
		{
		 	imagepng( $temp_img, "{$thumb_path}{$image_file_name}" );
		} 
		else  if ( strtolower($img_path_info['extension']) == 'gif' ){
		    imagegif( $temp_img, "{$thumb_path}{$image_file_name}" );
		} 
	}
}

here '$src_path' is path of directory of source image,  '$thumb_path' is path where new image will be save, '$thumb_width' is the width of thumb image and '$image_file_name' will the name of image file

Step 2:- How to use it

Open your controller in which you want to use it and add component

class UsersController extends AppController {

	public $components = array('Paginator','Imagethumb');

}

now call component function in your action

public function index() {

	$this->Imagethumb->generateThumb(WWW_ROOT .'uploads/', WWW_ROOT."uploads/uploadssmall_thumbs/",$thumb_img_width='100', $file_name='Music-tomasino.cz_.jpg');
}

here 'uploads' directory located under '/app/webroot' where your original image exist and thumb image will be save in 'uploadssmall_thumbs' directory

How to add image browse and image upload button in ckeditor

Others

Posted on 28 Aug 15 by Vickey
  2915

Ckeditor is a most populer text editor.We can change a textarea in to editor very easyly.But in some cases we need some extra functionality in our editor and we can fulfill these needs by adding some extra plugin.For example Color Button,Mathematical Formulas etc. you can use these addon or plugins by putting these in your ckeditor's plugin directory.If you want to insert an image in your editor you need to add image url but you can not upload an image with ckeditor.

 But by using some plugins you can do this. so lets add image upload functionality in ckeditor

1. Download Imageupload plugin

2. Download imgbrowse plugin

3. Extract these in to ckeditor plugins directory

4. Open your ckeditor config.js file and add extraplugin code

CKEDITOR.editorConfig = function( config ) {

	config.filebrowserBrowseUrl='/ckeditor/plugins/imagebrows/imgbrowse.html';
	config.filebrowserImageUploadUrl='/ckeditor/plugins/imgupload/imgupload.php';
};

5. Now open /ckeditor/plugins/imagebrows/imgbrowse.php and /ckeditor/plugins/imgupload/imgupload.php files and give your upload directory path

protected $root = '/uploads/';

$uploads = '/uploads/';

and you have done

 

How to set template by using library in codeigniter

Codeigniter

Posted on 25 Aug 15 by Vickey
  1685

By using library we can set themes in a codeigniter app. In codeigniter by defualt we load header and footer in every action.

public function index()
{
    $this->load->view('header');
    $this->load->view('index');
    $this->load->view('footer');
}

But if we use a library for this we can make it easy. so lets create a easy theme for codeigniter

1.Go to /application/libraries directory and create a file 'Layout.php' and add the below code

    class Layout 
    {
        var $codeigniter;
        function __construct() 
        {
            $this->codeigniter =& get_instance();
        }
        
        function load($template, $page_content = null, $data = null) 
        {
            
            if ( ! is_null( $page_content )) 
            {
                
                if (file_exists(APPPATH.'views/'.$template.'/'.$page_content )) 
                {
                    $page_content_path = $template.'/'.$page_content;
                }
                else if (file_exists(APPPATH.'views/'.$template.'/'.$page_content.'.php' )) 
                {
                    $page_content_path = $template.'/'.$page_content.'.php';
                }
                else if (file_exists(APPPATH.'views/'.$page_content )) 
                {
                    $page_content_path = $page_content;
                }
                else if (file_exists(APPPATH.'views/'.$page_content.'.php' )) 
                {
                    $page_content_path = $page_content.'.php';
                }
                else
                {
                    show_error('Requested view can not be load: ' . $template.'/'.$page_content.'.php');
                }
                 
                $content = $this->codeigniter->load->view($page_content_path, $data, TRUE);
                 
                if (is_null($data)) 
                {
                    $data = array('content' => $content);
                }
                else if (is_array($data))
                {
                    $data['content'] = $content;
                }
                else if (is_object($data))
                {
                    $data->body = $content;
                }
            }
            $this->codeigniter->load->view('layouts/'.$template, $data);
            
        }
        
    }

2. go to directory /application/config and open file 'autoload.php' and here set your template library

$autoload['libraries'] = array('Layout','database');

it will load your layout library

3. Now go to /application/views and create two file 'header.php' and 'footer.php' and put your html code accordingly

4. Under application/views  create a new directory 'layouts' and create a file 'main.php' under this and add the below code in the file

<?php $this->load->view('header'); ?>
<?php echo $content; ?>
<?php $this->load->view('footer'); ?>

you have created your first theme you can use this by using the below code

public function index()
{
    $data = array('title' => 'Your title',);
    $this->layout->load('main', 'content', $data);
}

here content is respected view of this action and main is the template name

How to use wepay payment gateway in cakephp

Cakephp

Posted on 22 Aug 15 by Vickey
  768

Wepay is a best payment gateway if you want to use croudfunding. In we pay payment gateway we can hold payment and capture it later when we want.For using we pay you need to create wepay stage account and download sdk from wepay site.In this post I am integration wepay in cakephp so for using wepay with cakephp follow these steps

1.Login in wepay and download sdk for php also take your  WEPAY CLIENT ID, WEPAY CLIENT SECRET,WEPAY ACCESS TOKEN and WEPAY ACCOUNT ID and define these in your bootstrap file or in app controller

define(WEPAY_CLIENT_ID,'tertre');
define(WEPAY_CLIENT_SECRET,'tedgt435ertrtre');
define(WEPAY_ACCESS_TOKEN,'gdfgterte5455');
define(WEPAY_ACCOUNT_ID,'345345');

2. Put your wepay sdk in app/Vender directory and import it in your controller

App::import('Vendor', 'wepay/wepay');

Now you are ready to use wepay code in your actions here are some example code for make payment with wepay

In the below code payment will be on hold beacuse I used 'auto_capture'     => FALSE if you do not want it on hold you can use TRUE

App::import('Vendor', 'wepay/wepay');
public function start_payment()
{
    $client_id = WEPAY_CLIENT_ID;
    $client_secret = WEPAY_CLIENT_SECRET;
    $access_token = WEPAY_ACCESS_TOKEN;
    $account_id = WEPAY_ACCOUNT_ID;
    
    $amount=10;
    $paymentReferenceId=22; // IF YOU ARE UPDATING YOUR DATABASE IT WILL BE THE PRIMARY KEY
    
    Wepay::useStaging($client_id, $client_secret);
    $wepay = new WePay($access_token);
    $response = $wepay->request('checkout/create', array(
    
	'account_id'        => $account_id,
	'amount'            => $amount,
	'short_description' => 'We pay testing',
	'reference_id' => $paymentReferenceId,
	'type'              => 'GOODS',
	'mode'=>'iframe',
	'fee_payer' => "Payee", 
	'redirect_uri' => "PUT HERE YOUR REDIRECT URL", 
	'callback_uri' => "GIVE YOUR IPN URL", 
	'auto_capture'     => FALSE
	
    ));
    $html='';
    $html	.='<div id="paymentBox"></div>';		
    $html .='<script type="text/javascript">';
    $html .='WePay.iframe_checkout("paymentBox", "'.$response->checkout_uri.'");';
    $html .='</script>';
    
    //$this->redirect($response->checkout_uri); // YOU WILL REDIRECT ON WEPAY FOR MAKE PAYMENT
}

and this code for ipn  if you want any responce after payment or you want to save payment record in your database

public function ipn(){
    
    $client_id = WEPAY_CLIENT_ID;
    $client_secret = WEPAY_CLIENT_SECRET;
    $access_token = WEPAY_ACCESS_TOKEN;
    $account_id = WEPAY_ACCOUNT_ID;
    
    Wepay::useStaging($client_id, $client_secret);
    $wepay = new WePay($access_token);
    $checkout = $wepay->request('checkout', array(
	'checkout_id' => $_POST['checkout_id'], 
    ));
    
    $reference_Id	=	$_POST['reference_id'];
    $checkout_id	=	$_POST['checkout_id'];
    $processing_fee	=	$checkout->fee;
    
    // SAVE checkout_id TO DATABASE
   
    
}

you can capture your payment by the below code

public function capture_funds(){
    
    $client_id = WEPAY_CLIENT_ID;
    $client_secret = WEPAY_CLIENT_SECRET;
    $access_token = WEPAY_ACCESS_TOKEN;
    $account_id = WEPAY_ACCOUNT_ID;
    
    //// FETCH RECORD FROM DATABASE
    $checkout_id='FETCH RECORD FROM DATABASE';
    
    Wepay::useStaging($client_id, $client_secret);
    $wepay = new WePay($access_token);
    $response = $wepay->request('checkout/capture', array(
	'checkout_id' => $checkout_id 
    ));
    
    
}

I hope it will help you for any question or query please comment

Thanks

Preview an image before upload on server

Jquery

Posted on 10 Aug 15 by Vickey
  3289

Html5 provide us an easy way to preview an image before upload it with the help of File API. File API is used for create a thumbnail preview of a image file before sending it to the server.With the help of File API you can get the file size and extension on the client side.Here I have an example code for preview a image before upload.

javascript Code

$( document ).ready(function() {
    $("#imagefile").change(function ()
    {
	    $("#img").show();
	    $("#img").attr("src",'TESTIMG.gif');
	    if (typeof(FileReader)!="undefined"){
	       
	        var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png)$/;
	        $($(this)[0].files).each(function () {
	            var getfile = $(this);
	            if (regex.test(getfile[0].name.toLowerCase())) {
	                var reader = new FileReader();
	                reader.onload = function (e) {
	                     $("#img").attr("src",e.target.result);
	                }
	                reader.readAsDataURL(getfile[0]);
	            } 
	            else {
	                alert(getfile[0].name + " is not image file.");
	                return false;
	            }
	        });
	    }
	     else {
	         alert("Browser does not supportFileReader.");
	     }
    });
});

Html Code


 
 
 

 

How to retrieving data in objects not array in cakephp

Cakephp

Posted on 06 Aug 15 by Vickey
  602

Cakephp by defualt return data as an array.For example if I want fetch a user's record from database i will use the below function and it will return
data in array form

public function index() {
        
        $data=$this->User->findById(4);
        pr($data); die;
        
}
Array
(
    [User] => Array
        (
            [id] => 4
            [name] => Kamryn Smitham
            [email] => ischmidt@hotmail.com
            [password] => qui
            [remember_token] => 
            [created_at] => 2015-05-08 09:22:18
            [updated_at] => 2015-05-08 09:22:18
        )

)

but in some cases we need data in objects so for get data in objects form we use 'Set::map()' function

public function index() {
        
        $data=$this->User->findById(4);
        $data = Set::map($data);
        pr($data); die;
        
}
stdClass Object
(
    [_name_] => User
    [id] => 4
    [name] => Kamryn Smitham
    [email] => ischmidt@hotmail.com
    [password] => qui
    [remember_token] => 
    [created_at] => 2015-05-08 09:22:18
    [updated_at] => 2015-05-08 09:22:18
)

here we get data as objects

What is the use of namespace in php

php

Posted on 06 Aug 15 by Vickey
  580

The word 'namespace' come in PHP version 5.3 by using namespace we can define more than one classes with the same name.If we have two or more class with the same name for example if we have a third party class which we are using in our project and we have also a core class with the same name then
when we create the object of class it will return a fatal error 'Fatal error: Cannot redeclare class'

class Login
{
    public function do_login()
    {
        return 'I am login as admin';
    }
}

class Login
{
    public function do_login()
    {
        return 'I am login as User';
    }
}

class Login
{
    public function do_login()
    {
        return 'Login By Facebook';
    }
}

$myobj = new Login();
echo $myobj->do_login();

But we can fix this error by using namespace. we will create a different namespace for each class

namespace Myproject\Admin;
class Login
{
    public function do_login()
    {
        return 'I am login as admin';
    }
}


namespace Myproject\User;
class Login
{
    public function do_login()
    {
        return 'I am login as User';
    }
}



namespace Myproject\FacebookLogin;
class Login
{
    public function do_login()
    {
        return 'Login By Facebook';
    }
}

$myobj = new Login();
echo $myobj->do_login();

now it will not give error but it will use the last class and you will see it will print 'Login By Facebook' but if want to use the all classes then there is need to use namespace
in this case we will create class object by using name space

$myobj = new \Myproject\Admin\Login();
echo $myobj->do_login();


$myobj = new \Myproject\User\Login();
echo $myobj->do_login();

$myobj = new \Myproject\FacebookLogin\Login();
echo $myobj->do_login();

or we can use this also

use Myproject\Admin\Login as admin_login;
$myobj = new admin_login();
echo $myobj->do_login();

 

www.000webhost.com