Subscribe For Free Updates!

We'll not spam mate! We promise.

Aug 26, 2014

preg_replace to add something after closing tag - PHP

preg_replace to add something after closing tag - PHP

PHP - preg_replace to add something after closing tag :

Here i will explain how to add something like string, char (or) any html tag after closing tag. Here we are using preg_replace() function to do it.

In the below example, add <br /> tag after closing of all <img> tag.

Syntax :

    preg_replace('/(<img[^>]+>(?:<\/img>)?)/i', '$1<br />', $str);
    
Note : This will match with <img />, <img>, <img></img> all of it.

Example :

    <?php
    
        $str = "<img src='img_path'>TechniqZone<img src='img_path'>";
        echo preg_replace('/(<img[^>]+>(?:<\/img>)?)/i', '$1<br />', $str);
        
    ?>

    
Output :

    <img src='img_path'><br />TechniqZone<img src='img_path'><br />
    
You can use this preg_replace() syntax for any of the html tags.

Aug 14, 2014

htmlentities() and html_entity_decode() in JQuery

htmlentities() and html_entity_decode() in JQuery :

htmlentities() and html_entity_decode() in JQuery
We are all know about use of htmlentities() in PHP. This function is used to convert all character to HTML entities. both function are used to treat string as a html and HTML as a string.
  
    For Example :
  
              
            echo htmlentities("TechniqZone");
          
         ?>

      
        Output :
      
            &lt ;a href=&#39 ;techniqzone.blogspot.in'&#39 ;&gt ;TechniqZone&lt ;/a&gt ; 
 // here semicolons (;) are placed with spaces for display here.
           
        This is very usefull in many places in php files to display html tags in website. But in javascript/JQuery, pre-defined encode decode function is not available.
      
        I hereby explained how to use encode and decode of HTML tags in JQuery. Before that need to know the diifference between JQuery.html() and JQuery.text().
      
            JQuery.html() - Treat string as HTML.
            JQuery.html() - Treat HTML as string.

          
        For Example :
      
            $("#techZone").html("<a href=''></a>");
            $("#techZone").text("<a href=''></a>");


Okay, now we create encode/decode custom function using JQuery.
  
        function htmlentities(str)
        {
            if(str) // check str is empty or not.
                return $("<div />").text(str).html();
            else
                return 'Argument mis-matched';
        }

      
        htmlentities("TechniqZone");
      
     Here create dummy <div> tag and append given string as text, after that take that dummy div text as html content.
  
     For decode,
  
        function html_entity_decode(str)
        {
            if(str) // check str is empty or not.
                return $("<div />").html(str).text();
            else
                return 'Argument mis-matched';
        }

  
        html_entity_decode("&lt ;a href=&#39 ;techniqzone.blogspot.in&#39 ;&gt ;TechniqZone&lt ;/a&gt ;");
// here semicolons (;) are placed with spaces for display here.

Note : htmlentities and html_entity_decode function are only working with jquery plugin files.

Jun 6, 2014

Redirect with HTTP Status Code - PHP

Redirect with HTTP Status Code - PHP :

Redirect with HTTP Status Code - PHP - TechniqZone

 

Redirect one url to another url using php is simply run with "header ("Location: redirectURL");" . But redirect with HTTP Status Code is more efficient to optimize for search engines.

    Here i will explain about php redirect with http status code. These http status code is common for all php versions.

<?php
function httpRedirect($code,$redirectURL){
   static $httpType = array (
       100 => "HTTP/1.1 100 Continue",
       101 => "HTTP/1.1 101 Switching Protocols",
       200 => "HTTP/1.1 200 OK",
       201 => "HTTP/1.1 201 Created",
       202 => "HTTP/1.1 202 Accepted",
       203 => "HTTP/1.1 203 Non-Authoritative Information",
       204 => "HTTP/1.1 204 No Content",
       205 => "HTTP/1.1 205 Reset Content",
       206 => "HTTP/1.1 206 Partial Content",
       300 => "HTTP/1.1 300 Multiple Choices",
       301 => "HTTP/1.1 301 Moved Permanently",
       302 => "HTTP/1.1 302 Found",
       303 => "HTTP/1.1 303 See Other",
       304 => "HTTP/1.1 304 Not Modified",
       305 => "HTTP/1.1 305 Use Proxy",
       307 => "HTTP/1.1 307 Temporary Redirect",
       400 => "HTTP/1.1 400 Bad Request",
       401 => "HTTP/1.1 401 Unauthorized",
       402 => "HTTP/1.1 402 Payment Required",
       403 => "HTTP/1.1 403 Forbidden",
       404 => "HTTP/1.1 404 Not Found",
       405 => "HTTP/1.1 405 Method Not Allowed",
       406 => "HTTP/1.1 406 Not Acceptable",
       407 => "HTTP/1.1 407 Proxy Authentication Required",
       408 => "HTTP/1.1 408 Request Time-out",
       409 => "HTTP/1.1 409 Conflict",
       410 => "HTTP/1.1 410 Gone",
       411 => "HTTP/1.1 411 Length Required",
       412 => "HTTP/1.1 412 Precondition Failed",
       413 => "HTTP/1.1 413 Request Entity Too Large",
       414 => "HTTP/1.1 414 Request-URI Too Large",
       415 => "HTTP/1.1 415 Unsupported Media Type",
       416 => "HTTP/1.1 416 Requested range not satisfiable",
       417 => "HTTP/1.1 417 Expectation Failed",
       500 => "HTTP/1.1 500 Internal Server Error",
       501 => "HTTP/1.1 501 Not Implemented",
       502 => "HTTP/1.1 502 Bad Gateway",
       503 => "HTTP/1.1 503 Service Unavailable",
       504 => "HTTP/1.1 504 Gateway Time-out"
   );
   header($httpType[$code]);
   header ("Location: $redirectURL");
}

httpRedirect(301,"http://techniqzone.blogspot.in/");

?>

Normally we do only header("Location: url"), here add header http status before redirect to given url.

Jun 5, 2014

PHP Validate Credit Card Number

PHP Validate Credit Card Number :

PHP Validate Credit Card - TechniqZone

 

Now a days , credit card purchase is happened in many websites. The below php function is used to validate the given credit card number in php.

function isCreditCardValid ( $number, $cctype )
{
    if ( !
is_string ( $number)
         || !
trim ( $number ) )
             return 
false;
      
    
$ccs = array (

        // Master Card
        'master' => '/^(5[1-5]{1})(\d{14})$/',

        // American Express 
        'amex' => '/^3(4|7)\d{13}$/',
        
        // Discover Card 
        'discover' => '/^6(011|22|4|5)(\d{12}|\d{13}|\d{14})$/', 
        
        // Visa Card 
        'visa' => '/^4(\d{12}|\d{15})$/',

        // Dinners Club        
        'dinners' => '/^(305|36|38|54|55)(\d{12}|\d{14})$/',

        // Carte Blanche         
        'carte' => '/^(30[0-5]{1})(\d{11})$/', 
        
        // enRoute 
        'enroute' => '/^2(014|149)\d{11}$/', 
        
        // Laser
        'laser' => '/^6(304|706|771|709)(\d{12}|\d{13}|\d{14}'.
                   '|d{\15})$/', 
        
        // Visa Electron 
        'visaelec' => '/^4(17500|917|913|844|508)(\d{10}|\d{12})$/', 
    );

    if ( !
is_string ( $cctype )
         || !
array_key_exists( strtolower ($cctype) , $ccs ) )
             return 
false;

    return (bool) 
preg_match ( $ccs[$cctype], $number );
} 

 

Example :

<?php

if(isCreditCardValid("371449635398431","amex"))
{
                 echo "Valid";
}
else
{
                 echo "Not Valid";
}

?>

 

Here preg_match concept is used to identify the valid credit card number.

 

May 21, 2014

MySQL query to trim particular character from database column field

MySQL has some default functions to trim particular cahr or whitespaces from all the column field in database rows. MySQL provide four type of methods to trim char.
1. TRIM()
2. TRIM(LEADING)
3. TRIM(BOTH)
4. TRIM(TRAILING)

we can use above four methods in select, update and delete queries.
1. TRIM()
    TRIM() function is used to remove the whitespaces from start and end of the string.
Query : select TRIM( TechniqZone );
Result : TechniqZone

    This is trim the whitespaces in all the column.
Example : update table_name set field1=TRIM(field1)
2. TRIM(LEADING)
    TRIM(LEADING) function is used to remove the given charecter from the starting postion of the string.
Query : select TRIM(LEADING "'" FROM "TechniqZone'");
Rssult : TechniqZone

  
    This method is remove the single quotes(') from al the column starting postion.
Example : update table_name set field1=TRIM(LEADING "'" FROM field1)
3. TRIM(BOTH)
    TRIM(BOTH) function is used to remove particular charecter from both start and end postion of the string.
Query : select TRIM(BOTH '"' FROM '"TechniqZone"');
Rssult : TechniqZone

    This is used to remove the double quotes (") from both position.
Example : update table_name set field1=TRIM(BOTH "'" FROM field1)
4. TRIM(TRAILING)
    TRIM(TRAILING) function is used to remove given charecter from end of the string.
Query : select TRIM(TRAILING '.com' FROM "TechniqZone.com");
Rssult : TechniqZone

    This MySQL query remove the .com from the end of the string.
Example : update table_name set field1=TRIM(TRAILING "xxx" FROM field1)
Note : TRIM() and TRIM(BOTH) is same as when we remove whitesapces from database column.
MySQL query to trim particular charecter from database column field - TechniqZone

May 20, 2014

Check String contains html tags and count of html tags using PHP

Check String contains html tags and count of html tags using PHP
Here i will explain how to check the given string contains html tags or not.  this function return boolean value.
// Function for check html tag presents
function hasTags($str){ 

$htmlTags = array('A' ,'B', 'BODY', 'BR', 'BUTTON', 'DIV', 'FONT', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'IMG', 'INPUT', 'TABLE');
// Here you mention what are the html tags you want to check
 if(preg_match_all("~(<\/?)\b(".implode('|',$htmlTags).")\b([^>]*>)~i",$str,$matches)){
       
return TRUE;
    }else{
        return 
FALSE;
    }
}

$str = 'Welcome to <h1><b></b></h1>';

if(hasTags($str)){
    echo 
'HTML tags Found';
}else{
    echo 
'HTML tags not found';
} 


If you want to get the present html tags count then consider the below function.

// Function for check html tag presents
function hasTags($str){
 $htmlTags
= array('A' ,'B', 'BODY', 'BR', 'BUTTON', 'DIV', 'FONT', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'IMG', 'INPUT', 'TABLE');



// Here you mention what are the html tags you want to check
if(preg_match_all("~(<\/?)\b(".implode('|',$htmlTags).")\b([^>]*>)~i",$str,$matches)){
        return
$matches[1];
    }else{
        return
0;
    }
}

$str = 'Welcome to <h1><b></b></h1>';

echo 'Tags Count = '.hasTags($str); 


Aug 25, 2013

Email validation using JavaScript and Jquery

Email validation using JavaScript and Jquery :

Email validation in Jquery - TechniqZone

 Here i will explain how to validate email id with JQuery. In JavaScript we can check the email id format only. but in jquery we can check whether we allow or not some of domain names also. First i will explain basic javascript method to validate email id.

Here is Javascript method :

function validateEmail(emailId)
{
var condition = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return condition.test(emailId);
}
In this javascript method only validate the given email id has alphabets and numeric. Here the variable "condition" has the email conditions. that is

([a-zA-Z0-9_.+-]) - is to allow email id username with  alphabets and numeric and also _.
@(([a-zA-Z0-9-]) - is to allow domail name with alphabets and numeric . and
([a-zA-Z0-9]{2,4}) - is to allow last part of the email id i.e., com, in, .. with alphabets and numeric and also                                   it's length should be 2 to 4.

Now i will explain how to validate email id with JQuery.

Here is JQuery Method :

$(document).ready(function() {

  $('#submitButton').click(function() {

    var emailCon = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
    var emailblockCon =/^([\w-\.]+@(?!gmail.com)(?!yahoo.com)([\w-]+\.)+[\w-]{2,4})?$/;

    var emailId = $("#mailId").val();
    if(emailId == '') {
      $("#mailId").val('Email id is Blank.');
      error = true
    }

    else if(!emailCon.test(emailId)) {
      $("#mailId").val('Check Your Email id.');
      error = true
    }

    else if(!emailblockCon.test(emailId)) {
      $("#mailId").val('gmail and yahoo mail ids not accept.');
      error = true
    }

    if(error == true) {
           return false;
    }

    });
}); 

In this JQuery method you can check the email format like in javascript . In jquery we validate extra one condition. here we validate the email id domain name also. because some of the website doesnt allow some free email providers domain. so we can also validate it here.


Aug 19, 2013

PHP - Validate Email Id


PHP - Validate Email Id :

 Here i will explain how to validate email id in php. This is very use full to validate email id in server side. php is used in server so we can validate email id in server side. if you want to validate email id in client side then you can use JavaScript, jquery etc...

 The below example will show you how to validate email id in PHP

Example :
<?php

$mailId = "xxx@gmail.com"; // Valid email
$conditions = '/^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([comco.in])+$/';
if (preg_match($conditions, $mailId))
{
echo "Valid Mail Id";
}
else
{
echo "Invalid Mail Id";
}

?&gt;





 In the above example "$mailId" having the email id given by user. and "$conditions" having conditions for validate given email id. here i used "preg_match()" predefined php function. this function return boolean value. if the match occurred then it will return true otherwise false.

 The above example print "Valid Mail Id". Here the variable "$conditions" have "com","co","in" conditions only, so it will allow these extension mail id only. and it will validate all allowed special characters only.

 if A$mailId="xxx@gmailo.comnm" then the output is "Invalid Mail Id".

Aug 14, 2013

Create directory with current year and month name - php

Create directory with current year and month name - php :
 

  Here i will explain about how to create folder / directory with the current year and month name. It is very usefull to seperate the uploaded image or file with the particular year and month name.

Here we will use the simple concept to create this. here date() function is used to get current year and month details.

For Example :

  if (!file_exists("techniq/".date('Y').'/'.date('m'))) {
    mkdir("techniq/".date('Y').'/'.date('m'), 0777, true);
   }

  In the above example three php pre defined function are used. that is file_exists() , date() , mkdir().

1. file_exists() :- This function is used to check the given path for directory is available or not. It will return bool value. If the file exists then it will return TRUE otherwise FALSE.

2. date() :- This function is used to get current timestamp. here i used date('Y'), it will return current year in numeric i.e., 2013. and date('m') return current month in the format of 08.

   Note : Read more about date() : http://techniqzone.blogspot.in/2013/07/php-to-get-yesterdayprevious-date.html

3. mkdir() :- This function is used to create a directory with the give filename or path. here i used 0777 argument for set folder permission for the created directory.

This method is easy to create Folder(directory) with current Year and Month name in php.

Aug 13, 2013

Export particular column data from table in phpmyadmin


Export particular column data from table in phpmyadmin :

 Here i will explain how to export particular column data from table. we can store the output in .sql or .csv file. In this method the output data will store in a file with newline (\n) separaters.

The syntax is :

SELECT column_name FROM table_name INTO OUTFILE '/opt/lampp/htdocs/fileName.sql'

The above syntax is store the output file in .sql format. you can change the format what you need. In the below example i will make the ooutput file in .csv format.

Example :

SELECT second_name FROM employee INTO OUTFILE '/opt/lampp/htdocs/secondName.csv'

Note : Best to download output file with .csv format. because .csv file format import has many advanced option when we import data to db. you can export with CSV, .zip, .gzip, etc... format.



Jul 31, 2013

PHP - To Check Query Process

PHP - To Check Query Process:

 Here i will explain how to check the mysql query processing by using php. This function shows you which threads are running.

Here i'm using "SHOW FULL PROCESSLIST" mysql command. This command is very useful if you get the "too many connections" error message and want to find out what is going on. The output shows the current running threads process id. You can use that id to kill that process.

php program is:

mysql_connect("localhost","root",""); // here we set localhost, username and password

$q = mysql_query("SHOW FULL PROCESSLIST"); // here we run the mysql query

echo "&lt;table border='1'&gt;";

while($l = mysql_fetch_row($q) ) {
echo "&lt;tr&gt;";
foreach($l as $val)
echo "&lt;td&gt;$val&nbsp;&lt;/td&gt;";
echo "&lt;/tr&gt;";

}
echo "&lt;/table&gt;";

mysql_close();

Note : The "SHOW FULL PROCESSLIST" command only shows you which
threads are running. If you do not use the FULL keyword, only the first 100 characters of each statement are shown in the Info field.

Jul 30, 2013

PHP to get yesterday(previous) date


PHP to get yesterday(previous) date:

Here are some methods to get the previous date using php. i.e.,)
yesterday date.
Here date() function is used and "D d-M-Y" format is used, it will
return the date format like "MON 29-Jul-2013".

Let we go to some examples to get the yesterday date in php.

1. echo date("D d-M-Y", time() - 60 * 60 * 24);

2. $pDate = new DateTime();
$pDate->add(DateInterval::createFromDateString('yesterday'));
echo $pDate->format('D d-M-Y');

3. echo date("D d-M-Y", strtotime("yesterday"));

4. echo date("D d-M-Y", strtotime('-1 days'));

5. echo date('D d-M-Y', time() - 86400);

6. echo date("D d-M-Y", mktime(0, 0, 0, date("m") , date("d")-1,date("Y")));


These all are return the date in same format like "MON 29-Jul-2013";

If you want some other date format then consider the below examples.

date("D d-M-Y"); // TUE 30-Jul-2013
date("F j, Y, g:i a"); // July 30, 2013, 3:10 pm
date("m.d.y"); // 07.30.13
date("j, n, Y"); // 30, 7, 2013
date("Y-m-d H:i:s"); // 2013-07-30 11:22:14
date('h-i-s, j-m-y, it is w Day'); // 03-10-41, 30-07-13, 2031
2045 2 Tueam13
date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 30th day.
date("D M j G:i:s T Y"); // Tue Jul 30 11:21:03 CEST 2013
date('H:m:s \m \i\s\ \m\o\n\t\h'); // 11:07:36 m is month
date("H:i:s"); // 11:21:48
date("Ymd"); // 20130730

Here you can see the attribute are used in date() function is "D,d,m,y,Y,M,H,m,s,i,a,A".
so you can modify it as what format you want like "date(D d/m/Y)". etc...

If you have any queries comments it. Sorry for my poor english.

Jul 14, 2013

Increase Import Maximum file size in phpmyadmin

Increase Import Maximum file size in phpmyadmin










                   Here are the steps to increase the import file size in phpmyadmin. Usually phpmyadmin allows to import sql files maximum of 2M (i.e 2,048kb). To increase the maximum file size do the following changes in php.ini file.


If you are using  windows ,the php configuration file can be located in your server (wampp or xampp) -> php folder.

Find
 upload_max_filesize =2M
in the file,
change the value acording to your need. Here I changed the value to 10M i.e , it allows to import sql files maximum of 10 Mb.

upload_max_filesize = 10M

 

Replace MS Word single quotes in PHP

Replace MS Word single quotes in PHP:
Replace MS Word single quotes in PHP

 The following function is used to replace Microsoft-encoded quotes in PHP.

function replaeQuotes($str) 
{ 
    $str1 = array(chr(145),chr(146), chr(147), chr(148), chr(151)); 
    $str2 = array("'", "'",'"','"','-'); 
    return str_replace($str1, $str2, $str); 
}

For Ex:

In php,

 $str="'This is TechniqZone'-For Developers";
$clearStr=replaeQuotes($str);

Remove MS Word special character symbol in html

Remove MS Word special character symbol in html :

 To remove the MS Word special character in html page or website page you just add the bellow header meta tag in your header field.

<META http-equiv="Content-type" content="text/html; charset=iso-8859-1">

Note: In some case the above meta tag will work individually, ie.,) No need to add any other meta tag with this.

Remove MS Word special character symbol in html

Jul 11, 2013

PHP Remove HTML tags from a String

PHP Remove HTML tags from a String :

PHP Remove HTML tags from a String

 The following code is used to remove the html tags from string.

<?php

$input="Hi this is <b>TechniqZone</b>";
$text = strip_tags($input, "");
echo $text;
?>

Output is Hi this is TechniqZone.

The above code remove all html tags from string.


Here strip_tags() function is used to remove tags from string.

string strip_tags ( string $str [, string $allowable_tags ] )


$allowable_tags - You can use the optional second parameter to specify tags which should not be stripped.



<?php

$input="Hi this is lt;a href='http://techniqzone.blogspot.in'><b>TechniqZone</b>lt;/a>";
$text = strip_tags($input, "<b>");
echo $text;
?>


Output is Hi this is TechniqZone. 

Here i allowed <b> tag from string.




Display Current Indian Standard Time using PHP

Display Current Indian Standard Time using PHP :
display indian standard time php


 The following code is used to get the current indian standard time using php.
here the default_timezone_set() function is used to set the country to set the particular time or date of that country.


<?php
date_default_timezone_set('Asia/Calcutta');
echo date("h:i a");
?>

Output of above code is :

06:40 pm

if you want capital letters of am/pm then you just use date("h:i A"). This will return 06:40 PM.

Jul 10, 2013

Php to convert UTC time to local time

Php to convert UTC time to local time
Php to convert UTC time to local time






 Here is a simple code to convert UTC time to local time in php. The $dateInLocal displays the UTC time as localtime.


$time = strtotime($dateInUTC.' UTC');
$dateInLocal = date("Y-m-d H:i:s", $time);
echo $dateInLocal;



Jul 9, 2013

Attachment in mail using PHP

Attachment in mail using PHP



In the previous post, I described HTML content in mails. In this post we can see how attachment in mails can be done using PHP .




$to = 'youraddress@example.com';
//define the subject of the email
$subject = 'Test email with attachment';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-
Content-Type: multipart/alternative; boundary="PHP-alt-"

--PHP-alt-
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!!!
This is simple text email message.

--PHP-alt-
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

TechniqZone Is Help To Guide Developers issues



This is something with HTML formatting.

--PHP-alt---

--PHP-mixed-
Content-Type: application/zip; name="attachment.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment


--PHP-mixed---

//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>

Jul 8, 2013

PHP to Determine Page Execution Time

PHP to Determine Page Execution Time :


PHP to Determine Page Execution Time


The below code is used to find the php page execution time.


Just paste the below code in header portion in php page.

<?php 
   $time = microtime(); 
   $time = explode(" ",$time); 
   $time = $time[1] + $time[0]; 
   $starttime = $time; 
;?> 

after the above code you can add other html or php codes.

and paste the below code in footer page of same php file.

<?php 
   $time = microtime(); 
   $time = explode(" ",$time); 
   $time = $time[1] + $time[0]; 
   $endtime = $time; 
   $totaltime = ($endtime - $starttime); 
   echo "This page execution time is ".$totaltime." seconds"; 
;?>