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

Saturday, March 5, 2016

Display Other Texts rather then English using PHP MySQL


When we want to display and store the data other than ENGLISH using PHP.

Below is the code used to save and retrieve the data in PHP.

mysql_set_charset('utf8',$db_connect);

where $db_connect is the "MySQL Host" connection handler. You can see the example below for the connection handler.


<?php
$db_connect = mysql_connect(HOST_NAME,USERNAME,PASSWORD);
mysql_set_charset('utf8',$db_connect);
?>


By using the above, we can store and retrieve the data in different languages like Telugu, French, Hindi, German and many.

Note: And also a major note we need to be keep in mind, when we try to retrieve the same UTF-8 converted data using AJAX. We should not use "mysql_set_charset" as AJAX by default sets the content as "UTF-8" 

Saturday, May 17, 2014

Restrict image access from browser using HTACCESS



 When we want to restrict the image access from the browser other than the page, add the below code in htaccess file to apply.


RewriteEngine on 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost [NC] 
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost.*$ [NC] 
RewriteRule \.(gif|jpg|png)$ - [F]

localhost need to be replaced by the domain name where the application is hosted. 

NOTE: Above code works in Apache (LINUX) not in windows

Monday, April 28, 2014

Redirect to maintenance page using HTACCESS



 Redirecting the whole site to maintenance page using HTACCESS

RewriteEngine On
RewriteBase /
RewriteCond %{REMOTE_ADDR} !^111\.11\.1\.11
RewriteCond %{REQUEST_URI} !^/maintenance\.html$
RewriteRule ^(.*)$ http://www.domainname.com/maintenance.html [R=307,L]


Rewrite condition mentioned is to stop the redirection for that particular domain.

RewriteCond %{REMOTE_ADDR} !^111\.11\.1\.11

"maintenance.html" is the page where you want to redirect the website.

Monday, November 18, 2013

Random values from an Array using php

Below is the function to pick random values from an existing array

function array_pick_random($arr, $number = 1) {
    shuffle($arr);
   
    $r = array();
    for ($i = 0; $i < $number; $i++) {
        $r[] = $arr[$i];
    }
    return $number == 1 ? $r[0] : $r;
}

In the above function '$arr' is the Array which we want to get the random values.

'$number' is the number of array elements need to return.

Function returns an array if '$number' contains more than 1.

Sunday, October 20, 2013

ajax with cross domain


We may worked with jQuery ajax in many cases but when we try to use jQuery AJAX to get the data from other domain, we need to use "crossDomain" & set it to true.

Let us consider the basic jQuery AJAX within the domain.

$.ajax({
            url: "show_users.php",
            data: {data1:"val1", data2="val2"},
            type:'POST',
            success: function(res)
            {
                $('#element_name').html(res);
            },
            error: function (){alert('something went wrong');}
});

Above is the AJAX request within the domain & just we are passing the data to the page "show_users.php" with two values. As it is simple AJAX request, it works fine.

But when we work with cross domains (i.e. AJAX request to other domain from our domain) we need to rewrite the jQuery AJAX as below.

$.ajax({
            url: "http://domain.com/show_users.php",
            data: {data1:"val1", data2="val2"},
            type:'POST',
            crossDomain: true,
            success: function(res)
            {
                $('#element_name').html(res);
            },
            error: function (){alert('something went wrong');}
});

We need to use "crossDomain" & set it to TRUE & in the domain.com show_users.php page we need to set an header as below.

header('Access-Control-Allow-Origin: *');

We can set the "Access-Control-Allow-Origin" with only one IP address or '*' if it is not limited to single IP address

Monday, July 29, 2013

Decode html entities using javascript

Below is the code to decode the html entities using javascript rather than the Server side scripting

function decodeEntities(input) {
    var y = document.createElement('textarea');
    y.innerHTML = input;
    return y.value;
}

Above function just receives the html values like below

var str = "<p>Hello World<br />This is the test message";

When we pass the above HTML string to the function it returns as below,

calling the JAVASCRIPT function 

decodeEntities(str)

Output is: "&lt;p&gt;Hello World&lt;br/&gt;This is the test message";

Wednesday, January 30, 2013

Basic UNIX commands



Below are the basic unix commands which may help you while using PUTTY to access the server. Move, copy, view the pages from folder to other destination. All other basic stuff syntax are given below


If there are images in this attachment, they will not be displayed.  Download the original attachment
Unix Basic Commands

Copy:

cp sorce_file target_file  :copies only if the files are in current direc

cp -r sor_DIR target_dir (to copy directories)

Move/Rename;

mv file1 file2

mv -i f1 f2 (asks for permision to move or not)

Remove:

rm filename

rm -r file (to remove directory structure)

rm -i file ( asks for permision to move or not)

view:

cat filename ( to view the complete file content)

To extract or unzip files:

unzip file ( extracts file to current dir)

To uncompress

uncompress filename

To compress

compress filename

To change directory

cd path

to list files in current dir

ls

ls -l (long list of files : gives acess permision,creation date..etc)

    -a(list all files satarting with a " .")

to make a dir

mkdir name or md name

to remove

rmdir dir_name

to clear the screen

clear (clears the windoe or terminal)

help commands

man <comd name> (displays the mannual page)

whatis <cammnd> (gives description)

date (to dispaly the date)

to count the words

wc filename (gives lines,words,characters

wc -l file (only lines)

wc -c file(only characters)

wc -w file(onbly words)

df ( displays the amount of free space)

grep (search a file for matching pattern)

grep [optioln]<regularExpression filename

eg: grep [a-z]*.c filename

Wednesday, January 16, 2013

Upload huge files in PHP


When we try to upload huge files using PHP, we face many issues to upload. One of them might be the php_value upload_max_filesize which is by default 2M in php.ini

Still we may have other issues which we need to do fix them. Below are the steps we need to add in htaccess to fix the large file uploads.


php_value upload_max_filesize 10M
php_value post_max_size 64M
php_value max_execution_time 300


Saturday, September 1, 2012

Generate random code using PHP


Below is the function to generate a random code(alpha-numeric) using PHP. We can use the below function for generating a coupon code (or) verification code (or) affiliate code for the people.



function generate_random_code( $size )
{
        $list_chars = array_merge(range('A','Z'), range(0,9));
      
        $referal_code = '';
      
        for($i=0;$i<=$size;$i++)
        {
            $referal_code .= $list_chars[mt_rand(0, count($list_chars)-1)];
        }
      
        return $referal_code;
      
}


$size  => Length of the random code to be generated. 

Wednesday, June 13, 2012

Calculate time difference using PHP


 function get_time_difference_php($created_time)
 {
        date_default_timezone_set('Asia/Calcutta'); //Change as per your default time
        $str = strtotime($created_time);
        $today = strtotime(date('Y-m-d H:i:s'));
        
        // It returns the time difference in Seconds...
        $time_differnce = $today-$str;
        
        // To Calculate the time difference in Years...
        $years = 60*60*24*365;
        
        // To Calculate the time difference in Months...
        $months = 60*60*24*30;
        
        // To Calculate the time difference in Days...
        $days = 60*60*24;
        
        // To Calculate the time difference in Hours...
        $hours = 60*60;
        
        // To Calculate the time difference in Minutes...
        $minutes = 60;

        if(intval($time_differnce/$years) > 1)
        {
            return intval($time_differnce/$years)." years ago";
        }else if(intval($time_differnce/$years) > 0)
        {
            return intval($time_differnce/$years)." year ago";
        }else if(intval($time_differnce/$months) > 1)
        {
            return intval($time_differnce/$months)." months ago";
        }else if(intval(($time_differnce/$months)) > 0)
        {
            return intval(($time_differnce/$months))." month ago";
        }else if(intval(($time_differnce/$days)) > 1)
        {
            return intval(($time_differnce/$days))." days ago";
        }else if (intval(($time_differnce/$days)) > 0) 
        {
            return intval(($time_differnce/$days))." day ago";
        }else if (intval(($time_differnce/$hours)) > 1) 
        {
            return intval(($time_differnce/$hours))." hours ago";
        }else if (intval(($time_differnce/$hours)) > 0) 
        {
            return intval(($time_differnce/$hours))." hour ago";
        }else if (intval(($time_differnce/$minutes)) > 1) 
        {
            return intval(($time_differnce/$minutes))." minutes ago";
        }else if (intval(($time_differnce/$minutes)) > 0) 
        {
            return intval(($time_differnce/$minutes))." minute ago";
        }else if (intval(($time_differnce)) > 1) 
        {
            return intval(($time_differnce))." seconds ago";
        }else
        {
            return "few seconds ago";
        }
  }

Tuesday, June 5, 2012

Difference between current date and past date using MySQL


Below is the function to get the time difference between Current date and the past date using MySQL. Mainly it can be used where we want to display the time gap between the registration of the user.


function getTimeDifference($created_since)
{
            $datediffquery = mysql_query  ("SELECT CASE WHEN TIMESTAMPDIFF(YEAR ,'".$created_since."', NOW()) > 1 THEN CONCAT(TIMESTAMPDIFF(YEAR ,'".$created_since."', NOW()), ' years ago')
                                                WHEN TIMESTAMPDIFF(YEAR ,'". $created_since."', NOW()) > 0 THEN CONCAT(TIMESTAMPDIFF(YEAR ,'". $created_since ."', NOW()), ' year ago')
                                                WHEN TIMESTAMPDIFF(MONTH ,'".$created_since."', NOW()) > 1 THEN CONCAT(TIMESTAMPDIFF(MONTH ,'".$created_since."', NOW()), ' months ago')
                                                WHEN TIMESTAMPDIFF(MONTH ,'".$created_since."', NOW()) > 0 THEN CONCAT(TIMESTAMPDIFF(MONTH ,'".$created_since."', NOW()), ' month ago')
                                                WHEN TIMESTAMPDIFF(DAY ,'".$created_since."', NOW()) > 1 THEN CONCAT(TIMESTAMPDIFF(DAY ,'".$created_since."', NOW()), ' days ago')
                                                WHEN TIMESTAMPDIFF(DAY ,'".$created_since."', NOW()) > 0 THEN CONCAT(TIMESTAMPDIFF(DAY ,'".$created_since."', NOW()), ' day ago')
                                                WHEN TIMESTAMPDIFF(HOUR ,'".$created_since."', NOW()) > 1 THEN CONCAT(TIMESTAMPDIFF(HOUR ,'".$created_since."', NOW()), ' hours ago')
                                                WHEN TIMESTAMPDIFF(HOUR ,'".$created_since."', NOW()) > 0 THEN CONCAT(TIMESTAMPDIFF(HOUR ,'".$created_since."', NOW()), ' hour ago')
                                                WHEN TIMESTAMPDIFF(MINUTE ,'".$created_since."', NOW()) > 1 THEN CONCAT(TIMESTAMPDIFF(MINUTE ,'".$created_since."', NOW()), ' minutes ago')
                                                WHEN TIMESTAMPDIFF(MINUTE ,'".$created_since."', NOW()) > 0 THEN CONCAT(TIMESTAMPDIFF(MINUTE ,'".$created_since."', NOW()), ' minute ago')
                                                WHEN TIMESTAMPDIFF(SECOND ,'".$created_since."', NOW()) > 1 THEN CONCAT(TIMESTAMPDIFF(SECOND ,'".$created_since."', NOW()), ' seconds ago')
                                            END
                                        AS total_days");
            
            $row = mysql_fetch_assoc($datediffquery);
            
            return $row['total_days'];
        }

Friday, May 25, 2012

Calculate time difference between two dates using PHP

Below is the PHP function to calculate the time difference between current date and the given date.

It will returns in Seconds, minutes, months (or) years based on the time difference.

And it can be used to calculate the time difference between two dates by changing the $today with the date which you want to pass.


function get_time_difference_php($created_time)
    {
        date_default_timezone_set('Asia/Calcutta');
        $str = strtotime($created_time);
        $today = strtotime(date('Y-m-d H:i:s'));
        
        // It returns the time difference in Seconds...
        $time_differnce = $today-$str;
        
        // To Calculate the time difference in Years...
        $years = 60*60*24*365;
        
        // To Calculate the time difference in Months...
        $months = 60*60*24*30;
        
        // To Calculate the time difference in Days...
        $days = 60*60*24;
        
        // To Calculate the time difference in Hours...
        $hours = 60*60;
        
        // To Calculate the time difference in Minutes...
        $minutes = 60;

        if(intval($time_differnce/$years) > 1)
        {
            return intval($time_differnce/$years)." years ago";
        }else if(intval($time_differnce/$years) > 0)
        {
            return intval($time_differnce/$years)." year ago";
        }else if(intval($time_differnce/$months) > 1)
        {
            return intval($time_differnce/$months)." months ago";
        }else if(intval(($time_differnce/$months)) > 0)
        {
            return intval(($time_differnce/$months))." month ago";
        }else if(intval(($time_differnce/$days)) > 1)
        {
            return intval(($time_differnce/$days))." days ago";
        }else if (intval(($time_differnce/$days)) > 0) 
        {
            return intval(($time_differnce/$days))." day ago";
        }else if (intval(($time_differnce/$hours)) > 1) 
        {
            return intval(($time_differnce/$hours))." hours ago";
        }else if (intval(($time_differnce/$hours)) > 0) 
        {
            return intval(($time_differnce/$hours))." hour ago";
        }else if (intval(($time_differnce/$minutes)) > 1) 
        {
            return intval(($time_differnce/$minutes))." minutes ago";
        }else if (intval(($time_differnce/$minutes)) > 0) 
        {
            return intval(($time_differnce/$minutes))." minute ago";
        }else if (intval(($time_differnce)) > 1) 
        {
            return intval(($time_differnce))." seconds ago";
        }else
        {
            return "few seconds ago";
        }
    }

Saturday, April 21, 2012

Load file using MySQL

Most of the Programmers will be using the normal file operations to import a CSV file, we can use MySQL Load file too import a CSV to database table.

Below is the syntax to import the file to DB

LOAD DATA INFILE "/home/mysql/data/my_table_data.csv" INTO TABLE dummy_table FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n';

Wednesday, March 7, 2012

Retrieve the XML node value using PHP

When we want to read the XML tag value, we may use simple_xml_load or DOMdocument to read it and will get the particular node value. Below is the simple PHP function to retrieve the XML node value by passing the XML as string and passing the starting XML tag and ending XML tag.


function get_value_by_tag_Name( $str, $s_tag, $e_tag)
{
$s = strpos( $str,$s_tag) + strlen( $s_tag);
$e = strlen( $str);
$str= substr($str, $s, $e);
$e = strpos( $str,$e_tag);
$str= substr($str,0, $e);
$str= substr($str,0, $e);
return  $str;
}

Here $str is the XML which we are passing as a string, $s_tag is the Starting tag(Ex: '<EmployeeDetails'>) and $e_tag is the ending tag (Ex: '</EmployeeDetails>'). By passing the values it returns the node value.

So, it reduces the parsing XML and DOM Document steps.

Thursday, January 12, 2012

How PHP Script runs


PHP is a web scripting language which is platform independent.

Below picture shows you how the php script executes when you enter the URL of the page.


Wednesday, October 26, 2011

Upgrade Phpmyadmin in XAMPP

What is Phpmyadmin? Phpmyadmin is a tool written in PHP for viewing the MySQL tables & execute the SQL queries with the interface.

I'm just explaining how to upgrade the Phpmyadmin.

Want to Upgrade the latest Phpmyadmin in XAMPP, it is as simple as the usage.

Just download the latest version of Phpmyadmin from phpmyadmin or download from the link below.

First take a copy of Phpmyadmin folder in XAMPP or else just rename it in XAMPP then extract the downloaded files into XAMPP folder.

And now, take the config.inc.php file from the renamed folder & place it in the new folder, thats it & just check the latest version is running successfully.

Download, the latest phpmyadmin here


Wednesday, August 31, 2011

Restrict the file uploads using PHP


Below is the php code to restrict the file uploads for a particular type of files. As an example, I'm showing all the extension types in the "Allowed extensions" variable.


<?php

  $allowedExtensions = array("txt","csv","htm","html","xml",
    "css","doc","xls","rtf","ppt","pdf","swf","flv","avi",
    "wmv","mov","jpg","jpeg","gif","png");
    if ($_FILES['upload_file']['tmp_name'] > '') {
      if (!in_array(end(explode(".",
            strtolower($_FILES['upload_file']['name']))),
            $allowedExtensions)) {
       die($_FILES['upload_file']['name'].' is an invalid file type!<br/>'.
        '<a href="javascript:history.go(-1);">'.
        '&lt;&lt Go Back</a>');
      }
    }

?>





Saturday, August 13, 2011

Remove the special characters from the query string

Function to remove the special characters from the query string using PHP.

function trim_req($string){
$string=preg_replace('/[^A-Za-z0-9-]+/', '', $string);
$string = str_replace("<", "", $string);
$slug = str_replace(">", "", $string);
return $slug;
}




Compress & decrease the page loading time using HTACCESS

Place the below code in htaccess & decrease the loading time taken for the browser.


<IfModule mod_gzip.c>
    mod_gzip_on       Yes
    mod_gzip_dechunk  Yes
    mod_gzip_item_include file      \.(html?|txt|css|js|php|pl)$
    mod_gzip_item_include handler   ^cgi-script$
    mod_gzip_item_include mime      ^text/.*
    mod_gzip_item_include mime      ^application/x-javascript.*
    mod_gzip_item_include mime      ^image/.*
    mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</IfModule>

Above code will compress the HTML,CSS,JS,PHP,PL script files and also image files. 


Wednesday, May 25, 2011

Maximum length for the POST and GET methods

Maximum length of the POST is defined in the PHP ini file. Mostly it is 128M. To know the maximum POST length check your ini file for post_max_size

Maximum URL length is 2083 characters i.e. maxlength in GET method.