PHP 4 Savvy Coding


I encountered this problem several times coding with wordpress plugins. As lots of servers still running in PHP4 are likely to have this problem. So I’m writing there the solutions to those.

file_put_contents() function is only introduced after PHP5 so if you have to run codes in servers running still old PHP4 you can use the following code to create an alternative function on the fly:

if(!function_exists('file_put_contents')) {
function file_put_contents($File, $Data, $Append = false) {
if(!$Append) $Mode = 'w';
else $Mode = 'a';
$Handle = @ fopen($File, $Mode);
if(!$Handle) return false;
$Bytes = fwrite($Handle, $Data);
fclose($Handle);
return $Bytes;
}
}

Or, Alternatively you can write this code snippet to replace just the function call if there’s not much call to it:

 if( !function_exists('file_put_contents') )
{
function file_put_contents($filename_comments,$data_comments)
{
$fh = @fopen($filename_comments,'w');
if( $fh ) { fwrite($fh,$data,strlen($data_comments)); fclose($fh); }
}
}

If you come around with str_ireplace() function you can do the following:

if(!function_exists('str_ireplace')) {
function str_ireplace($search,$replace,$subject) {
$search = preg_quote($search, "/");
return preg_replace("/".$search."/i", $replace, subject);
}
}

Or this:

if (!function_exists('str_ireplace')  {
function str_ireplace($search,$replace,$subject) {
$token = '^[[term^]';
$haystack = strtolower($subject);
$needle = strtolower($search);
while (($pos=strpos($haystack,$needle))!==FALSE)  {
$c++;
$subject = substr_replace($subject,$token,$pos,strlen($search));
$haystack = substr_replace($haystack,$token,$pos,strlen($search));
}
while (($pos=strpos($subject,$token))!==FALSE)  {
$subject = substr_replace($subject,$replace,$pos,strlen($token));
}
return $subject;
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s