Archive for the ‘PHP Solutions’ Category

Function to Extract The Value From a String With PHP

Friday, August 8th, 2008

If you’re working with text information, you often need to extract some parts of text from articles, web pages and so on. You can use regular expressions for this, but if you’re not familiar with them, you’ve got to use string functions of PHP.

When I didn’t know what regular expressions are, I’ve written a function that extracts the text you need from a string. It is useful when you need to parse forms, web pages for some exact information, etc. Here it is:

<?

function extract_value($source, $start, $end)
{
$pos=@strpos($source, $start)+strlen(stripslashes($start));
$pos2=@strpos($source, $end, $pos);
$len=$pos2-$pos;
$output=substr($source, $pos, $len);
return $output;
}

?>

Function above takes three arguments: text source, the first matching part and the second matching part. Function extracts the text between these two values. Sample usage is: $match=extract_value($result, “from here”, to here”); This is much easier than to deal with regular expressions, especially if you are new to PHP. This function is not for professionals, however it is a great solution if you often need to parse something from text without regular expressions.

How to Create All Possible Word Combinations from a String With PHP

Monday, August 4th, 2008

Sometimes you need to change the word order in a line for some reason. I am going to show you a PHP solution that allows you to create all possible word combinations from a string. The code below should explain you all operations that are performed.

<?

// Factorial
function fact($s){
if ($s==0) return 1;
else return $fact = $s * fact($s-1);
}

$phrase=”Your Phrase Comes Here”;
// Let’s count the number of words by creating an array
$words=explode(” “, $phrase);
$n=count($words);

// Here comes a loop that creates all possible combinations of array positions
for ($m=1; $m<=fact($n); $m++)
{
$ken = $m-1;
$f = 1;
$a = array();
for($iaz=1; $iaz<=$n; $iaz++)
{
$a[$iaz] = $iaz;
$f = $f*$iaz;
}
for($iaz=1; $iaz<=$n-1; $iaz++)
{
$f = $f/($n+1-$iaz);
$selnum = $iaz+$ken/$f;
$temp = $a[$selnum];
for($jin=$selnum; $jin>=$iaz+1; $jin–)
{
$a[$jin] = $a[$jin-1];
}
$a[$iaz] = $temp;
$ken = $ken%$f;
}
$t=1;

// Let’s start creating a word combination: we have all the necessary positions
$newphrase=”";

// Here is the while loop that creates the word combination
while ($t<=$n)
{
$newphrase.=$words[$a[$t]-1].” “;
$t++;
}
// Output of the phrase
echo $newphrase.”\r\n”;

}

?>

The example above will output:

Your Phrase Comes Here
Your Phrase Here Comes
Your Comes Phrase Here
Your Comes Here Phrase
Your Here Phrase Comes
Your Here Comes Phrase
Phrase Your Comes Here
Phrase Your Here Comes
Phrase Comes Your Here
Phrase Comes Here Your
Phrase Here Your Comes
Phrase Here Comes Your
Comes Your Phrase Here
Comes Your Here Phrase
Comes Phrase Your Here
Comes Phrase Here Your
Comes Here Your Phrase
Comes Here Phrase Your
Here Your Phrase Comes
Here Your Comes Phrase
Here Phrase Your Comes
Here Phrase Comes Your
Here Comes Your Phrase
Here Comes Phrase Your

You can play with number combinations instead of words.

Human Readable Date Format List for PHP date Function

Monday, July 28th, 2008

PHP offers a large variety of arguments that can be passed to the date() function. You are able to almost everything you want having just the current time stamp. I’ve selected the most useful readable formats - I think you might need it for any purpose. I used it to randomize a site’s content to vary posting dates. So, here is the list:

F j, Y
F j, y
F d, Y
F d, y
d-M-Y
d-M-y
j-M-y
j-M-Y
d/n/y
d/m/y
d/n/Y
d/m/Y
j/m/y
j/m/Y
j/n/y
j/n/Y
Y-m-j
Y-n-j
Y-m-d
Y-n-d
n/d/y
m/d/y
n/d/Y
m/d/Y
m/j/y
n/j/y
m/j/Y
n/j/Y
d.m.Y
d.m.y
d.n.Y
d.n.y
j.m.Y
j.n.Y
j.m.y
j.m.y
m-j-Y
n-j-Y
m-d-Y
n-d-Y

Most of these date formats look well and I hope you find it useful

How to Create a db4 Database from a Text File or Array

Monday, July 21st, 2008

When you need to deal with big amounts of data, MySQL is not a good solution. db4 is much faster and easier - you don’t need any SQL queries to extract the necessary values and use them. The process of db4 file creation is quite easy; you need to have your PHP compiled with dba support. If you don’t know how to do it, you can find it on my blog: dba support for PHP

If you have a text file, you need to have your values arranged. The best way to do this is to start each key-value pair with a new line. This way you will easily explode your strings into little arrays and then add them to your db4 database. The code is here:

<?
// Let’s create our db4 file - you should have all the necessary permissions to do it.
$id=dba_open(’./baza.db’, ‘c’, ‘cdb’);
dba_close($id);
// Opening for writing
$id=dba_open(’./baza.db’, ‘w’, ‘db4′);
// Here is an array with keys and values (you may get it from your text file or using any other

// convenient way for you
$positions=array(”some key”=>”some value”);
// We’re inserting these values into our db4 database.
foreach ($positions as $key=>$value)
{
dba_insert($key, $value, $id);
}
// Optimizing our database file
dba_optimize($id);
// That’s all. We can close it
dba_close($id);

?>

We have created a db4 file that should have bigger size than the initial txt file. Next tim I will show you how to access your db4 file and how to extract values from it.

Adding Google Adsense Code Between Topics in phpBB

Sunday, July 6th, 2008

You can often see it even on popular forums. Google Adsense or any other ad code is inserted between posts or looks like a usual post. How do they do that?

I will show you how to add Adsense code after first post and I hope you will be able to figure out how to do it to put it at the middle of posts, as the last post, etc.

We will need to edit two files. They are viewtopic.php and viewtopic_body.tpl (located at the template directory). Let’s start with the first one.
In viewtopic.php in the main phpBB directory, at around line 826, you’ll find:

//
// Okay, let’s do the loop, yeah come on baby let’s do the loop
// and it goes like this …
//

Right under that is the statement that begins the looping through the posts:

for($i = 0; $i < $total_posts; $i++)
{

Under this statement let’s add the block that shows ad code:

if ($i==”0″) {
$adblock = $adblocktext;
} else {
$adblock = “”;
}

Next we should define $adblocktext - it is the variable containing ad code.

$adblocktext = <<<EOM
<tr><td colspan=2 align=center>
Insert your Google AdSense Code Here
</td></tr>
<tr><td class=”spaceRow” colspan=”2″ height=”1″><img
src=”templates/subSilver/images/spacer.gif”
alt=”" width=”1″ height=”1″ /></td>
</tr>
EOM;

Now, let’s declare our ad variable. Scroll down to around line 1170 to find something like this:

$template->assign_block_vars(’postrow’, array(
‘ROW_COLOR’ => ‘#’ . $row_color,
‘ROW_CLASS’ => $row_class,

In that block we need to add the following line:

‘AD_BLOCK’ => $adblock,

That’s all with viewtopic.php. Variables are defined and assigned. Now we need to modify our template to get this working.

Let’s open viewtopic_body.tpl. It should be located in the templates directory under the template that is used at your forum.

Let’s find the line with the following text:

<!– END postrow –>

Right above it, we will add the following text:

{postrow.AD_BLOCK}

That’s all! Don’t forget to save both edited files and have fun! Your code will be shown after the first post. You are able to use JavaScript, Google Adsense code or just everything you want.

How to Decode Javascript Escaped Text with PHP

Saturday, June 21st, 2008

Recently I had to decode a string that was encoded with javascript, using ascii codes of symbols. In JavaScript everything looks simple - unescape() allows to get a readable string. But I had to do it with PHP and the first thought was to use chr and ord functions. But there was a simple solution as usual.

I had to use urldecode to obtain readable text from JavaScript escaped string. Though my string was not an URL, everything went well. So this function might be useful not only for URL decoding, but also helps to deal with Javascript encoding.

Checking Google Pagerank with PHP

Thursday, June 19th, 2008

Today I’ll show you the script that allows to get Google Pagerank value for any site you like. Note, that Google limits the number of toolbar queries per IP per day.

<?php
function StrToNum($Str, $Check, $Magic) {
$Int32Unit = 4294967296;
$length = strlen($Str);
for ($i = 0; $i < $length; $i++) {
$Check *= $Magic;
if ($Check >= $Int32Unit) {
$Check = ($Check - $Int32Unit * (int) ($Check / $Int32Unit));
$Check = ($Check < -2147483648) ? ($Check + $Int32Unit) : $Check;
}
$Check += ord($Str{$i});
}
return $Check;
}

function HashURL($String) {
$Check1 = StrToNum($String, 0×1505, 0×21);
$Check2 = StrToNum($String, 0, 0×1003F);

$Check1 >>= 2;
$Check1 = (($Check1 >> 4) & 0×3FFFFC0 ) | ($Check1 & 0×3F);
$Check1 = (($Check1 >> 4) & 0×3FFC00 ) | ($Check1 & 0×3FF);
$Check1 = (($Check1 >> 4) & 0×3C000 ) | ($Check1 & 0×3FFF);

$T1 = (((($Check1 & 0×3C0) << 4) | ($Check1 & 0×3C)) <<2 ) | ($Check2 & 0xF0F );
$T2 = (((($Check1 & 0xFFFFC000) << 4) | ($Check1 & 0×3C00)) << 0xA) | ($Check2 & 0xF0F0000 );

return ($T1 | $T2);
}

function CheckHash($Hashnum) {
$CheckByte = 0;
$Flag = 0;

$HashStr = sprintf(’%u’, $Hashnum);
$length = strlen($HashStr);

for ($i = $length - 1; $i >= 0; $i –) {
$Re = $HashStr{$i};
if (1 === ($Flag % 2)) {
$Re += $Re;
$Re = (int)($Re / 10) + ($Re % 10);
}
$CheckByte += $Re;
$Flag ++;
}

$CheckByte %= 10;
if (0 !== $CheckByte) {
$CheckByte = 10 - $CheckByte;
if (1 === ($Flag % 2) ) {
if (1 === ($CheckByte % 2)) {
$CheckByte += 9;
}
$CheckByte >>= 1;
}
}

return ‘7′.$CheckByte.$HashStr;
}

function getch($url) { return CheckHash(HashURL($url)); }

function check_pr($url)
{
$googlehost=’toolbarqueries.google.com’;
$user_agent=”Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.14) Gecko/20080404 Firefox/2.0.0.14″;

$ch = getch($url);
if ($ch)
{
$googleurl=’http://’.$googlehost.’/search?client=navclient-auto&ch=’.$ch.’&features=Rank&q=info:’.$url;
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $googleurl);
curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
$data = curl_exec($ch);
curl_close($ch);
if(!substr_count($data, “Rank_”))
return (’n/a’);
else
{
$pos = strpos($data, “Rank_”);
$pr=substr($data, $pos + 9);
$pr=trim($pr);
$pr=str_replace(”\n”,”,$pr);
return $pr;
}
}
}
?>

The most flexible function here is check_pr. Though it accepts ony one argument, you can modify it in the way you lilke. Especially, instead of $googlehost=’toolbarqueries.google.com’; you can enter any Google datacenter to query about pagerank.

Checking E-gold Balance with PHP and cURL

Thursday, June 12th, 2008

I’ve been using e-gold for a while and I am very pleased with this online payment system. Especially I like their shopping card interface that allows to accept or make payments instantly. Today I’ll show you how to check e-gold balance having automation activated and server IP added. This code was written several years ago, so forget me some irregular methods :)

$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.e-gold.com/acct/balance.asp?AccountID=E-gold&Passphrase=Password");
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
$content=curl_exec($ch);
curl_close($ch);

if($content)
{
$balancecontent=$content;
$ot1=strpos($balancecontent, 'type=hidden name=Gold_Grams');
$balancecontent=substr($balancecontent, $ot1);
$ot=strpos($balancecontent," “)+67;
$rezcont=substr($balancecontent, $ot);
$do=strpos($rezcont, “

“);
$balance=substr($balancecontent, $ot, $do);
echo $balance;
}
?>

This code will output your e-gold account balance. If not, please,check whether everything is ok with automation access (you have to confirm several times that you want to enable automation at their site).

How to Use Another IP for cURL Requests

Tuesday, June 10th, 2008

Recently I have had the problem with e-gold automation. E-gold server refused to accept my IP for an unknown reason. I had to send some payments so I triple checked the code, tried different solutions before I got the Idea to try this code from another server IP. This worked and I was happy that my server came with several IPs. All I had to do was to add a string to my code. Here it is:

curl_setopt ($ch,CURLOPT_INTERFACE, “SECOND_SERVER_IP”);

This told cURL to make requests from another IP that was not banned. Hope you will find it useful as it is usually a problem to use different ips for different requests

Monitoring Number of Apache Requests with PHP

Thursday, June 5th, 2008

Today I’ll come with a small piece of code that will allow you to monitor the number af requests to Apache that are processed at the moment. This might help you to prevent server overload as you will always know what’s happening to your Apache. We’ll parse server-status page and will take the number of requests. Simple and fast< as usual.

<?

// Getting the page with server status

$sekas=file_get_contents(”http://localhost/server-status”);
// Locating the position of the number of requests displayed

$pos=strpos($sekas, “requests currently being processed”)-5;
// Creating regexp pattern for replacement
$pattern=”[^0-9]“;
// Replacing non-numeric symbols
$traseu=ereg_replace($pattern, “”, substr($sekas, $pos, 5));
echo $traseu;
?>

Hope this code will help you.