Thursday, September 16, 2010

PHP HELPS

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 = '/]*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]*\[(.*)\]/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 = '/]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>/siU';
preg_match_all($reg_expr,$page,$matches);


how to get row number in mysql select query
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

htaccess redirect invalid url to error page

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&param2=$2 [L]

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


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

Display Find Get Yahoo Backlinks in php

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

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

$expression = '/Inlinks \((.*)\)<\/i>/Us';

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

print_r($matches);

Search whole word from database value in mysql

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


how to use ob_start function in php
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 :



Hello World, example : hi to all




ob_end_flush();

Output :
Hello World, example : hello to all

Read Atom Feed From Blogger Entry
$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; $jentry);

$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;
}
Posted by Vasim Padhiyar at 10:46 PM 0 comments Links to this post
Monday, August 10, 2009
publish post on movable type api blog with xmlrpc
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'] = '

Free PHP Script !!!
Author : Vasim Padhiyar
Contact : iamvasim@gmail.com
Blog : http://scriptforphp.blogspot.com

';

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];
Posted by Vasim Padhiyar at 2:54 AM 0 comments Links to this post
Tuesday, August 4, 2009
how to integrate google search api for php
$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 '

';
print_r($json);
exit;
Posted by Vasim Padhiyar at 7:38 AM 2 comments Links to this post
Labels: google search, json decode, json encode
Tuesday, July 28, 2009
How to read article from text file ?
# 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

".$title."

";
echo "".nl2br($body)."";
echo "
";
}

# contact me : iamvasim@gmail.com for more free php script

# do you want to create your own article directory ?
# do you want to create auto article submition directory ?
# you can hire php web developer from http://scriptforphp.blogspot.com
Posted by Vasim Padhiyar at 11:57 PM 1 comments Links to this post
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

Posted by Vasim Padhiyar at 4:15 AM 0 comments Links to this post
Labels: DATE TIME, MYSQL
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

Posted by Vasim Padhiyar at 4:10 AM 1 comments Links to this post
Labels: DATE TIME, MYSQL
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);
Posted by Vasim Padhiyar at 7:25 AM 0 comments Links to this post
Labels: fopen, fwrite
Friday, June 19, 2009
how to check all checkboxes within a div elemen in javascript
JAVASCRIPT
=======================================

CHECK


CHECK 1
CHECK 2
CHECK 3
CHECK 4
CHECK 5


Posted by Vasim Padhiyar at 12:35 AM 2 comments Links to this post
Labels: checkbox, javascript
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] =

Your content

"
$entry = "

".htmlentities($DB_ARTICLE[article_text])."
";
Posted by Vasim Padhiyar at 5:02 AM 0 comments Links to this post
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

Posted by Vasim Padhiyar at 4:37 AM 0 comments Links to this post
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='';
$a .='';
$a.='';
$a.= '';
$a.='';
$a.='http://www.yourdomain.com';
$a.='Your site Details here';
$a.='en-us';
$a.='http://blogs.law.harvard.edu/tech/rss/';
$a.='';
$a.='';
$a.='http://www.linktoitem1.com';
$a.='http://www.linktoitem1.com';
$a.='Item1 Description Here';
$a.=''.date("D, d M Y H:i:s T",UNIX_TIMESTAMP).'';
$a.='';
$a.='';
$a.='';
$a.='http://www.linktoitem2.com';
$a.='http://www.linktoitem2.com';
$a.='Item2 Description Here';
$a.=''.date("D, d M Y H:i:s T",UNIX_TIMESTAMP).'';
$a.='';
$a.='';
$a.='';

echo trim($a);
Posted by Vasim Padhiyar at 4:22 AM 0 comments Links to this post
Labels: FEED, RSS
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;
Posted by Vasim Padhiyar at 4:11 AM 0 comments Links to this post
Labels: SWAP
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
Posted by Vasim Padhiyar at 3:27 AM 0 comments Links to this post
Labels: MYSQL, ORDER BY
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


Top of Form















Bottom of 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;
}

Saturday, January 9, 2010

Important link for developer

Hello All,

Please post the links and document you are creating new at the time of development.

Thanks
pankaj