Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Saturday, 27 February 2016

[Solution] How to limit text in php? 0

Do you wanna show limited text of long text content? if you are using php, then use this simple handy function, else use this logic to build your own function in your programming language.

Here is the procedure we used to create our handy function.

  • First we will apply strip_tags() function on our string to avoid breaking any html. 
  • And then compare our string length with limit parameter. If string length is lesser than limit parameter value, then return the same string. If it is greater than limit parameter value, then turncate the string using substr() function with our limit parameter.
  • To avoid breaking word, check the string ending with any words, If it is a separated with space,  then break it up.


Function definition:
function limitText($string, $limit=200, $concatStr){
     //strip tags to avoid breaking any html
     $string = strip_tags($string);
     if(strlen($string) > $limit){
          //turncate string
          $stringCut = substr($string,0,$limit+1);
          //make sure it ends in a word.
          //if the ending word is a long text and it exceeds the limit, then break it up
          $string = (strrpos($stringCut, ' '))?substr($stringCut,0,strrpos($stringCut, ' ')).$concatStr:$stringCut.$concatStr;
     }
     return $string;
}
Function usage:
$limitedText = limitText($string, 100, '...');

Have any doubt, feel free to comment here!

Saturday, 11 July 2015

[Solution] Unable to load or find PHP extension php_intl.dll in WAMP 0

Recently I was started to working with CakePHP 3.x. The latest version of CakePHP needed intl extension to work with it. But I could not enable intl extension in my latest version of Wamp 2.5. So, I have got an error,

PHP Startup : Unable to load dynamic library C:/wamp/path/to/php/ext/php_intl.dll - The specified module could not be found.

We can solve it in a two ways.

Solution 1:

  1. Just go to C:/wamp/path/to/bin/php/php5.5.12/. Copy all the files starts with icu* and paste it into C:/wamp/path/to/bin/apache/apache2.2.22/bin/  directory.
  2. To enable intl extension,
    • Click on the wamp icon
    • Click on PHP
    • Click PHP extensions
    • Click on php_intl
  3. Now Restart All Services. 
Thats all... Your intl extension is enabled now... 

Solution 2:

  1. Just include the PHP directory into the system's PATH variable.
  2. Install the full Microsoft VC++ 2012 Runtime Redistributable package. Make sure to get the 32 bit version for 32 bit PHP builds.
Have any doubt, feel free to comment here!

Saturday, 9 August 2014

$_GET vs. $_POST - PHP 0

$_GET and $_POST
  • Both GET and POST create an array.
  • e.g. array(key=>value, key2=>value2, key3=>value3, ...).
  • This array holds key/value pairs, where keys are the names of the form controls and values are the input data from the user.
  • Both GET and POST are treated as $_GET and $_POST. These are superglobals, which means that they are always accessible, regardless of scope - and you can access them from any function, class or file without having to do anything special.
  • $_GET is an array of variables passed to the current script via the URL parameters.
  • $_POST is an array of variables passed to the current script via the HTTP POST method.

When to use GET?
Information sent from a form with the GET method is visible to everyone (all variable names and values are displayed in the URL). GET also has limits on the amount of information to send. The limitation is about 2000 characters. However, because the variables are displayed in the URL, it is possible to bookmark the page. This can be useful in some cases.
GET may be used for sending non-sensitive data.
Note: GET should NEVER be used for sending passwords or other sensitive information!
When to use POST?
Information sent from a form with the POST method is invisible to others (all names/values are embedded within the body of the HTTP request) and has no limits on the amount of information to send.
Moreover POST supports advanced functionality such as support for multi-part binary input while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.


Sunday, 27 July 2014

Convert CSV to Two dimensional array (2D Array) - PHP 2

When you get the data from CSV file, It will return return array of each row. To work with this, we need to convert it as 2D array. So, this following code snippet will help you to covert CSV array to 2D array. In this we used PHP's array_combine function.

FUNCTION DEFENITION
function get2DArrayFromCsv($file, $delimiter) {
    if (($handle = fopen($file, "r+")) !== FALSE) {
        $i = 0;
        $data2DArray = array();
        while (($lineArray = fgetcsv($handle, 0, $delimiter)) !== FALSE) {
            for ($j = 0; $j < count($lineArray); $j++) {
                $data2DArray[$i][$j] = $lineArray[$j];
            }
            $i++;
        }
        fclose($handle);
    }
    return $data2DArray;
}

HOW IT WORKS

* Just used incremental variable $i to mention number of row in 2D array.
* Once finished the iteration for a row, then increment $i for the next row.
* See how array_combine works.

PARAMETERS 

$file - File path
$delimiter - delimiter used in this CSV

FUNCTION USAGE
get2DArrayFromCsv($file_path, ',');
Recommended Article : Convert CSV to JSON with header row as key - PHP

Have any doubt? Feel free to comment here!!!


Wednesday, 16 July 2014

Convert CSV to JSON with header row as key - PHP 1

When you get the data from CSV file, It will return return array of each row. If we want this array in JSON as header row as key and cell value as value, We can use PHP's array_combine function.

So, We can use this following function to achieve this task.

FUNCTION DEFENITION
function getJsonFromCsv($file,$delimiter) { 
    if (($handle = fopen($file, 'r')) === false) {
        die('Error opening file');
    }

    $headers = fgetcsv($handle, 4000, $delimiter);
    $csv2json = array();

    while ($row = fgetcsv($handle, 4000, $delimiter)) {
      $csv2json[] = array_combine($headers, $row);
    }

    fclose($handle);
    return json_encode($csv2json); 
}
HOW IT WORKS

* Just read the first line separately and merge it into every row.
* The above function opens a file handle, reads the first line into $headers
* Then reads the remaining lines.
* It combines each line with the $headers.
* See how array_combine works.

PARAMETERS 

$file - File path
$delimiter - delimiter used in this CSV

FUNCTION USAGE
getJsonFromCsv($file_path, ',');
Recommended Article : Convert CSV to Two dimensional array (2D Array) - PHP

Have any doubt? Feel free to comment here!!!


Saturday, 12 July 2014

Strict Standards: Non-static method DOMDocument::load() should not be called statically - PHP 0

In PHP recently I faced this issue. When I tried to use my xml file using php's document load() function.

Problem
$dom = DOMDocument::load('myXml.xml');
It works perfectly. But I throws error
Strict Standards: Non-static method DOMDocument::load() should not be called statically
Solution
The reason why it's happening is because I called a load() method in the DOMDocument class in which is not static.

 Instead of calling it with :: We need to call it with ->

I found PHP document about the usage of DOMDocument load() method.
$doc = new DOMDocument();
$doc->load('myXml.xml');
Now the error is gone...!!!

Have any doubt feel free to comment here!


Tuesday, 24 June 2014

Get all dates in given month and year in php 0

To get all dates in given month and year, we need to know how many days in that given month and year.

to do that we are going to use PHP's date() and mktime() functions.

Syntax :

date(format,timestamp)
mktime(hour,minute,second,month,day,year,is_dst);

Function:

the following function will return dates in array format for given month and year in Y-m-d format.

Parameters:

$month   -  Month number
$year    -  Year        

usage:

$dates = get_dates($month,$year);

Example:
output:

Explanation:

We just calculated the number of days in month and using for loop, we are creating array in our own format.

Have any doubt, feel free to comment here!

Tuesday, 3 June 2014

How to get full referrer url in php 0

To get referrer url, we are going to use $_SERVER variable called HTTP_REFERER.

In some cases we need to check, this page redirected from where? To fill up that "where" we should use  $_SERVER[HTTP_REFERER].

NOTE:
  • If users use a bookmark or directly visit your site by manually typing in the URL, HTTP_REFERER will be empty.
  • If the users are posting to your page programatically (CURL) then they're not obliged to set the HTTP_REFERER as well.

So, to get full referrer URL in your PHP page, we need to use,
echo $_SERVER[HTTP_REFERER];
Have any doubt, feel free to comment here!

Related Post : How to get current full URL in PHP

How to get current full URL in PHP 0

To get current full url in php, we can use php's $_SERVER variables.

We are going to use
  • $_SERVER[REQUEST_SCHEME]  - It will print which type scheme (ex.http)
  • $_SERVER[HTTP_HOST]       -  Server host name
  • $_SERVER[REQUEST_URI]      - current URI 
So, We can combine those three like below,
$URL = $_SERVER[REQUEST_SCHEME].'://'.$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI];
 Simply echo it like this echo $_URL; to test it.

Have any doubt, feel free to comment here!

Related Post : How to get full referrer url in php

Friday, 23 May 2014

How to check current day is the last day of the month in php 0

We can simply use PHP's data() function to do this.

  •  date('t') will return the last day of the month.
  •  date('j') will return the current day of the month.

So, we can simply implement our if-else logic here to get the output.
$maxDays    =  date('t');
$currentDay =  date('j');

if($maxDays == $currentDay)
{
    echo 'Last Day of month';
}
else
{
    echo 'Not last day of the month';
}
Have any doubt, feel free to comment here!

Wednesday, 7 May 2014

How to set default time zone in php? 0

to set default timezone in our php page, we can use PHP native function.

syntax:

date_default_timezone_set('region/area');

for example, if you are in New York, your timezone is "America/New_York"

standard timezone for India is "Asia/Kolkata" or "Asia/Calcutta".

WHY we need to set timezone in our PHP page?

     Consider your server in India and your client access your web page from America, In this situation you are getting date() or time() from your server using PHP, it will return server timezone. That means it will return Indian time.

     So, you should change it to American timezone to get correct date() or time() from server.

You can put this in your header of footer php file to set timezone in all of your pages.

Timezone Array

If you are giving option to select timezone to user, you should list out all timezones in your select box. You can simply use this below function to do this. it will return array of timezones.


And you can use that array in your form like the above code.

Monday, 14 April 2014

Grouping PHP array 0

When we have a same ids for multiple array values, we can group those array values for easy handling.

Consider if we have a array like this,
Array
(
    [0] => Array
        (
            [id] => 96
            [shipping_no] => 212755-1
            [part_no] => reterty
            [description] => tyrfyt
            [packaging_type] => PC
        )

    [1] => Array
        (
            [id] => 96
            [shipping_no] => 212755-1
            [part_no] => dftgtryh
            [description] => dfhgfyh
            [packaging_type] => PC
        )

    [2] => Array
        (
            [id] => 97
            [shipping_no] => 212755-2
            [part_no] => ZeoDark
            [description] => s%c%s%c%s
            [packaging_type] => PC
        )

)
If we want to group the above array by `id`, we can use this following piece of code,
$result = array();
foreach ($arr as $data) {
  $id = $data['id'];
  if (isset($result[$id])) {
     $result[$id][] = $data;
  } else {
     $result[$id] = array($data);
  }
}
So, the  print_r($result) result will be,
Array
(
    [96] => Array
        (
            [0] => Array
                (
                    [id] => 96
                    [shipping_no] => 212755-1
                    [part_no] => reterty
                    [description] => tyrfyt
                    [packaging_type] => PC
                )

            [1] => Array
                (
                    [id] => 96
                    [shipping_no] => 212755-1
                    [part_no] => dftgtryh
                    [description] => dfhgfyh
                    [packaging_type] => PC
                )
        )
    [97] => Array
        (
            [0] => Array
                (
                    [id] => 97
                    [shipping_no] => 212755-2
                    [part_no] => ZeoDark
                    [description] => s%c%s%c%s
                    [packaging_type] => PC
                )

        )