PHP

PHP, source code, scripts, developing, tips & hints

Extract images from HTML

0

Small script to extract the images from a text or HTML.

$html=file_get_contents("http://neo22s.com");
$imgsrc_regex = '!http://.+\.(?:jpe?g|gif|png)!Ui';
preg_match($imgsrc_regex, $html, $matches);
print_r ($matches);

How to redirect your RSS Feed to Feedburner

0

This is a really simple yet handly tip to redirect your feed to Feedburner.

Edit, or create an .htaccess file in your htdocs root, and add this lines:

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_USER_AGENT} !FeedBurner
RewriteRule ^rss/$ http://feeds.feedburner.com/yourURL [R,L]
</IfModule>

Now any request to yoursite.com/feed will be redirected to the custom feedburner feed ;)

Be aware that only works in apache.

Youtube brackets

0

I’ve been using youtube bracket for wp for long time.

Based on that Idea I isolated it to make it work at any installation.

This script allows you to write anywhere in your content this and will return a flash player with the video embed.

Function that embeds the flash in the content:

$content=mediaPostDesc($content);//usage
 
function mediaPostDesc($the_content){//from a description add the media
//using http://www.robertbuzink.nl/journal/2006/11/23/youtube-brackets-wordpress-plugin/
    if (VIDEO){
        $stag = "[youtube=http://www.youtube.com/watch?v=";
        $etag = "]";
        $spos = strpos($the_content, $stag);
        if ($spos !== false){
            $epos = strpos($the_content, $etag, $spos);
            $spose = $spos + strlen($stag);
            $slen = $epos - $spose;
            $file  = substr($the_content, $spose, $slen);    
			//youtube
            $tags = '<object width="425" height="350">
                    <param name="movie" value="'.$file.'"></param>
                    <param name="wmode" value="transparent" ></param>
                    <embed src="http://www.youtube.com/v/'. $file.'" type="application/x-shockwave-flash" wmode="transparent" width="425" height="350"></embed>
                    </object>';    
            $new_content = substr($the_content,0,$spos);
            $new_content .= $tags;
            $new_content .= substr($the_content,($epos+1));
 
            if ($epos+1 < strlen($the_content)) {//reciproco
                $new_content = mediaPostDesc($new_content);
            }
            return $new_content;
        }
        else return $the_content;
    }
    else return $the_content;
}

(more…)

Compress HTML before sending to the browser

0

Hany function ob_gzhandler that help facilitate sending gz-encoded data to web browsers that support compressed web pages.

This is the way I do it, checking the extension it’s loaded and that it’s possible to start the encoding:

if (extension_loaded('zlib')) {//check extension is loaded
    if(!ob_start("ob_gzhandler")) ob_start();//start HTML compression, if not normal buffer input mode
}

Detect file extension in PHP

0

Super easy trick to find a file extension:

$file="some_file.jpg";
$ext=end(explode(".", $file);

Other ways:

Substring:

$ext = substr($file, strrpos($file, '.') + 1);
//or:
$ext= substr(strrchr($file, "."), 1 );

Using path info:

$info = pathinfo($file);
$ext=$info['extenstion'];

Function to check if visitor is a bot

13

This function will check whether the visitor is a search engine robot

function is_bot(){
	$botlist = array("Teoma", "alexa", "froogle", "Gigabot", "inktomi",
	"looksmart", "URL_Spider_SQL", "Firefly", "NationalDirectory",
	"Ask Jeeves", "TECNOSEEK", "InfoSeek", "WebFindBot", "girafabot",
	"crawler", "www.galaxy.com", "Googlebot", "Scooter", "Slurp",
	"msnbot", "appie", "FAST", "WebBug", "Spade", "ZyBorg", "rabaz",
	"Baiduspider", "Feedfetcher-Google", "TechnoratiSnoop", "Rankivabot",
	"Mediapartners-Google", "Sogou web spider", "WebAlta Crawler","TweetmemeBot",
	"Butterfly","Twitturls","Me.dium","Twiceler");
 
	foreach($botlist as $bot){
		if(strpos($_SERVER['HTTP_USER_AGENT'],$bot)!==false)
		return true;	// Is a bot
	}
 
	return false;	// Not a bot
}

There’s any other better way?

Ping your sitemap.xml to Google

3

Not to long a go we explained how to generate a sitemap.xml with PHP.

Well, there was something missing and I think really important, to ping Google about the changes in the sitemap.

Simplest way of doing this:

file_get_contents('http://www.google.com/webmasters/sitemaps/ping?sitemap=http://yoursite.com/sitemap.xml');

Remember to register your site at Google webmaster tools, since if you don’t will not work.

Check requirements for PHP web application

2

Imagine that you need to have an installation form for your web app.

Of course you will need to ask many things, but before you ask, what about been sure the client match all the software requirements?

Check the PHP version:

$phpversion = substr(PHP_VERSION, 0, 6);
if($phpversion >= 5.2) {
       echo "Right PHP version"; 
}
else{
	echo "No, you can't continue with the installation";
	exit;
}

In this example we require 5.2 at least to continue.

Check extension loaded in PHP:

if (!extension_loaded('curl')){
    echo 'Not found, please proceed to install';
    exit;
}
else echo 'Found';

In this example we check that CURL it’s loaded.

Checking apache module installed:

if (in_array('mod_rewrite',apache_get_modules())) echo 'Found';
else echo 'Not found';

In this example we check that mod_rewrite it’s loaded.

Checking folder permissions:

 if(is_writable('/images')) { 
	echo 'OK - Writable'; 
} 
elseif(!file_exists('/images')) { 
	echo 'File Not Found';
} 
else {
	echo 'Unwritable (check permissions, chmod 755 should fix this)';
	exit;
}

Checking mysql connection:

if (!mysql_connect($_POST["DB_HOST"],$_POST["DB_USER"],$_POST["DB_PASS"])){
	$msg=mysql_error();
	echo 'Mysql error:' .$msg;
	exit;
}
else echo "connected!";

Read RSS in PHP with cache

1

Simple function to read RSS where you can set some values:

function rssReader($url,$maxItems=15,$begin="",$end=""){
        $rss = simplexml_load_file($url);
        $i=0;
        if($rss){
            $items = $rss->channel->item;
            foreach($items as $item){
                if($i==$maxItems) return $out;
                else $out.=$begin.'<a href="'.$item->link.'" target="_blank" >'.$item->title.'</a>'.$end;
                $i++;
            }
        }
        return $out;
    }

Usage example:

echo '<ul>'.rssReader('http://neo22s.com/feed/',5,'<li>','</li>').'</ul>';

Using cache with the class fileCache:

 function rssReader($url,$maxItems=15,$cache,$begin="",$end=""){
        $cache= (bool) $cache;
        if ($cache){
            $cacheRSS= new fileCache();//seconds and path
            $out = $cacheRSS->cache($url);//getting values from cache
        }else $out=false;
 
        if (!$out) {	//no values in cache
            $rss = simplexml_load_file($url);
            $i=0;
            if($rss){
                $items = $rss->channel->item;
                foreach($items as $item){
                    if($i==$maxItems){
                        if ($cache) $cacheRSS->cache($url,$out);//save cache	
                        return $out; 
                    }
                    else $out.=$begin.'<a href="'.$item->link.'" target="_blank" >'.$item->title.'</a>'.$end;
                    $i++;
                }
            }   		
        }
        return $out;
    }

Usage example RSS with cache:

echo '<ul>'.rssReader('http://neo22s.com/feed/',5,true,'<li>','</li>').'</ul>';

Based on this one from sihan: (more…)

Input select generated from query – PHP

2

Just a handy function that I use a lot.

With this function you can generate an input select from a given query.

Parameters:
1- Query to be displayed as a select, the query needs to returns at least 2 values, 1st one for the option value, and the 2nd one for the display value.
2-Input Select name, thisw woud be the name that your select will have in the form.
3-Which option it’s selected from the list. I non is set the first one it’s selected.

function sqlOption($sql,$name,$option){//generates a select tag with the values specified on the sql, 2nd parameter name for the combo, , 3rd value selected if there's
	global $ocdb;
	$result =$ocdb->query($sql);//1 value needs to be the ID, second the Name, if there's more doens't work
	$sqloption= "<select name='".$name."' id='".$name."'>
				<option value='0'>Home</option>";
	while ($row=mysql_fetch_assoc($result))
	{
		$first=mysql_field_name($result, 0);
		$second=mysql_field_name($result, 1);
 
			if ($option==$row[$first]) { $sel="selected=selected";}
			$sqloption=$sqloption .  "<option ".$sel." value='".$row[$first]."'>" .$row[$second]. "</option>";
			$sel="";
	}
		$sqloption=$sqloption . "</select>";
		echo $sqloption;
}

Same function but that can group:
(more…)

Go to Top