My Main Blog

Saturday 13 December 2014

MPDF not inserting image in pdf

MPDF not inserting image in pdf


You may face this problem while working with MPDF when you generate pdf file. this is due to mpdf is not accept full url of image.
for example this will no work:
"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjCUFHmg4DCI4m29aa_GeLclII2Jkkt6MrPJs-QrzPVDQL2pgXcta3D4hCvGCuFvTWIilBExj4bRd-hAaTrRNSA05SGEAHqNGeITZsQChBvRIDxc4IKy8hl3FwTUKGeEZmLhk7eRVd8624/s1600/video-watermark.jpg"

to overcome this problem you need to download that image in your server and use relative path while generating pdf. for example if your site name is : http://agalaxycode.blogspot.in/
then you need to create a folder "images" and save different name image from download  "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjCUFHmg4DCI4m29aa_GeLclII2Jkkt6MrPJs-QrzPVDQL2pgXcta3D4hCvGCuFvTWIilBExj4bRd-hAaTrRNSA05SGEAHqNGeITZsQChBvRIDxc4IKy8hl3FwTUKGeEZmLhk7eRVd8624/s1600/video-watermark.jpg". suppose you have downloaded and saved it with the name "aa.jpg" in "images" foler.
After that use this relative path in MPDF "images/aa.jpg".
MPDF uses relative path rather than absolute path

Wednesday 10 December 2014

mysqli stmt return result

How to return result from mysqli stmt prepare and bind_param statement.
Please note that you must install  MySQL Native Driver (mysqlnd) driver to use get_result();


DBClient.php

<?php
//error_reporting(E_ALL ^ E_DEPRECATED);
class DBClient {
var $host,$db,$user,$pass;
var $mysqli,$isDBConnect;
function __construct() {
    $this->host = "localhost";
    $this->db = "mydb";
    $this->user = "root";
    $this->pass = "pass";
    try {
          $this->mysqli = new mysqli($this->host, $this->user, $this->pass,$this->db );
        if ($this->mysqli->connect_error) {
            die('Error : ('. $this->mysqli->connect_errno .') '. $this->mysqli->connect_error);
        }
    } catch(Exception $ee) {
        $this->link=false;
           $this->isDBConnect=false;
    }
}

public function autocommit_false() {
    $this->mysqli->autocommit(FALSE);   
}

public function commit() {
    $this->mysqli->commit();   
}

public function rollback() {
    $this->mysqli->rollback();
}
public function close() {
    $this->mysqli->close();
}

}
?>


Part_Wise_Class.php
<?php
class Part_Wise_Class {   
    public function part_wise_get_part_nm($class_id,$subject_id) {
        $ssql = "SELECT part_id,part_nm from part_info WHERE class_id =? and subject_id=?";
        $db=new DBClient();
        $stmt = $db->mysqli->stmt_init();
        $stmt = $db->mysqli->prepare($ssql);
        $stmt->bind_param("ii",$class_id,$subject_id);
        $stmt->execute();
        $result = $stmt->get_result();
        $db->close();
        return $result;
   }   
}
?>



test.php

<?php
include_once("DBClient.php");
include_once("Part_Wise_Class.php");   
$part_wise=new Part_Wise_Class();
$class_id=$_GET['class_id'];
$subject_id=$_GET['subject_id'];
$result=$part_wise->part_wise_get_part_nm($class_id,$subject_id);
$rows = array();
while ($row = $result->fetch_array(MYSQLI_BOTH)) {
            echo $row['part_id'];
}
?>

Tuesday 2 December 2014

Php json and jquery

How to use PHP, JSON and JQUERY

It is very simple to use PHP, JSON and JQUERY. for this you needed to create two files.
One file is "index.html", second file is "util.php" and this file the class file "DBClient.php" that will responsible for mysql database connection and return result according the sql query.
index.html file call the util.php using jquery ajax metod. and util.php is calling the DBClient.php and create it's object and return the result. the result will parse in index.html and parse it.

 


index.html

<input type="button" class="button" value="get value" id="btn1" />
<script language="javascript" type="text/javascript">
$("#btn1").click(function() {
    $.ajax({
    type: 'POST',
    url: 'util.php',
    data: { para1: 'city' },
    dataType: 'json',
    success: function (data) {    
        $.each(data.class_info, function(idx, obj) {
            alert(obj.city_name+"===="+obj.city_id);
        });
    }
});   
});
</script>

// you can also use below code,but then you will use different jquery code as below:
 //print  json_encode($rows);
// $.each(data, function(idx, obj) {
//           alert(obj.city_name+"===="+obj.city_id);
//        });util.php

<?php
include_once("DBClient.php");

if(isset($_POST['para1'])) {
$num_rows =0;
$db=new DBClient();
// the "city" table holding the columns "city_id" and "city_name"
$rs_qlist=$db->exeQueryi("select *from city");
$rows = array();
while($r = mysqli_fetch_assoc($rs_qlist)) {
    $rows[] = $r;
}
print ' { "class_info" : ' . json_encode($rows) . ' } ';
}
?>

// you can also use below code,but then you will use different jquery code as below:
 //print  json_encode($rows);
// $.each(data, function(idx, obj) {
//           alert(obj.city_name+"===="+obj.city_id);
//        });


DBClient.php
<?php
//error_reporting(E_ALL ^ E_DEPRECATED);
class DBClient {
var $host,$db,$user,$pass;
var $mysqli,$isDBConnect;
function __construct() {
    $this->host = "localhost";
    $this->db = "mydb";
    $this->user = "root";
    $this->pass = "pass";
    try {
          $this->mysqli = new mysqli($this->host, $this->user, $this->pass,$this->db );
        if ($this->mysqli->connect_error) {
            die('Error : ('. $this->mysqli->connect_errno .') '. $this->mysqli->connect_error);
        }
    } catch(Exception $ee) {
        $this->link=false;
           $this->isDBConnect=false;
    }
}

public function exeQueryi($query) {
    try {
        $result = $this->mysqli->query($query);
        return $result;
    } catch(Exception $ee) {
        return (FALSE);
    }
}

public function autocommit_false() {
    $this->mysqli->autocommit(FALSE);   
}

public function commit() {
    $this->mysqli->commit();   
}

public function rollback() {
    $this->mysqli->rollback();
}
public function close() {
    $this->mysqli->close();
}
}
?>

Tuesday 25 November 2014

MPDF error Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in MPDF57\includes\functions.php

When you download MPDF from http://www.mpdf1.com/mpdf/index.php  and working on it with latest version of PHP you may encounter following error:

Deprecated: preg_replace(): The /e modifier is deprecated, use preg_replace_callback instead in MPDF57\includes\functions.php on line 99

So How can you solve this problem? follow below steps:

In file "MPDF57/mpdf.php"...........   Line 32140 :  comment listed below line of code:

$temp[2][$iterator] = preg_replace("/^([^\n\t]*?)\t/me","stripslashes('\\1') . str_repeat(' ', ( $tabSpaces - (mb_strlen(stripslashes('\\1')) % $tabSpaces)) )",$temp[2][$iterator]);

TO

//$temp[2][$iterator] = preg_replace("/^([^\n\t]*?)\t/me","stripslashes('\\1') . str_repeat(' ', ( $tabSpaces - (mb_strlen(stripslashes('\\1')) % $tabSpaces)) )",$temp[2][$iterator]);


And also in "MPDF57/includes/function.php"....... Line number: 96 and 97 comment 
listed below lines of code:

$str = preg_replace('/\&\#([0-9]+)\;/me', "code2utf('\\1',{$lo})",$str);
$str = preg_replace('/\&\#x([0-9a-fA-F]+)\;/me', "codeHex2utf('\\1',{$lo})",$str);

TO

//$str = preg_replace('/\&\#([0-9]+)\;/me', "code2utf('\\1',{$lo})",$str);
//$str = preg_replace('/\&\#x([0-9a-fA-F]+)\;/me', "codeHex2utf('\\1',{$lo})",$str);

if you are still getting any error then at the top of php page where you are using MPDF use one line of code:

error_reporting(E_ALL ^ E_DEPRECATED);

This will permanently remove the error.



Monday 24 November 2014

Create a simple page in Laravel using Controller

Create a simple page in Laravel using Controller


1) Create a "ClientpagesController.php" file in "app/controllers/" folder as below contents

<?php
class ClientpagesController extends \BaseController {
  public function contactus(){
     return View::make("contactme");
  }
}

2) Open "app/routes.php" file and paste as:
Route::get("contactus" , "ClientpagesController@contactus");

3) Now create "contactme.php" in "app/views/" folder with any matter,
<html>
...............................
...............................
...............................
</html>

4) Now open this url in browser:
http://localhost:90/MyLaravel/public/contactus

Create a simple page in Laravel using Route

Create a simple page in Laravel using Route

To configure Laravel look here  

Here I am creating a simple "aboutus" page using "Routes" in Laravel.
Follow below steps:

1) Open "app/routes.php" file and paste as:

Route::get('aboutus', function()
{
    return View::make('aboutus');

});

2) Now create "aboutus.php" in "app/views/" folder with any matter,
<html>
...............................
...............................
...............................
</html>

3) now open browser with this URL:
http://localhost:90/MyLaravel/public/aboutus




Saturday 22 November 2014

How to create controller in Laravel



There are two methods to create controller in Laravel.
A) By command prompt using "artisan controller:make" :
B) By manually creating controller.
To configure Laravel look here 

A) By command prompt using "artisan controller:make" :
I am assuming you are using wamp 2.5.
  1. Go to in the "c:\wamp\www\" folder
  2. Open command window and cd in "c:\wamp\www\"
    type "composer create-project laravel/laravel TestPro1" in command window; where composer is the exe file name "create-project" is the keywors, "laravel/laravel" is the keyword, "TestPro1" is the project name.
    This will create a folder "TestPro1" with supporting directories and files.
  3. Rename "server.php" to "index.php"
  4. Open command prompt in "d:\wamp\www\TestPro1" and type the                                    "php artisan controller:make MyController".   *Keep in mind that you must in the directory "TestPro1" when you issue the command in command window                            "php artisan controller:make MyController" and there must be a file "artisan", "composer.json", "composer.lock".
  5. This will create a file "MyController.php" in the "TestPro1\app\controllers". 
  6.  replace it's index() method as below
  7. public function index()
        {
             return "
    This is my web page in Laravel";
        }
  8. and register it by "Route::resource('welcome','WelcomeController');" in "routes.php" under "D:\wamp\www\TestPro1\app" folder.
  9. now you can see page content y http://localhost:/TestPro1/
B) By manually creating controller. 
Goto "d:\wamp\www\TestPro1\app\controllers" folder. create a file "MyController.php". and paste listed below content.

<?php
class MyController extends \BaseController {

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        //
        return "This is my web page in Laravel";
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store()
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
 
public function show($id)
    {
        //
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        //
    }

 /**
     * Update the specified resource in storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function update($id)
    {
        //
    }

 /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        //
    }
}

and register it by "Route::resource('welcome','WelcomeController');" in "routes.php" under "D:\wamp\www\TestPro1\app" folder.
now you can see page content y http://localhost:/TestPro1/

Laravel Installation and configuration

Laravel Installation and configuration

First you need to install Composer from this link:
https://getcomposer.org/download/
Here you can find both installer for windows and Unix.

If you are in windows then download here:  https://getcomposer.org/Composer-Setup.exe
Before installing Composer check that you must have PHP 5.3 or later.

  1. I am assuming that you are using Wamp 2.5
  2. Go to in the "c:\wamp\www\" folder
  3. open command window and cd in "c:\wamp\www\"
  4. type "composer create-project laravel/laravel TestPro1" in command window; where composer is the exe file name "create-project" is the keywors, "laravel/laravel" is the keyword, "TestPro1" is the project name.
  5. This will create a folder "TestPro1" with supporting directories and files.
  6. Rename "server.php" to "index.php"

open browser with this link :
http://localhost/TestPro1/index.php

You can see default page .




How to enable debug on in Laravel

How to enable debug on in Laravel

While working with laravel Framework you could face this error "Whoops, looks like something went wrong."
To overcome this error first you need to see what is the exact error in your code. to show exact error you need to set debug true in "app.php" file.

Follow below steps:
  1. Open "\app\config\app.php" file.
  2. Set " 'debug' => false" to 'debug' => true
 Now you can the exact error and fix the error.



Monday 17 November 2014

Url rewriting in Php

Very simple Url rewriting in Php

Suppose you have a website and you are operating it with query string as below:
http://www.yoursite.com/computer.php?company=asus&name=s56c

you are using two query string "company" and "name". In "company" you are passing "asus" on the other-hand in "name" you are passing "s56c". So the question is that how to convert

"http://www.yoursite.com/computer.php?company=asus&name=s56c"
                                   TO
"http://www.yoursite.com/computer/asus/s56c.html"

The url "http://www.yoursite.com/computer/asus/s56c.html" is not SEO friendly. so how to make it SEO friendly?

It is very simple. for this you need to create ".htaccess" in the root folder where your site's  files existing. paste listed below 3 lines in ".htaccess" file.


Options +FollowSymLinks
RewriteEngine on
RewriteRule computer/(.*)/(.*)\.html computer.php?company=$1&name=$2



And this is the content of your "computer.php" file

<?php
$company=$_GET['company'];
$name=$_GET['name'];
echo $company."--".$name;
?>


open the computer.php as "http://www.yoursite.com/computer/asus/s56c.html"


Access mysql data using mysqli_connect in PHP Class


Access mysql data using mysqli_connect in PHP with mysqli_query


Access mysql record by Object oriented method using class and object in PHP. Here is the class name is "DBClient" and it's method name is "exeQueryi()", that is return record from mysql table name "user_login". The __construct() method automatically called when we create any object of class "DBClient". Here I am using mysqli_connect,mysqli_query,mysqli_num_rows and mysqli_fetch_array.


<?php
class DBClient {
var $host,$db,$user,$pass;
var $linki,$isDBConnect;

function __construct() {
    $this->host = "localhost";
    $this->db = "mydb";
    $this->user = "root";
    $this->pass = "";
    try {
        $this->linki = mysqli_connect($this->host, $this->user, $this->pass,$this->db );
        if (!is_resource($this->linki)) {
            $this->isDBConnect=false;
        } else {
            $this->isDBConnect=true;
        }
    } catch(Exception $ee) {
        $this->linki=false;
           $this->isDBConnect=false;
    }
}

public function exeQueryi($query) {
    try {
        $result = mysqli_query( $this->linki,$query);
        return $result;
    } catch(Exception $ee) {
        return (FALSE);
    }
}
}
?>

<?php
$user_login="admin";
$user_pass="admin";
$sql=sprintf("SELECT *FROM user_info WHERE user_login = '%s' and user_pass='%s'", $user_login,$user_pass);
$db=new DBClient();
$rsLogin=$db->exeQueryi($sql);
$numRows = mysqli_num_rows($rsLogin);
if($numRows>0) {
        $rsLoginRow=mysqli_fetch_array($rsLogin);
        $user_login= $rsLoginRow['user_login'];
        $user_pass=$rsLoginRow['user_pass'];
echo "login found";
} else {
echo "login not found";
}
?>



Wednesday 5 November 2014

incorrect date time in PHP

incorrect date time in PHP

set timezone in PHP

You could be face a accurate Indian date time problem in PHP, because web server located to USA or any other country. that's why date and time which you are looking is wrong. but you can set it. so after set it you can get the correct indian time. you only need to set timezome as listed below:

date_default_timezone_set('Asia/Calcutta');

Export to excel in PHP

Export to excel in PHP

If you have a data and want to generate excel file of that data. then call this listed below function in php.



public function exportToExcelUtil($filename,$data) {
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Expires: 0");
echo  $data;
}

Validate email in PHP

Validate email in PHP

Here is the simple php function by this you can validate email which entered by any user.


public function checkEmail($mailID) {
$pat = "/^[a-zA-Z0-9._-]+@[a-zA-Z0-9-.]+\.[a-zA-Z. ]{2,6}$/";
if(preg_match($pat,$mailID)) {
return true;
} else {
return false;
}
}

Tuesday 4 November 2014

Access mysql data using Class in PHP

Access mysql data using Class in PHP using mysql_connect and use mysql_select_db and mysql_query



Access mysql record by Object oriented method using class and object in PHP. Here is the class name is "DBClient" and it's method name is "getDistrict", that is show records from mysql table name "district_names". The __construct() method automatically called when we create any object of class "DBClient".


<?php
class DBClient{
var $host;
var $db ;
var $user;
var $pass;
var $link,$isDBConnect;
var $isError,$errorValue;
function __construct() {
$this->host = "localhost";
$this->db = "dbname";
$this->user = "root"; 
$this->pass = ""; 
try {
$this->link = mysql_connect($this->host, $this->user, $this->pass);
if (!is_resource($this->link)) {
$this->isDBConnect=false;
}
else {
    mysql_select_db($this->db,$this->link);
$this->isDBConnect=true;
}
}
catch(Exception $ee){
$this->link=false;
   $this->isDBConnect=false;
}
}
public function exeQuery($query) {
try {
$result = mysql_query($query, $this->link);
return $result;
}
catch(Exception $ee){
return (FALSE);
}
}
public function getDistrict() {
 $res=false;
 try {
  $sSql="SELECT * FROM district_names";
  $res=$this->exeQuery($sSql);
  $rows = mysql_num_rows($res);
  if($rows>0) {
  } else {
$res=false;
  } 
 } catch(Exception $ee){
  $res=false; 
 } 
 return $res; 
}
}

$dd=new DBClient();
$cntDis=$dd->getDistrict();
if($cntDis) {
while($cntRow=mysql_fetch_array($cntDis)) {
$district_id= $cntRow['district_id'];
$districtname=$cntRow['districtname'];
echo $district_id.'====='.$districtname;
}
 }
?>

Friday 31 October 2014

Download image without cURL and with cURL in PHP

Download image without cURL and with cURL in PHP




<?php
// without cURL
$downloadImageUrl="http://fc04.deviantart.net/fs26/f/2008/072/b/1/Frozen_Galaxy_by_Vpr87.jpg";
////// Using without CURL
$img = file_get_contents($downloadImageUrl);
$file1 = dirname(__file__).'/aaa.jpg';
file_put_contents($file1, $img);



////// // with cURL
$fileName=$downloadImageUrl;
$header = array(
            "Accept-Encoding: gzip,deflate",
            "Accept-Charset: utf-8;q=0.7,*;q=0.7",
            "Connection: close"
        );
$useragent = 'Amit Kumar Gaur amitt800@gmail.com  http://amitkgaur.blogspot.com';
$file2 = dirname(__file__).'/bbb.jpg';
$curlObj=curl_init();
curl_setopt($curlObj, CURLOPT_HTTPHEADER, $header);
curl_setopt($curlObj, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlObj, CURLOPT_HEADER, false);
curl_setopt($curlObj, CURLOPT_USERAGENT, $useragent);
curl_setopt($curlObj, CURLOPT_CONNECTTIMEOUT, 999);
curl_setopt($curlObj, CURLOPT_TIMEOUT, 9999);
curl_setopt($curlObj, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
curl_setopt($curlObj, CURLOPT_URL, $downloadImageUrl);
$response = curl_exec($curlObj);
$return = false;
if(!curl_errno($curlObj)) {
    file_put_contents($file2, $response);
}
?>

Orbital chase paymentech gateway

Orbital Chase Paymentech Gateway Mark for Capture

Chase Orbital is one of the complex Payment Gateway. It's authorization process is very complex.
Here is the code for Orbital Chase Paymentech Gateway Mark for Capture Request in PHP.
You can frequently use it as free.


<?php
$url = "https://orbitalvar2.paymentech.net"; // testing
//$url = "https://orbital1.paymentech.net"; // production
$post_string="
<?xml version=\"1.0\" encoding=\"UTF-8\"?>
    <Request>
        <MarkForCapture>
            <OrbitalConnectionUsername>YOUR-USERNAME-HERE</OrbitalConnectionUsername>
            <OrbitalConnectionPassword>YOUR-PASSWORD-HERE</OrbitalConnectionPassword>
            <OrderID>123456789</OrderID>
            <Amount>8500</Amount>
            <BIN>000002</BIN>
            <MerchantID>YOUR-MERCHANT-ID-HERE</MerchantID>
            <TerminalID>001</TerminalID>
            <TxRefNum>4F320B79F23280DAE62777C80721F838FF13548D</TxRefNum>
        </MarkForCapture>
    </Request>";
    $header= "POST /authorize/ HTTP/1.0\r\n";
    $header.= "MIME-Version: 1.0\r\n";
    $header.= "Content-type: application/PTI\r\n";
    $header.= "Content-length: "  .strlen($post_string) . "\r\n";
    $header.= "Content-transfer-encoding: text\r\n";
    $header.= "Request-number: 1\r\n";
    $header.= "Document-type: Request\r\n";
    $header.= "Interface-Version: Test 1.4\r\n";
    $header.= "Connection: close \r\n\r\n";
    $header.= $post_string;
 
   //// just initialize curl here and post the data to the orbital server.


 
?>

Thursday 30 October 2014

Latitude Longitude by address in php

How to find Latitude Longitude by address in php.


You can find very easily Latitude and Longitude by given address with combination of Google map api and php.

<?php
    $address = 'Sector 37,Noida,India';
    $geocode = file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($address) . '&sensor=true');
    $geocode  = json_decode($geocode );
    echo 'Latitude:' . $geocode ->results[0]->geometry->location->lat;
    echo 'Longitude:' . $geocode ->results[0]->geometry->location->lng;

?>

Remove special character in php

Remove special character in php.


You have a website and in that website you have lot of form for user. user fill many data via that forms. some time user feed special characters that are unreadable. so how to remove that special characters before inserting in data base? here is the few lines of code that will do it.



<?php
$input = "Fóø Bår this is the php form data ?A?B?C?D //\\?......!@#$%^&*()_+"; // input text
$output = iconv("utf-8", "ascii//TRANSLIT//IGNORE", $input);
$output =  preg_replace("/^'|[^A-Za-z0-9\s-]|'$/", '', $output); // Remove utf-8 special characters except blank spaces
echo $output; // Results
?>