10 Useful Code Snippets For PHP Developers
1. Validate E-Mail
function is_valid_email($email)
{
if(eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$",$email))
return true;
else
return false;
}
2. Validate domain name
function is_valid_url($url)
{
if (preg_match('/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/i', $url)) {
echo "Your url is ok.";
else
echo "Wrong url.";
}
3. Truncate String
This function takes a long string and shortens it to a defined length and adds appends an ellipsis (or custom string) to the end. Instead of chopping a word in half (if the limit finished within it), it moves the pointer up to the previous space.
function truncate($text, $limit = 25, $ending = '...')
{
$text = strip_tags($text);
if (strlen($text) > $limit) {
$text = substr($text, 0, $limit);
$text = substr($text, 0, -(strlen(strrchr($text, ' '))));
$text = $text . $ending;
}
return $text;
}
4.Get Real IP Address
function getRealIPAddr()
{
if (!empty($_SERVER['HTTP_CLIENT_IP'])){
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else{
$ip=$_SERVER['REMOTE_ADDR'];
}
return $ip;
}
5. SEO and URL Friendly String
This function takes a string and makes it SEO and URL friendly.
function seo($string){
$string = preg_replace("`\[.*\]`U","",$string);
$string = preg_replace('`&(amp;)?#?[a-z0-9]+;`i','-',$string);
$string = preg_replace( "`&([a-z])(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo);`i","\\1", $string );
$string = preg_replace( array("`[^a-z0-9]`i","`[-]+`") , "-", $string);
$string = htmlentities($string, ENT_COMPAT, 'utf-8');return strtolower(trim($string, '-'));
}
6. Send Simple Mail
function send_simple_mail($from,$to,$subject,$body)
{
$headers = "From: $from\r\n";
$headers .= "Reply-To: $from\r\n";
headers .= "Return-Path: $from\r\n";
$headers .= "X-Mailer: PHP5\n";
$headers .= 'MIME-Version: 1.0' . "\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
@mail($to,$subject,$body,$headers);
}
7.Directory Listing
function list_files($dir)
{
if(is_dir($dir)){
if($handle = opendir($dir)){
while(($file = readdir($handle)) !== false){
if($file != "." && $file != ".." && $file != "Thumbs.db"{
echo '<a target="_blank" href="'.$dir.$file.'">'.$file.'</a><br/>'."\n";
}
}
closedir($handle);
}
}
}
8. Generate a Random String
This snippet creates and returns a random string. It can be used for random string creation.
function get_random_string(){
$string = "abcdefghijklmnopqrstuvwxyz0123456789";
for($i=0;$i<25;$i++){
$pos = rand(0,36);
$str .= $string[$pos];
}
return $str
}
9. Send Files Via FTP
$connection = ftp_connect($server);
$login = ftp_login($connection, $ftp_user_name, $ftp_user_pass);
if (!$connection || !$login) { die('Connection attempt failed!'); }
$upload = ftp_put($connection, $dest, $source, $mode);
if (!$upload) { echo 'FTP upload failed!'; }
ftp_close($connection);
10. Find title Tag and Get Value
This code snippet will find and print the text within the title tag of a html page.
function get_title_value(){
$fp = fopen("http://www.example.com","r");
while (!feof($fp) ){
$page .= fgets($fp, 4096);
}
$titre = eregi("<title>(.*)</title>",$page,$regs);
echo $regs[1];
fclose($fp);
}
Category PHP, Last Modified: 08 Ekim 2009 Author: emincan | Giriş









Tip 8: I think you would benefit from using “rand(0, strlen($string));” instead of using “rand(0, 36)”.
Great tips! Thank you!
There is no need for truncate function (Point 3), PHP has got substr_replace.
substr_replace($text,'...',25);
I think we need for truncate function. Because substr_replace chops a word in half and becomes a problem with non-english characters.
e.g:
echo substr_replace('şçşçşçşçiğiğşğşğ','...',3);[...] can see more snippets at this site and search for some more snippets of code [...]
10 Useful Code Snippets For PHP Developers | Listelog…
Useful code snippets for PHP….
Hi man! use filter_var is very powerfull and fast that regex…
10 Useful Code Snippets For PHP Developers…
10 Useful Code Snippets For PHP Developers: Validate E-Mail, Validate domain name, Truncate String, Get Real IP Address, SEO and URL Friendly String, Send Simple Mail, Directory Listing, Generate a Random String, Send Files Via FTP, Find title Tag and …