Subscribe For Free Updates!

We'll not spam mate! We promise.

Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

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.

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 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 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".

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

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);

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"; 
;?>

Jul 7, 2013

Sending Nice HTML Email with PHP


Sending Nice HTML Email with PHP :





   Everyone wishes to include Html content in their mails. Here is a sample code to send a mail with HTML content. You can edit the HTML content as you prefer.


$to = 'sample@example.com';

$subject = 'Sample HTML content';

$headers = "From: " . strip_tags($_POST['req-email']) . "\r\n";
$headers .= "Reply-To: ". strip_tags($_POST['req-email']) . "\r\n";
$headers .= "CC: susan@example.com\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";

$message = '<h1>';';
$message .= '<a href='http://techniqzone.blogspot.in/'>TechniqZone</a> Is Help To Guide Developers issues.';
$message .= '</h1>';
mail($to, $subject, $message, $headers);


$message contains HTML content. And the HTML content will be executed in the mail.

PHP Get Last 12 Months


PHP to get last 12 months : 

 The following coding is used to get previous 12 months by using PHP.



<?php

for ($t = 1; $t <= 12; $t++) {
    echo date("F Y m", strtotime( date( 'Y-m-01' )." -$t months"));
    echo "<br />";
}

?>

 Output of this code is :

June 2013 06
May 2013 05
April 2013 04
March 2013 03
February 2013 02
January 2013 01
December 2012 12
November 2012 11
October 2012 10
September 2012 09
August 2012 08
July 2012 07



 Here date "F Y m" is used to make the date format in above format. you can store these dates in arrat also by using below code.


<?php
for ($t = 1; $t <= 12; $t++) {
    $mnt[]= date("F Y m", strtotime( date( 'Y-m-01' )." -$t months"));
}
?>


Here $mnt is php array variable with last 12 months.

Jun 17, 2013

Get all images from folder - php

Get all images from folder - php:

 The below code is used to get all images from folder in local system. we can set the condition for file type to read files from particular directory in php.

<?php
$imgdir = 'images/'; 
$allowed_types = array('png','jpg','jpeg','gif'); 
$dimg = opendir($imgdir);
while($imgfile = readdir($dimg))
{
  if( in_array(strtolower(substr($imgfile,-3)),$allowed_types) OR
          in_array(strtolower(substr($imgfile,-4)),$allowed_types) )
/*If the file is an image add it to the array*/
  {$a_img[] = $imgfile;}
}
echo "<ul>";

 $totimg = count($a_img);

 for($x=0; $x < $totimg; $x++)
{
echo "<li><img src='" . $imgdir . $a_img[$x] . "' /></li>";
}
echo "</ul>";


?>


 In the above coe $imgdir is used to pick your directory. $allowed_type is used to set the type of files u allowed from folder to pickup. 

opendir() function is used to open your given folder to read it.

readdir() is used to read folder. the while loop is read all files from folder and push the allowed type files in $a_img array.

Now we can print all image name by using for loop or any other method.


May 21, 2013

Get body message content from mail using PHP

Get body message content from mail using PHP :

 Here i will explain how to get mail contents(body of mail) by using php. Here i used two functions like imap_num_msg() and imap_body() which return the contents of a specific message respectively and the number of messages in the mail box.

Syntax of these function:

int imap_num_msg ( resource imap_stream)
string imap_body ( resource imap_stream, int msg_number, int options)

1. To get number of mail in inbox :


 For get this we need to pass IMAP stream into imap_num_msg() function and it return the result.


<?php

    $imap = imap_open("{mail.yourserver.com:143}INBOX", "username", "password");

    $message_count = imap_num_msg($imap);

    print $message_count;

    imap_close($imap); 

?>

2. To get message content :

 <?php

    $imap = imap_open("{mail.yourserver.com:143}INBOX", "username", "password");

    $message_count = imap_num_msg($imap);

    for ($i = 1; $i <= $message_count; ++$i) {

        $header = imap_header($imap, $i);

        $body = trim(substr(imap_body($imap, $i), 0, 100)); // 100 specifies no.of character u need.

        $prettydate = date("jS F Y", $header->udate);

        if (isset($header->from[0]->personal)) {

            $personal = $header->from[0]->personal;

        } else {

            $personal = $header->from[0]->mailbox;

        }

        $email = "$personal <{$header->from[0]->mailbox}@{$header->from[0]->host}>";

        echo "On $prettydate, $email said \"$body\".\n";

    }

    imap_close($imap); 

?>





May 19, 2013

Use JSON in PHP 4 or PHP 5.1.x

Use JSON in PHP 4 or PHP 5.1.x : 


Here i will explain how to use JSON (json_encode() , json_decode()) in versions of PHP earlier than 5.2. Add the following custom function to use (json_encode() , json_decode()) this functions in php. IF u don't have this JSON PEAR Package You can download in HERE 

1. for json_encode() :

if (!function_exists('json_encode')) {
    function json_encode($content) {
        require_once 'classes/JSON.php';
        $json = new Services_JSON;
        return $json->encode($content);
    }
}

2. for json_decode() :

if (!function_exists('json_decode')) {
    function json_decode($content, $assoc=false) {
        require_once 'classes/JSON.php';
        if ($assoc) {
            $json = new Services_JSON(SERVICES_JSON_LOOSE_TYPE);
        }
        else {
            $json = new Services_JSON;
        }
        return $json->decode($content);
    }
}


Now you can work with JSON, even when you eventually upgrade to PHP 5.2.

 The JSON PEAR Package download page link is given below :
 
   >>> Download the Services_JSON PEAR package


May 10, 2013

php to remove last two characters from string



php remove last two characters from string

 The following code is used to remove character from the last of the string. here "substr()" function is used.
this function is used to get substring from original string.

<?php
echo substr('abcdef', 1);     // bcdef
echo substr('abcdef', 1, 3);  // bcd
echo substr('abcdef', 0, 4);  // abcd
echo substr('abcdef', 0, 8);  // abcdef
echo substr('abcdef', -1, 1); // f

// Accessing single characters in a string
// can also be achieved using "square brackets"
$string = 'abcdef';
echo $string[0];                 // a
echo $string[3];                 // d
echo $string[strlen($string)-1]; // f

?>

May 9, 2013

Check String Contain Specific words - PHP



Check String Contain Specific words - PHP

The following code is used to find the specific words or char from a string by using php.
here "strpos()" is used. This function is used to get string position from the original string. here i just get true or false result if the original string contains the specific word or character,

if (strpos($a,'are') !== false) 
{
    echo 'true';
}
else
{
    echo 'false';
}