Menus

Friday, 16 October 2015

PHP Programming Tips


INDEX
PHP - add item to beginning of associative array
PHP sizeof() Function
Split multiple lines and input them in separate row in a database
How to print a debug log
PHP prepend leading zero before single digit number
Show a number to 2 decimal places
Comparing Dates in PHP
Adding days to Date in PHP





PHP - add item to beginning of associative array


How can I add an item to the beginning of an associative array? 

For example, say I have an array like this:
$arr = array('key1' => 'value1', 'key2' => 'value2');

Answers:

You could use the union operator:

$arr1 = array('key0' => 'value0') + $arr1;

One way is with array_merge:
<?php
$arr = array('key1' => 'value1', 'key2' => 'value2');
$arr = array_merge(array('key0' => 'value0'), $arr);  ?>

PHP sizeof() Function

The sizeof() function returns the number of elements in an array.

<?php
$cars=array("Volvo","BMW","Toyota");
echo sizeof($cars);
?>

Example

for($i=0;$i<sizeof($batch);$i++){                    
   echo '<td>'. $batch[$i]['batch_name'].'</td>';
}


Split multiple lines and input them in separate row in a database



How to explode a multi-line string?


PHP explode() Function

Definition and Usage

The explode() function breaks a string into an array.

Syntax

explode(separator,string,limit)




Depending on your os a newline can be "\n", "\r\n" or "\r".
Give this a shot:
$strip=explode("<br>", nl2br($linkfield));
or maybe safer:
$strip=explode("\n", str_replace(array("\n", "\r\n"), "\n", $linkfield));


$address=explode("\n", str_replace(array("\n", "\r\n"), "\n", $student->present_address));
print_r($address);

Output

 Array ( [0] => SHANEESH P [1] => OPP MUNICIPAL OFFICE [2] => MALAPPURAM [3] => KERALA [4] => INDIA )


<?php
$text = $_POST['userlist'];
$array = explode('\n', $text);
?>



How to print a debug log


file_put_contents('your_log_file', 'your_content');
or
error_log ('your_content', 3, 'your_log_file');

Example 

file_put_contents('error_log', $userid);

Value stored to error_log file in your folder.



PHP prepend leading zero before single digit number


str_pad($number, 2, '0', STR_PAD_LEFT); 

Add zero to before number.

<?pph

$m=1;

$p= str_pad($m, 3, '0', STR_PAD_LEFT);

echo $p;

?>

Output : 001



show a number to 2 decimal places


You can use number_format():
return number_format((float)$number, 2, '.', '');

$padded = sprintf('%0.2f', $unpadded);

echo round(5.045, 2); 


Comparing Dates in PHP


How to compare Dates in php


<?php

$exp_date = "2017-01-10";
$todays_date = date("Y-m-d");

$today = strtotime($todays_date);
$expiration_date = strtotime($exp_date);

if ($expiration_date > $today) {
     echo "yes";
} else {
     echo "no";
}


?>


Adding days to Date in PHP


<?php

$Date = date("Y-m-d"); // "2010-09-17";
echo date('Y-m-d', strtotime($Date. ' + 1 days'));
echo '<br>';
echo date('Y-m-d', strtotime($Date. ' + 360 days'));

?>




Friday, 25 September 2015

Introduction and requirements for using YII2 Farmework

Introduction

What is Yii

Yii is a high performance, component-based PHP framework for rapidly
developing modern Web applications. The name Yii (pronounced Yee or [ji
:]) means “simple and evolutionary” in Chinese. It can also be thought of
as an acronym for Yes It Is!



Requirements and Prerequisites

Yii 2.0 requires PHP 5.4.0 or above. You can find more detailed requirements
for individual features by running the requirement checker included in every
Yii release.


Using Yii requires basic knowledge of object-oriented programming (OOP),
as Yii is a pure OOP-based framework. Yii 2.0 also makes use of the latest
features of PHP, such as namespaces2 and traits3 . Understanding these con-
cepts will help you more easily pick up Yii 2.0.






How to setup / install PHP 5.6 on Ubuntu 12.04, 14.04 or 14.10



sudo add-apt-repository ppa:ondrej/php5-5.6
sudo apt-get update
sudo apt-get install php5
 
 
 
To properly check  the installed version of PHP do: 
 
 
php5 -v 
 
 



How to install mysql?



This is the mysql server witch you need.

sudo apt-get install mysql-server
 
The client you need it if you want to run commands from the workbench and not from a terminal. so this is optional.

sudo apt-get install mysql-client
 
and for Mysql-Workbench(optional):

sudo apt-get install mysql-workbench




Install phpMyAdmin



phpMyAdmin is a very popular MySQL management software package.


Step 1: Install phpMyAdmin

First, you’ll follow a simple best practice: ensuring the list of available packages is up to date before installing anything new.

apt-get -y update

Then it’s a matter of just running one command for installation via apt-get:

apt-get -y install phpmyadmin

Step 2: Basic Configuration

As the installation runs you’ll be asked a few simple questions regarding the basic configuration of phpMyAdmin.

Step 3: Finish the Configuration of Apache

For a refresher on editing files


vi /etc/apache2/apache2.conf

Add the following to the bottom of the file:

# phpMyAdmin Configuration

Include /etc/phpmyadmin/apache.conf



And, restart Apache 2 with the following command:

service apache2 restart

Verify that phpMyAdmin is working by visiting the_IP_of_your_server/phpmyadmin.

For example:

http://127.0.0.1/phpmyadmin
http://localhost/phpmyadmin




Install NetBeans IDE 8.0:


NetBeans is a software development platform written in Java. The NetBeans Platform allows applications to be developed from a set of modular software components called modules.

Applications based on the NetBeans Platform, including the NetBeans integrated development environment (IDE), can be extended by third party developers.


JDK 7u80 with NetBeans 8.0.2


This distribution of the JDK includes the Java SE bundle of NetBeans IDE, which is a 

powerful integrated development environment for developing applications on the Java platform. 


Click Download

















Thursday, 17 September 2015

Project developing time faced errors in PHP, MySql, and Apache



PHP Fatal Error – yii\base\ErrorException

Allowed memory size of 134217728 bytes exhausted (tried to allocate 262144 bytes)


Answers


Just add this below line to before line of you getting error in your file
ini_set('memory_limit', '-1');
It will take unlimited memory usage of server, it's working fine.
****************************************

php.ini changed as follows: memory_limit = 512MB to memory_limit = 536870912

****************************************

And also to change it via php like so (before error line):
ini_set('memory_limit','128M');
****************************************




PHP Fatal Error – yii\base\ErrorException

Maximum execution time of 30 seconds exceeded




Edit php.ini


Follow the path /etc/php5(your php version)/apache2/php.ini.
Open it and set the value of max_execution_time to a desired one.

max_execution_time = 360     
 ; Maximum execution time of each script, in seconds (I CHANGED THIS VALUE)

max_input_time = 120          
; Maximum amount of time each script may spend parsing request data

;max_input_nesting_level = 64 ; Maximum input variable nesting level

memory_limit = 128M           
; Maximum amount of memory a script may consume (128MB by default)




All the answers above are correct, but I use a simple way to avoid it in some cases.
Just put this command in the begining of your script:
set_time_limit(0);





Wednesday, 16 September 2015

YII2 mPDF


HTML to PDF introduction


Setting paper size in FPDF


mPDF is a simple and popular tool for shared hosting users to create and convert UTF-8 encoded HTML pages to PDF files.


The yii2-mpdf extension is a Yii2 wrapper component for the mPDF library with enhancements. The mPDF library offers ability to generate PDF files from UTF-8 encoded HTML. This library is based on FPDF andHTML2FPDF, with a number of enhancements. The key features in the library are to be able to generate PDF files 'on-the-fly' from HTML content, handling different languages. See the list of features and/or examples for the library. The yii2-mpdf extension offers an easy way to integrate and use the mPDF library within your Yii application with subtle enhancements. 



Installation
The preferred way to install this extension is through composer. Either run:
  1. $ php composer.phar require kartik-v/yii2-mpdf "*"
or add:
  1. "kartik-v/yii2-mpdf": "*"
to the require section of your composer.json file. Then run:
  1. php composer.phar update
to get the updated package on your application install.


Install and  Use    




Settings \kartik\mpdf\Pdf


The extension includes the \kartik\mpdf\Pdf Component class (which extends and builds upon the yii/base/Component class).


mPDF Usage


How to set or resize margin in mPDF ?
How to change paper orientation in mPDF ?
How to change font size in mPDF ?
How to change paper size in mPDF ?


Answers:


If you want to be more specific about encoding and page size, you can put those parameters when initializing mPDF class like this:


1
$mpdf = new mPDF('utf-8', 'A4');

You can even specify actual page size in mm. In the example below the page size will be 190mm wide x 236mm height:

1$mpdf = new mPDF('utf-8', array(190,236));


If you want full functionality, you can even specify margins and if the page is landscape like this:


1
$mpdf = new mPDF('',    // mode - default ''
2 '',    // format - A4, for example, default ''
3 0,     // font size - default 0
4 '',    // default font family
5 15,    // margin_left
6 15,    // margin right
7 16,     // margin top
8 16,    // margin bottom
9 9,     // margin header
10 9,     // margin footer
11 'L');  // L - landscape, P - portrait




Example


* First find required data
* Create php file receipt-print.php. This file used to display format for pdf file.
* Use renderPartial funtion to send values to display receipt-print.php and assign object to $html variable
* Create mpdf object assign parameters.
* Write html and create output.




public function actionPrintCommonReceipt($receipt_no, $ccid)
    {
        
        if(!yii::$app->user->can('view-receipt'))   
        {        
            throw new ForbiddenHttpException;
            die();
        }
        
            $model = $this->findModel($receipt_no, $ccid);
                    
            $model->receipt_date=date('d-m-Y',strtotime($model->receipt_date));                   
            $modelsReceiptitems = $model->receiptitems;
            
            $student = $this->findStudentDetails($model->students_admission_number,$ccid);

            $cent = Center::findone(['ccid'=>$ccid]);
            
            $html = $this->renderPartial('receipt-print',[
                'model' => $model,
                'modelsReceiptitems' => $modelsReceiptitems,
                'student' => $student,
                'centerAddress'=>$cent['address'],
                ]);
                        
                //$imgSrc = Yii::$app->urlManager->createAbsoluteUrl('site/loadimage');
$mpdf = new mPDF('utf-8', 'A4',0,'',15,15,5,5,4,9,'P');
//$mpdf->WriteHTML('<watermarkimage src='.$imgSrc.' alpha="0.33" size="50,30"/>');
$mpdf->showWatermarkImage = true;
$mpdf->WriteHTML($html);
$mpdf->Output($title.'.pdf', "I");
            
        
    }



mPDF settings to Custom Paper Size

How to set the page in landscape mode in mpdf ?



// Define a Landscape page size/format by name
$mpdf=new mPDF('utf-8', 'A4-L');

mPDF set to half of paper size A4 


They even give an example with custom size:
Example with a custom 210x148 mm page size:
$pdf = new FPDF('P','mm',array(210,148));

$mpdf = new mPDF('utf-8', array(210,148),0,'',15,15,5,5,4,9,'P');