Subscribe For Free Updates!

We'll not spam mate! We promise.

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

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.


Jun 16, 2013

Javascript popup window to return value to parent window

Javascript popup window to return value to parent window:

 We can pass the values to child window to parent window by using javascript. These passing methodology working with html tags and javascript functions.

The javascript popup window is used to get the external value like select the region from map etc.

Follow the below html programs to pass the value from javascript popup window..

parent.html :

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Opener</title>
<script type='text/javascript'>
function valideopenerform(){
var popy= window.open('popup.html','popup_form','location=no,menubar=no,status=no,top=50%,left=50%,height=550,width=750')
}
</script>
</head>

<body>
<form name='form1' id='form1' >
<input type='text' id='text1' name='text1' />
<input type='button' value='go' onclick='valideopenerform()' />
</form>

</body>

</html> 

 In this first html valideopenerform() is i used. in this function i called the second html for open as a popup window. and createone text field with the id "text1". i '' return the value to this text field from popup window.

popup.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Opener</title>
<script type='text/javascript'>
function validepopupform(){
window.opener.document.form1.text1.value=document.form2.text2.value;
self.close();
}
</script>

</head>

<body>
<form id='form2' name='form2' >
<input type='text' id='text2' name='text2' />
<input type='button' value='go' onclick='validepopupform()' />
</form>

</body>


</html> 

 In this second html i used validepopupform() to return the value to parent window text field by using text field id(text1).

Now the value passed to the parent window text field.


May 26, 2013

Rounding Numbers to ‘N’ Decimal

Rounding Numbers to ‘N’ Decimal

 This will let you round off a number to ‘N’ decimal places. In the below example we are rounding of a number to 2 decimal places.

var num = 4.56789;
alert(num.toFixed(2));

It will alert as 4.56.

Another function to display a number upto a length is toPrecision(x).

num = 520.2375;
result = num.toPrecision(4);
alert(result);

It will display as 520.2.
 


Generate Random number from 1 to N

Generate Random number from 1 to N

Below little script helps you in generating random number between 1 to N.


var random = Math.floor(Math.random() * N + 1);




May 23, 2013

Basic MySQL Query Commands

Basic MySQL Query Commands :

Syntax for Query Commands

1. CREATE Command

The Create command is used to create a table by specifying the tablename, fieldnames and constraints as shown below:

Syntax:
$createSQL=("CREATE TABLE tblName");

Example:
$createSQL=("CREATE TABLE tblstudent(fldstudid int(10) NOTNULL AUTO_INCREMENT PRIMARY KEY,fldstudName VARCHAR(250) NOTNULL,fldstudentmark int(4) DEFAULT '0' ");

2. SELECT Command

The Select command is used to select the records from a table using its field names. To select all the fields in a table, '*' is used in the command. The result is assigned to a variable name as shown below:

Syntax:
$selectSQL=("SELECT field_names FROM tablename");

Example:
$selectSQL=("SELECT * FROM tblstudent");

3. DELETE Command

The Delete command is used to delete the records from a table using conditions as shown below:

Syntax:
$deleteSQL=("DELETE * FROM tablename WHERE condition");

Example:
$deleteSQL=("DELETE * FROM tblstudent WHERE fldstudid=2");

4. INSERT Command

The Insert command is used to insert records into a table. The values are assigned to the field names as shown below:

Syntax:
$insertSQL=("INSERT INTO tblname(fieldname1,fieldname2..) VALUES(value1,value2,...) ");

Example:
$insertSQL=("INSERT INTO Tblstudent(fldstudName,fldstudmark)VALUES(Baskar,75) ");

5. UPDATE Command

The Update command is used to update the field values using conditions. This is done using 'SET' and the fieldnames to assign new values to them.

Syntax:
$updateSQL=("UPDATE Tblname SET (fieldname1=value1,fieldname2=value2,...) WHERE fldstudid=IdNumber");

Example:
$updateSQL=("UPDATE Tblstudent SET (fldstudName=siva,fldstudmark=100) WHERE fldstudid=2");

6. DROP Command

The Drop command is used to delete all the records in a table using the table name as shown below:

Syntax:
$dropSQL=("DROP tblName");

Example:
$dropSQL=("DROP tblstudent");



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

.htaccess Automatically redirect to Mobile Website

.htaccess Automatically redirect to Mobile WebSite :


 Here i will explain how to redirect your website automatically to mobile scree website. This method is functioned from your website .htaccess. so this method is more efficient compare with find screen resolution and then redirect.

The .htaccess only assign our websites url functionality in on-load of site front-end coding.

Here is the coding :


 >>Note : # is used to comand the line in .htaccess.

RewriteEngine on
RewriteBase /
# Check if this is the noredirect query string
RewriteCond %{QUERY_STRING} (^|&)m=0(&|$)
# Set a cookie, and skip the next rule
RewriteRule ^ - [CO=mredir:0:www.techmiqzone.blogspot.in]

# Check if this looks like a mobile device
# (You could add another [OR] to the second one and add in what you
#  had to check, but I believe most mobile devices should send at
#  least one of these headers)
RewriteCond %{HTTP:x-wap-profile} !^$ [OR]
RewriteCond %{HTTP:Profile}       !^$ [OR]
RewriteCond %{HTTP_USER_AGENT} "acs|alav|alca|amoi|audi|aste|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd-" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "dang|doco|eric|hipt|inno|ipaq|java|jigs|kddi|keji|leno|lg-c|lg-d|lg-g|lge-" [NC,OR]
RewriteCond %{HTTP_USER_AGENT}  "maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|nec-|newt|noki|opwv" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "palm|pana|pant|pdxg|phil|play|pluc|port|prox|qtek|qwap|sage|sams|sany" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "teli|tim-|tosh|tsm-|upg1|upsi|vk-v|voda|w3cs|wap-|wapa|wapi" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "wapp|wapr|webc|winw|winw|xda|xda-" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "up.browser|up.link|windowssce|iemobile|mini|mmp" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "symbian|midp|wap|phone|pocket|mobile|pda|psp" [NC]
RewriteCond %{HTTP_USER_AGENT} !macintosh [NC]

# Check if we're not already on the mobile site
RewriteCond %{HTTP_HOST}          !^m\.
# Can not read and write cookie in same request, must duplicate condition
RewriteCond %{QUERY_STRING} !(^|&)m=0(&|$) 

# Check to make sure we haven't set the cookie before
RewriteCond %{HTTP_COOKIE}        !^.*mredir=0.*$ [NC]

# Now redirect to the mobile site
RewriteRule ^ http://m.techmiqzone.blogspot.in [R,L]


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';
}

May 7, 2013

Get URL from address bar - PHP


Get URL from address bar - PHP

 The following code is used to get full url address by using php.

<?php
$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo $url;
?>

Notes:
 Here we are using 2 functions in php to get full url from address bar.
1. $_SERVER['HTTP_HOST']
2. $_SERVER['REQUEST_URI']
$_SERVER['HTTP_HOST'] - This function will show only server name.
$_SERVER['REQUEST_URI'] - This function will show you the path to file of your url.

 When you run $_SERVER['HTTP_HOST'];  for this website you'll get result "www.techniqzone.blogspot.in" only, no "http://" no "/Get URL from address bar - PHP"

<?php 
$server=$_SERVER['HTTP_HOST'];
echo $server;
?>

Output is "www.techniqzone.blogspot.in".

This script "$_SERVER['REQUEST_URI']" display the result like below.
no "http://" and no "www.techniqzone.blogspot.in

Example:

<?php
$request_url=$_SERVER['REQUEST_URI'];
echo $request_url;
?>

Output of $_SERVER['REQUEST_URI'] is "/Get URL from address bar - PHP"

If you want to get full URL from this site you, we have to use (.) to connect 2 functions together and create http:// by yourself.

<?php
$url="http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo $url;
?>

May 6, 2013

Random Password Generator


Random Password Generator

 This tool is used to generate the random password that is generate random string with given "n" length.
This tool is very use full for generate password with full secured.


Password length :
Password :

May 5, 2013

Get details about an image in PHP


Get details about of an image in PHP:

The following code is used to get the all details about image by using php and the result will be store in an array.



<?php
$filename = image.jpg; //image file path
$imgDetails = getimagesize($filename);
print_r($imgDetails);
?>

The beloow code is simple to get width and height, type of the image file.


<?php
$img = "images/empty.gif";
list($width, $height, $type, $attr) = getimagesize($img);
print "Width : $width and height = $height";
?> 



May 4, 2013

Get cursor position in a textarea - Jquery


Get cursor position in a textarea - Jquery:

The following code is used to get the cursor point in textarea. if you change the id of textarea with particular div id then you can get the cursor points within the div.


(function ($, undefined) {
    $.fn.getCursorPosition = function() {
        var el = $(this).get(0);
        var pos = 0;
        if('selectionStart' in el) {
            pos = el.selectionStart;
        } else if('selection' in document) {
            el.focus();
            var Sel = document.selection.createRange();
            var SelLength = document.selection.createRange().text.length;
            Sel.moveStart('character', -el.value.length);
            pos = Sel.text.length - SelLength;
        }
        return pos;
    }
})(jQuery);

the bellow code is for set textarea id to call the above function.

$("#myTextBoxSelector").getCursorPosition();

May 3, 2013

JQuery to get Current Date


JQuery to get Current Date:

 The following code is used to get current date and time by using jquery.

 Before that, Date() function is not the part of JQuery. it is one of JavaScript's features.

var date = new Date();

var month = date.getMonth()+1;
var day = date.getDate();
var output = date.getFullYear() + '-' + (month<10 :="" day="" font="" month="">


May 2, 2013

Random String Generator in PHP



Random String Generator in PHP:


 The following function "getrandum_str()" is used to get the random string with specified string length.
This function may used to get encrypted key value or generate the random password and etc...


<?php
function getrandum_str()
{
  $abc = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  $lengt = 10; // set the length of result
  $strn = "";
  for($i=0;$i<$lengt;$i++)
  {
    $strn.=$abc[rand(0,strlen($abc)-1)];
  }
  return $strn;
}
?>