How to POST values using cURL request and get the response


Make your POST variable first:


$params = array(
 'first_name' => 'Ziyed',
 'last_name' => 'Uddin',
 'email' => 'test@email.com'	
);

Write a function to prepare your cURL post variable:


private function build_params($params) {
 $return = array();
 foreach ($params as $key => $value) {
  $return[] = $key . '=' . urlencode($value);
 }
 return implode('&', $return);
}

Now define your cURL connection, send the request and get the response


$ch = curl_init(); // Create a cURL instance
curl_setopt($ch, CURLOPT_URL, 'http://www.yourwebsiteurl.com'); //Set your cURL POST url
curl_setopt($ch, CURLOPT_POSTFIELDS, $this->build_params($params)); //Prepare your cURL POST variable
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
$response = curl_exec($ch); //Execute cURL Request and Get the Response
curl_close($ch); // Close cURL instance

Advertisements

Unicode font like arabic or others displaying technique on webpage from mysql database at CakePHP or raw php


1. Make Sure that your database has UTF8 Character set, Run the following code

 ALTER DATABASE databasename CHARACTER SET utf8 COLLATE utf8_unicode_ci;
 

2. Make Sure that your table has UTF8 Character set and Collate utf8_unicode_ci or utf8_general_ci

 ALTER TABLE tablename CONVERT TO CHARACTER SET utf8 COLLATE utf8_unicode_ci;
 

3. Make Sure that your webpage has utf8 enable

 <meta charset="UTF-8">
 

4. Set utf8 before any mysql query in raw php

 mysql_query("SET NAMES utf8");
 

At CakePHP you can set this very easily at database config file:

Remove the comment line before ‘encoding’ and make this line available for execution.

 
 public $default = array(
	'datasource' => 'Database/Mysql',
	'persistent' => false,
	'host' => 'localhost',
	'login' => 'root',
	'password' => '',
	'database' => 'cake278',
	'prefix' => '',
	//'encoding' => 'utf8',
 );
 
 

Sorting a multi dimentional associative array with a array key value


Here we will sort the following multi dimentional associative array with comment_date key in DESC order.

Before start your sorting, your data may look like:


 $comments = Array
   (
		[0] => Array
			(
				[id] => 10				
				[customer_id] => 2047148
				[comment] => This is a test comment.
				[comment_date] => 2011-06-10 04:52:10
			)

		[1] => Array
			(
				[id] => 8				
				[customer_id] => 2047148
				[comment] => This is a test comment.
				[comment_date] => 2011-06-10 04:49:28
			)

		[2] => Array
			(
				[id] => 51
				[customer_id] => 2047080
				[comment] => This is a test comment.
				[comment_date] => 2015-11-10 10:23:28
			)

		[3] => Array
			(
				[id] => 43437
				[customer_id] => 1
				[comment] => This is a test comment.
				[comment_date] => 2011-12-22 13:33:05
			)

	)


So you need a php function that will manage your sorting list perfectly.


	function multi_sort($array, $key, $sort_flags = SORT_REGULAR, $order = SORT_DESC) {
        if (is_array($array) && count($array) > 0) {
            if (!empty($key)) {
                $mapping = array();
                foreach ($array as $k => $v) {
                    $sort_key = '';
                    if (!is_array($key)) {
                        $sort_key = $v[$key];
                    } else {
                        foreach ($key as $key_key) {
                            $sort_key .= $v[$key_key];
                        }
                    }
                    $mapping[$k] = $sort_key;
                }
                switch ($order) {
                    case SORT_ASC:
                        asort($mapping, $sort_flags);
                        break;
                    case SORT_DESC:
                        arsort($mapping, $sort_flags);
                        break;
                }
                $sorted = array();
                foreach ($mapping as $k => $v) {
                    $sorted[] = $array[$k];
                }
                return $sorted;
            }
        }
        return $array;
     }

Now time to call the function from your code to manage your sorting.


	
    $sorted_comments = $this->multi_sort($comments, array('comment_date'));   
	

After Sorting with multi_sort function your data will look like:


	Array
	(
		[0] => Array
			(
				[id] => 51
				[customer_id] => 2047080
				[comment] => This is a test comment.
				[comment_date] => 2015-11-10 10:23:28
			)

		[1] => Array
			(
				[id] => 43437
				[customer_id] => 1
				[comment] => This is a test comment.
				[comment_date] => 2011-12-22 13:33:05
			)

		[2] => Array
			(
				[id] => 10
				[customer_id] => 2047148
				[comment] => This is a test comment.
				[comment_date] => 2011-06-10 04:52:10
			)

		[3] => Array
			(
				[id] => 8
				[customer_id] => 2047148
				[comment] => This is a test comment.
				[comment_date] => 2011-06-10 04:49:28
			)

	)

php class to manage image upload, resize, crop


Save the class as “image_manage.php” under project root folder or where ever you want.


<?php

class image_manipulation {

    public $relative_path_to_point_img_folder;   //Relative folder path of image going to be uploaded. example "./upload/"
    public $absolute_path_to_point_img_folder;   //Absolute folder path of image going to be uploaded. example "http://www.mysite.com/upload/"
    public $fileFieldName;                       //Image File input field name
    public $allowedMimeTypes = array(
        'jpg|jpeg|jpe' => 'image/jpeg',
        'gif' => 'image/gif',
        'png' => 'image/png',
        'bmp' => 'image/bmp',
        'tif|tiff' => 'image/tiff',
        'ico' => 'image/x-icon'
    );

    /*
     *  constructor takes three arguments
     *  1st: relative path of image folder.  example "./upload/"
     *  2nd: absolute path of image folder.  example "http://www.mysite.com/upload/"
     *  3rd: image file input field name
     */    
    public function __construct($img_folder_relative_path, $img_folder_absolute_path, $img_file_field_name) {
        $this->relative_path_to_point_img_folder = $img_folder_relative_path;
        $this->absolute_path_to_point_img_folder = $img_folder_absolute_path;
        $this->fileFieldName = $img_file_field_name;
    }

    /*
     * validateType function used to check image type and error occured
     * @param
     * $data: $_FILES sould be passed to this variable of the image to be uploaded
     * @return: if ture return image type otherwise false
     */
    public function validateType($data) {
        if (isset($data[$this->fileFieldName]['type']) && $data[$this->fileFieldName]['error'] == 0) {
            return in_array($data[$this->fileFieldName]['type'], $this->allowedMimeTypes);
        }
        return false;
    }

    /*
     * validateUpload function used to check image upload error and size error
     * @param
     * $data: $_FILES sould be passed to this variable of the image to be uploaded
     * @return: true if no error occure otherwise return false
     */
    public function validateUpload($data) {
        if ($data[$this->fileFieldName]['error'] != 0) {
            return $this->uploadError[$data[$this->fileFieldName]['error']];
        }
        if ($data[$this->fileFieldName]['size'] == 0) {
            return false;
        }
        return true;
    }

    /**
     * @param array $fileInfo
     * array index
     * location: relative path to image file
     * width (int): width to resize
     * height (int): height to resize
     * propotional (bool): resize image ratio and original image ration will be same
     * direction (string x): 
     * crop (stirng zoom-in): zoom in crop image would be resized and crop the unmached part
     * quality (int 0~100): quality of the resized image
     * @return: new image url with absolute path
     */
    public function resize($fileInfo) {
        if (!isset($fileInfo['location'])) {
            return false;
        }

        //if not width and height provided return the original file
        if ((!isset($fileInfo['width']) || !$fileInfo['width']) && (!isset($fileInfo['height']) || !$fileInfo['height'])) {
            return $fileInfo['location'];
        }

        //load the image
        $imgInfo = getimagesize($fileInfo['location']);
        $originalWidth = $imgInfo[0];
        $originalHeight = $imgInfo[1];
        $type = $imgInfo[2];
        $propotional = isset($fileInfo['propotional']) ? $fileInfo['propotional'] : false;
        $propotionDirection = isset($fileInfo['direction']) ? $fileInfo['direction'] : 'x';
        $crop = isset($fileInfo['crop']) ? $fileInfo['crop'] : 'zoom-in';
        $quality = isset($fileInfo['quality']) ? $fileInfo['quality'] : 90;
        $srcX = 0;
        $srcY = 0;
        $dstX = 0;
        $dstY = 0;

        //set vars
        $originalRatio = $originalWidth / $originalHeight;
        $resizedWidth = isset($fileInfo['width']) ? $fileInfo['width'] : 0;
        $resizedHeight = isset($fileInfo['height']) ? $fileInfo['height'] : 0;
        if ($resizedWidth == 0) {
            $resizedWidth = round($originalRatio * $resizedHeight);
        }
        if ($resizedHeight == 0) {
            $resizedHeight = round($resizedWidth / $originalRatio);
        }

        if ($propotional) {
            if ($propotionDirection == 'x') {
                $resizedHeight = round($resizedWidth / $originalRatio);
            } else {
                $resizedWidth = round($originalRatio * $resizedHeight);
            }

            $resizedImageName = $resizedWidth . 'X' . $resizedHeight;
        } else {
            $resizedImageName = $resizedWidth . 'X' . $resizedHeight;

            $newRatio = $resizedWidth / $resizedHeight;

            if ($newRatio > $originalRatio) {
                if ($crop == 'zoom-in') {
                    $newWidth = $originalWidth;
                    $newHeight = $newWidth / $newRatio;
                    $resizedImageName .= '_w_zoom_in_';
                } else {
                    $newHeight = $originalHeight;
                    $newWidth = $newRatio * $newHeight;
                    $dstX = ($resizedWidth - $resizedHeight * $originalRatio) / 2;

                    $resizedImageName .= '_w_zoom_out_';
                }
            } else {
                if ($crop == 'zoom-in') {
                    $newHeight = $originalHeight;
                    $newWidth = $newRatio * $newHeight;
                    $srcX = $originalWidth / 2 - $newWidth / 2;

                    $resizedImageName .= '_h_zoom_in_';
                } else {
                    $newWidth = $originalWidth;
                    $newHeight = $newWidth / $newRatio;
                    $dstY = ($resizedHeight - ($resizedWidth / $originalRatio)) / 2;

                    $resizedImageName .= '_w_zoom_out_';
                }
            }

            $originalHeight = $newHeight;
            $originalWidth = $newWidth;
        }


        $resizedImageName .= $quality . '_' . str_replace(' ', '_', strtolower($fileInfo['file_name']));
        $destination = $this->relative_path_to_point_img_folder . $resizedImageName;
        $image_return_url = $this->absolute_path_to_point_img_folder . $resizedImageName;

        //check if file already exits
        if (file_exists($destination)) {
            return $destination;
        }

        $canvas = imagecreatetruecolor($resizedWidth, $resizedHeight);

        //transparency staff
        if ($type == IMAGETYPE_GIF || $type == IMAGETYPE_PNG) {
            //not working need to fix
            //imagefill($canvas, 0, 0, IMG_COLOR_TRANSPARENT);
            //imagesavealpha($canvas, true);
            //imagealphablending($canvas, true);
        }

        switch ($type) {
            case IMAGETYPE_GIF:
                $image = imagecreatefromgif($fileInfo['location']);
                break;
            case IMAGETYPE_JPEG:
                $image = imagecreatefromjpeg($fileInfo['location']);
                break;
            case IMAGETYPE_PNG:
                $image = imagecreatefrompng($fileInfo['location']);
                break;
            default:
                return false;
        }
        imagecopyresampled($canvas, $image, $dstX, $dstY, $srcX, $srcY, $resizedWidth, $resizedHeight, $originalWidth, $originalHeight);


        switch ($type) {
            case IMAGETYPE_GIF:
                imagegif($canvas, $destination);
                break;
            case IMAGETYPE_JPEG:
                imagejpeg($canvas, $destination, $quality);
                break;
            case IMAGETYPE_PNG:
                $quality = 9 - (int) ((0.9 * $quality) / 10.0);
                imagepng($canvas, $destination, $quality);
                break;
            default:
                return false;
        }

        //return $destination;
        return $image_return_url;
    }

    /**
     * @param 
     * $filename: only image file name going to be croped
     * x1 (int): x1 coordinate value
     * y1 (int): y1 coordinate value
     * x4 (int): x4 coordinate value
     * y4 (int): y4 coordinate value
     * @return: new image url with absolute path
     */
    public function crop($filename, $x1, $y1, $x4, $y4) {
        
        $filename_location = $this->relative_path_to_point_img_folder . $filename;
        
        if (!file_exists($filename_location)) {
            return false;
        }
                
        $imgInfo = getimagesize($filename_location);
        $originalWidth = $imgInfo[0];
        $originalHeight = $imgInfo[1];
        $type = $imgInfo[2];
        $new_width = ( $x4 - $x1 );
        $new_height = ( $y4 - $y1 );
        
        $cropedImageName = $x1.$y1."_".$new_width."X".$new_height."_".$filename;
        $destination = $this->relative_path_to_point_img_folder . $cropedImageName;
        $image_return_url = $this->absolute_path_to_point_img_folder . $cropedImageName;

        //check if file already exits
        if (file_exists($destination)) {
            return $image_return_url;
        }

        $canvas = imagecreatetruecolor($new_width, $new_height);
        
        switch ($type) {
            case IMAGETYPE_GIF:
                $image = imagecreatefromgif($filename_location);
                break;
            case IMAGETYPE_JPEG:
                $image = imagecreatefromjpeg($filename_location);
                break;
            case IMAGETYPE_PNG:
                $image = imagecreatefrompng($filename_location);
                break;
            default:
                return false;
        }        
        
        imagecopyresampled($canvas, $image, 0, 0, $x1, $y1, $new_width, $new_height, $new_width, $new_height);
        
        switch ($type) {
            case IMAGETYPE_GIF:
                imagegif($canvas, $destination);
                break;
            case IMAGETYPE_JPEG:
                $quality = 95;
                imagejpeg($canvas, $destination, $quality);
                break;
            case IMAGETYPE_PNG:
                $quality = 9 - (int) ((0.9 * $quality) / 10.0);
                imagepng($canvas, $destination, $quality);
                break;
            default:
                return false;
        }
        
        return $image_return_url;
    }

    /**
     * @param 
     * $data: $_FILES sould be passed to this variable of the image to be uploaded
     * @return: if uploaded successfully its return an array with values otherwise it return empty array
     */
    public function upload($data) {
        $original_file_name = $data[$this->fileFieldName]['name'];
        $new_file_name = time() . $original_file_name;
        $image_actual_file_location = $this->relative_path_to_point_img_folder . $new_file_name;
        $image_return_url = $this->absolute_path_to_point_img_folder . $new_file_name;
        $file_temp_name = $data[$this->fileFieldName]['tmp_name'];
        $arr = array();
        if ($this->validateType($data)) {
            if (move_uploaded_file($file_temp_name, $image_actual_file_location)) {
                $arr = array(
                    'original_file_name' => $original_file_name,
                    'new_file_name' => $new_file_name,
                    'image_relative_url' => $image_actual_file_location,
                    'image_absolute_url' => $image_return_url
                );
                return $arr;
            } else {
                return $arr;
            }
        } else {
            return $arr;
        }
    }

    /**
     * @param 
     * $img_name: Image name going to be removed completely.
     * @return: if removed it will return true otherwise false.
     */
    public function remove($img_name){        
        $destination = $this->relative_path_to_point_img_folder . $img_name;        
        if (!file_exists($destination)) {
            $this->error = 'File not found';
            return false;
        }        
        $res = unlink($destination);
        return $res;        
    }

}

?>

To make it workable at view please check the below how i am calling:


<?php
//include the image_manage.php class by defining its actual location
include './image_manage.php';  

//create an object of image_manipulation class
$image = new image_manipulation('./upload/', 'http://www.mysite.com/upload/', 'fileToUpload');
$url = $image->crop('mytest_image.jpg', 100, 50, 700, 400);

?>


Basic php crud operation to manage mysql database using pdo




<?php

class db extends PDO {
    
    public $pid = 'id'; // $pid is a primaty key of a table

    function __construct($dsn, $username, $passwd, $options = array()) {
        parent::__construct($dsn, $username, $passwd, $options);
    }

    /*
     * Function 'get_data_by_id' return single table row by an id
     * Arguments:
     * 1st:  Table name. example: 'images'
     * 2nd:  Row id to get the result, id must be a primary key of a table
     * 3rd:  Return type 'object' or 'array', Default is object
     * Returns the row if found
     * 
     *  $row = $db->get_data_by_id('images', 3, 'array');
     * 
     */
    function get_data_by_id($tablename, $id, $output_type = 'object') {
        $stmt = $this->prepare("SELECT * FROM $tablename WHERE $this->pid=?");
        $stmt->execute(array($id));
        if ($output_type == 'object') {
            $rows = $stmt->fetchAll(PDO::FETCH_OBJ);
        } else {
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
        return $rows;
    }
    
    

    /*
     * Function 'get_all_datas 'return table rows by any condition
     * Arguments:
     * 1st:  Table name. example: 'images'
     * 2nd:  Take associative array of condition. example:  array('id'=>3)
     * 3rd:  Return type 'object' or 'array'. Default is object
     * Returns the rows if found
     * 
     *  $param = array(
     *     'id' => 3,
     *  );
     *  $row = $db->get_all_datas('images', $param, 'array');
     * 
     */
    function get_all_datas($tablename, $param = array(), $output_type = 'object') {
        if (!empty($param)) {
            $keys = '';
            $values_ = array();
            $i = 1;
            foreach ($param as $key => $value) {
                if (!empty($key)) {
                    ($i == 1) ? $keys = $keys . "$key=?" : $keys = $keys . "AND $key=?";
                }
                $i++;
            }
            $values_ = array_values($param);
            $stmt = $this->prepare("SELECT * FROM $tablename WHERE $keys");
            $stmt->execute($values_);
        } else {
            $stmt = $this->prepare("SELECT * FROM $tablename");
            $stmt->execute();
        }

        if ($output_type == 'object') {
            $rows = $stmt->fetchAll(PDO::FETCH_OBJ);
        } else {
            $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
        }
        return $rows;
    }
    

    /*
     * Function 'insert' insert values to a table by condition
     * Arguments:
     * 1st:  Table name. example: 'images'
     * 2nd:  Take associative array of values, array key must be same as table column name. example:  array('city'=> 'Dhaka', 'name'=>'Mr. Jonson').
     * Returns last inserted id of a table.
     * 
     *  $param = array(
     *     'caption' => 'Edited',
     *     'original_file_name' => 'bangladehbeautyful.png',
     *     'file_name' => '54458888beautyful.png'
     *  );
     *  $last_inserted_id = $db->insert('images', $param);
     * 
     */
    function insert($tablename, $param) {
        
        $keys = '';
        $values = '';
        $values_ = array();
        $i = 1;
        foreach ($param as $key => $value) {
            if (!empty($key)) {
                ($i == 1) ? $keys = $keys . "`$key`" : $keys = $keys . ", `$key`";
                ($i == 1) ? $values = $values . "?" : $values = $values . ", ?";
            }
            $i++;
        }
        $values_ = array_values($param);
        $sql = "INSERT INTO $tablename($keys) VALUES($values)";
        $stmt = $this->prepare($sql);
        $stmt->execute($values_);
        return $this->lastInsertId();
    }
    

    /*
     * Function 'update' update values to a table by id
     * Arguments:
     * 1st:  Table name. example: 'images'
     * 2nd:  Take an id of a table, id must be a primary key of a table.
     * 3rd:  Take associative array of values, array key must be same as table column name. example:  array('city'=>'Dhaka', 'name'=>'Mr. Jonson').
     * Returns the counter how much row updated.
     * 
     *  $param = array(
     *     'caption' => 'Edited',
     *     'original_file_name' => 'bangladehbeautyful.png',
     *     'file_name' => '54458888beautyful.png'
     *  );
     *  $row_effected = $db->update('images', 2, $param);
     * 
     */
    function update($tablename, $id, $param) {
        $keys = '';
        $values = '';
        $values_ = array();
        $i = 1;
        foreach ($param as $key => $value) {
            if (!empty($key)) {
                ($i == 1) ? $keys = $keys . "$key=?" : $keys = $keys . ", $key=?";
            }
            $i++;
        }
        $values_ = array_values($param);
        array_push($values_, $id);
        $sql = "UPDATE $tablename SET $keys WHERE $this->pid=?";
        $stmt = $this->prepare($sql);
        $stmt->execute($values_);
        return $stmt->rowCount();
    }
    
    /*
     * Function 'delete' delete the table row by id
     * Arguments:
     * 1st:  Table name. example: 'images'
     * 2nd:  Take an id of a table, id must be a primary key of a table.
     * Returns the counter how much row updated.
     * 
     *  $row_effected = $db->delete('images', 2);
     * 
     */
    function delete($tablename, $id) {
        $sql = "DELETE FROM $tablename WHERE $this->pid=:id";
        $stmt = $this->prepare($sql);
        $stmt->bindValue(':id', $id, PDO::PARAM_STR);
        $stmt->execute();
        return $stmt->rowCount();
    }

}

$HostName = 'localhost';
$dbName = 'dbname';
$username = 'root';
$password = '';


$db = new db("mysql:host=$HostName;dbname=$dbName;charset=utf8", $username, $password);
//$db->id = 'id';

?>


Mailchimp integration with php


Please Download MCAPI class from git url given below

https://github.com/ziyed/mailchimp_php_class.git

Or

http://apidocs.mailchimp.com/api/downloads/#php

How to use mailchimp php class and manipulate user data.


<?php 

  require_once 'MCAPI.php';

  // grab an API Key from http://admin.mailchimp.com/account/api/
  $api = new MCAPI($apiKey);

  // grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
  // Click the "settings" link for the list - the Unique Id is at the bottom of that page. 
  $list_id = "58d58d54d5s";
                    
  $merge_vars = Array(                       
	'FNAME' => 'First Name'
  );

  if ($api->listSubscribe($list_id, $useremail, $merge_vars) === true) {
	// It worked!
  } else {
	// An error ocurred, return error message
  }

?>