Saturday, April 10, 2010

regular expression in php examples

Contact Us :

Hire PHP Web Developer

regular expression in php examples
TO CHECK ALPHA-NUMERIC STRING
$subject = "hi to all 123";

if(preg_match('/[^A-Za-z0-9\ ]/i',$subject))
{
echo "error";
}
else
{
echo "success";
}

FIND SPECIFIC LINK FROM WEBPAGE
$content = @file_get_contents("http://www.somewebpage.com/somepage.html");
$trans = array('/'=>'\/');
$link = strtr("http://www.searchdomain.com",$trans);
$regexp = '/<a\s[^>]*href=\"'.$link.'\"[^>]*>searchdomain<\/a>/siU';
if(@preg_match($regexp, $content))
{
echo "Match"; 
}
else
{
echo "Not Match"; 
}

FIND EMAIL FROM FOLLOWING CONTENT
$content = "Aamir  [aamir@yahoo.com], Alice [alice@yahoo.com]";

$friends_array = explode(',',$content);

for($i=0; $i<count($friends_array); $i++)
{

preg_match('/[^>]*\[(.*)\]/Ui',$friends_array[$i],$matches);

print_r($matches);
}

 GET ALL LINKS FROM WEBPAGE
$page = @file_get_contents("http://www.somewebpage.com/somepage.html");
$reg_expr = '/<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>/siU';
preg_match_all($reg_expr,$page,$matches);

Thursday, March 25, 2010

how to get row number in mysql select query

Contact Us :
Hire PHP Web Developer

Example Table : test

id  name
====   ======
2 xyz
5       abc
6       pqr
7       uvw


Query :
SET @i := 0;
SELECT @i := @i + 1 as row_num,id,name FROM test WHERE 1=1


OUTPUT
row_num  id  name
=======  ====   ======
1        2 xyz
2        5       abc
3        6       pqr
4        7       uvw

Tuesday, February 9, 2010

htaccess redirect invalid url to error page

Contact Us

Hire PHP Web Developer


If you are new to htaccess , Create htaccess file by rename any file with ".htaccess" name.

Now you can write rules & conditions for invalid urls

Some common error code:
  • 401 - Authorization Required
  • 400 - Bad request
  • 403 - Forbidden
  • 500 - Internal Server Error
  • 404 - Page Not Found
To redirect to error page we can use following :

Syntax :

ErrorDocument ERROR_CODE /ERROR_REDIRECT_FILE.html

Examples :

ErrorDocument 404 /error_404.html

ErrorDocument 500 /somefolder/error_500.html


Some More Examples

  • RewriteRule ^/$ /homepage.html [L]
  • RewriteCond %{REQUEST_FILENAME} !-f

    RewriteRule ^(.+)errata\.html?$ cgi-bin/errata/errata-html/$1

    (Rewrites can be conditional, for example, rewrite only if the file could not be found: )
  • RewriteRule ^(.*)/(.*)$ index.php?param1=$1¶m2=$2 [L]

    (Match if url passed like "http://www.mysite.com/value1/value2/" then redirect to http://www.mysite.com/index.php?param1=value1¶m2=value2)

Note : If you have any query or questions about htaccess programing kindly post your comments 

Wednesday, January 27, 2010

Display Find Get Yahoo Backlinks in php

Contact Us

Hire PHP Web Developer

$url = "http://www.google.com";

$page = file_get_contents("http://siteexplorer.search.yahoo.com/search?p=$url&bwm=i&bwmf=a&bwms=p");

$expression = '/<span class="btn">Inlinks \((.*)\)<i class="tl"><\/i>/Us'; 

preg_match($expression, $page, $matches); 

print_r($matches);

Search whole word from database value in mysql

Contact Us

Hire PHP Web Developer

Following example will retrive all the records from table that have 'music' word in emp_info colomn.
Query will avoid emp_id = 4 bcoz its not has 'music' only. its 'musics' in value.

There are 3 ways, you can get result from databse.

Lets assume we have following table :

table : emp_info

CREATE TABLE 
  emp_info (
  emp_id  INT UNSIGNED NOT NULL PRIMARY KEY,
  emp_name VARCHAR(200),
  emp_info TEXT,
  FULLTEXT (emp_info)
   );

Insert following rows into table :

emp_id  emp_name emp_info
=============================================================================
1  Rocky  i love to sing a song 
2  Andy  i want to become a singer 
3  Jackson  i am music lover
4  Neil  i don't like musics
5  Williem  sometime i enjoy music
6  Helly  i love music all day 


query1 => SELECT emp_id FROM emp_info WHERE  emp_info like '% music %'
query2 => SELECT emp_id FROM emp_info WHERE  MATCH (emp_info) AGAINST('music') 
query3 => SELECT emp_id FROM emp_info WHERE  emp_info REGEXP '[[:<:]]music[[:>:]]' =1 

Output of all query: 
emp_id : 
3
5
6

contact : iamvasim@gmail.com

Monday, January 18, 2010

how to use ob_start function in php

Contact Us

Hire PHP Web Developer

Syntax :
bool ob_start ([ callback $output_callback [, int $chunk_size [, bool $erase ]]] )

what it does :
This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.

Example :

<?php
function callback_function($buffer)
{
// replace all the apples with oranges
return (str_replace("hi", "hello", $buffer));
}

ob_start("callback_function");
?>
<html>
<body>
<p>Hello World, example : hi to all </p>
</body>
</html>
ob_end_flush();

Output :
Hello World, example : hello to all

Wednesday, November 11, 2009

Read Atom Feed From Blogger Entry

Contact Us

Hire PHP Web Developer

$xml_url = "http://scriptforphp.blogspot.com/feeds/posts/default";

$ch = curl_init($xml_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);

if(!preg_match("|The blog you were looking for was not found.|Ui",$data))
{
$xml = new SimpleXmlElement($data, LIBXML_NOCDATA);
$xml_detail = parseAtom($xml);
for($j=0; $j<count($xml_detail); $j++)
{
$url = addslashes($xml_detail[$j][url]);
$title = addslashes($xml_detail[$j][title]);
$desc = addslashes($xml_detail[$j][desc]);

}
}


function parseAtom($xml)
{
$cnt = count($xml->entry);

$atom = array();
for($i=0; $i<$cnt; $i++)
{
$total_link = count($xml->entry[$i]->link);
for($j=0; $j<$total_link; $j++)
{
$urlAtt = $xml->entry[$i]->link[$j]->attributes();
if($urlAtt['rel']=="alternate")
{
$atom[$i]['url'] = $urlAtt['href'];
}
}

$atom[$i]['title'] = $xml->entry[$i]->title;
$atom[$i]['desc'] = substr(strip_tags($xml->entry[$i]->content),0,130);
}
return $atom;
}

Monday, August 10, 2009

publish post on movable type api blog with xmlrpc

Contact Us

Hire PHP Web Developer

require_once('IXR_Library.inc.php'); // Download

$blog_id = "2"; // only blogid no need to set username/password for blog

$admin_user = "username here"; // Login username => that you use at http://www.yourdomain.com/cgi-bin/mt.cgi
$admin_pass = "password here"; // Web Services Password => will be found at http://www.yourdomain.com/cgi-bin/mt.cgi?__mode=view&_type=author&id=XX
$xmlrpc_host = "http://www.yourdomain.com/cgi-bin/mt-xmlrpc.cgi"; // or http://www.yourdomain.com/cgi-bin/mt/mt-xmlrpc.cgi

$client = new IXR_Client($blog_url);

if (!$client->query('metaWeblog.getCategories',$blog_id, $admin_user,$admin_pass)) {
die('An error occurred - '.$client->getErrorCode().":".$client->getErrorMessage());
}

$content['title'] = "Free PHP Script";
$content['categories'] = array($response[0]['categoryName']);
$content['description'] = '<p> <b> Free PHP Script !!! </b> <br> Author : Vasim Padhiyar <br> Contact : iamvasim@gmail.com <br> Blog : http://scriptforphp.blogspot.com </p>';

if (!$client->query('metaWeblog.newPost',$blog_id, $admin_user,$admin_pass, $content, true)) {
die('An error occurred - '.$client->getErrorCode().":".$client->getErrorMessage());
}
else
{
$response = $client->getResponse();
}

$post_id = $response['postid'];
$post_url = $response['link'];
$category = $response['categories'][0];

Tuesday, August 4, 2009

how to integrate google search api for php

Contact Us

Hire PHP Web Developer

$url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=~car~insurance&rsz=large&hl=en&safe=off";

// sendRequest
// note how referer is set manually
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, "http://www.scriptforphp.blogspot.com");
$body = curl_exec($ch);
curl_close($ch);


// download json library file from Download Here

include('JSON/JSON.php');
$object = new Services_JSON();
$json = $object->decode($body);

echo '<pre>';
print_r($json);
exit;

Tuesday, July 28, 2009

How to read article from text file ?

Contact Us :
Hire PHP Web Developer

# problem : How to read article from text file ?
# article txt file will be in following way
# root_directory/test/import/file1.txt , root_directory/test/import/file2.txt
# filename or directory does not matter
# Article format : 1st line = title , rest of will be article body

$dir = "test/import";

if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$files[] = $file;
}
}
closedir($handle);
}

for($i=0; $i<count($files); $i++)
{
$file = $dir."/".$files[$i];
$fp = fopen($file, "r");
$title = fgets($fp);
$body = fread ($fp, filesize ($file));
fclose ($fp);

echo "<h2>".$title."</h2>";
echo "<span>".nl2br($body)."</span>";
echo "<br>";
}

Monday, June 29, 2009

convert DATE format to UNIX TIMESTAMP in mysql


Table : info
============================
id name dob
============================
1 test1 2008-12-03 00:00:00
2 test2 2009-06-01 00:00:00
============================

$sql = "SELECT UNIX_TIMESTAMP(dob) AS birthdate FROM info WHERE 1=1";

OUTPUT :
-------------
birthdate
========
1228280400
1243828800

How to convert UNIX TIMESTAMP to DATE in mysql


Table : info
============================
id name dob
============================
1 test1 1235994659
2 test2 1235994707
============================


$sql = "SELECT DATE(FROM_UNIXTIME(dob)) AS birthdate FROM info WHERE 1=1";


OUTPUT :
-------------
birthdate
========
2009-03-02
2009-03-02

Monday, June 22, 2009

fopen fwrite in php

// Create ip.txt file
// place code below

$iptxt = $_SERVER['REMOTE_ADDR']
$fname = "ip.txt";
$fhandle = fopen($fname,"r");
$fhandle = fopen($fname,"w");
fwrite($fhandle,$iptxt);
fclose($fhandle);

Friday, June 19, 2009

how to check all checkboxes within a div elemen in javascript

JAVASCRIPT
=======================================
<script type="text/javascript">
function checkByParent(aId, aChecked) {
var collection = document.getElementById(aId).getElementsByTagName('INPUT');
for (var x=0; x if (collection[x].type.toUpperCase()=='CHECKBOX')
collection[x].checked = aChecked;
}
}
</script>
<a href="#" onclick="checkByParent('mydiv', true)">CHECK</a>
<div id="mydiv">
CHECK 1 <input type="checkbox">
CHECK 2 <input type="checkbox">
CHECK 3 <input type="checkbox">
CHECK 4 <input type="checkbox">
CHECK 5 <input type="checkbox">
</div>

Tuesday, June 16, 2009

The reference to entity must end with the ';' delimiter

// For Blogger post if u got above error please try below code
// this will post html content in a publish post
$DB_ARTICLE[article_title]="Any Title";
$DB_ARTICLE[article_text] = <h1>Your content</h1>"
$entry = "<entry xmlns='http://www.w3.org/2005/Atom'>
<title type='text'>".$DB_ARTICLE[article_title]."</title>
<content type='text/html'>".htmlentities($DB_ARTICLE[article_text])."</content>
</entry>";

Thursday, June 11, 2009

how to create login logout script in php

I search through the internet and find below usefull tutorial
check out this is very easy step by step script provided
with graphical view too.

PHP Login script tutorial

how to create rss feed in php

// How to create RSS feed for site in php
// Check your rss is correct or not @ http://validator.w3.org/feed/


$a='<?xml version="1.0" encoding="UTF-8"?>';
$a .='<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">';
$a.='<channel>';
$a.= '<atom:link href="http://www.anydomain.com?feed=xml" rel="self" type="application/rss+xml" />';
$a.='<title>Your Site Title</title>';
$a.='<link>http://www.yourdomain.com</link>';
$a.='<description>Your site Details here</description>';
$a.='<language>en-us</language>';
$a.='<docs>http://blogs.law.harvard.edu/tech/rss/</docs>';
$a.='<item>';
$a.='<title>Title For Item1</title>';
$a.='<link>http://www.linktoitem1.com</link>';
$a.='<guid>http://www.linktoitem1.com</guid>';
$a.='<description>Item1 Description Here</description>';
$a.='<pubDate>'.date("D, d M Y H:i:s T",UNIX_TIMESTAMP).'</pubDate>';
$a.='</item>';
$a.='<item>';
$a.='<title>Title For Item2</title>';
$a.='<link>http://www.linktoitem2.com</link>';
$a.='<guid>http://www.linktoitem2.com</guid>';
$a.='<description>Item2 Description Here</description>';
$a.='<pubDate>'.date("D, d M Y H:i:s T",UNIX_TIMESTAMP).'</pubDate>';
$a.='</item>';
$a.='</channel>';
$a.='</rss>';

echo trim($a);

How to swap 2 variable values without using 3rd variable in php

$a = 10;
$b = 20;

$a=$a+$b;
$b=$a-$b;
$a=$a-$b;

echo $a;
echo $b;

Wednesday, June 10, 2009

how to order mysql query via input order in an IN() clause

SELECT *
FROM `articles`
WHERE article_id
IN ( 31, 27, 36, 23 )
ORDER BY FIND_IN_SET(
article_id,'31,27,36,23' )
LIMIT 0 , 30

Monday, June 8, 2009

Free sandbox paypal script in php

// First create 3 files in root of site called
// paypal_return.php,cancel_return.php,notify_return.php
// Replace business@domain.com with your test business account email id

<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" name="frm" id="frm" method="post">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="upload" value="1">
<input type="hidden" name="business" value="business@domain.com">
<input type="hidden" name="item_name" value="Deposite Balance">
<input type="hidden" name="amount" value="100">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="charset" value="utf-8">
<input type="hidden" name="rm" value="2" >
<input type="hidden" name="return" id="return" value="http://yoursite/paypal_return.php" />
<input type="hidden" name="cancel_return" value="http://yoursite/cancel_return.php">
<input type="hidden" name="notify_url" value="http://yoursite/notify_return.php">
<input type="hidden" name="first_name" value="Vasim" />
<input type="hidden" name="last_name" value="Padhiyar" />
<input type="submit" value="Paypal" name="btn" />
</form>

// After Payment Complete , Paypal will return you Token in request
// on paypal_return.php
//Check This Token Transation Record on paypal server as below

$order_status = check_paypal($_REQUEST['tx']);

if($order_status=='SUCCESS')
{
// Update Database and return to main page
}
else
{
// Error msg
}


// Replace $auth_token with your appropriate token
function check_paypal($paypal_tx)
{
$status = "FAIL";

$req = 'cmd=_notify-synch';

$tx_token = $paypal_tx;

$auth_token = "03suYLK9KVmKHZMETOKW4Ad0g2uDM7R2mS0-IUd4B2tFr6E0SlDZRUVSX-G";

$req .= "&tx=$tx_token&at=$auth_token";

$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('www.sandbox.paypal.com', 80, $errno, $errstr, 30);

if (!$fp)
{
$status = "FAIL";
}
else
{
fputs ($fp, $header . $req);

$res = '';
$headerdone = false;
while (!feof($fp))
{
$line = fgets ($fp, 1024);

if (strcmp($line, "\r\n") == 0)
{
$headerdone = true;
}
else if ($headerdone)
{
$res .= $line;
}
}

$lines = explode("\n", $res);

$keyarray = array();

if (strcmp ($lines[0], "SUCCESS") == 0)
{
$status = "SUCCESS";
}
else if (strcmp ($lines[0], "FAIL") == 0)
{
$status = "FAIL";

}

}

fclose ($fp);

return $status;
}