12 Useful PHP Snippets


1. Check domain creation date

simple one minute, you must have whois on your system

[php]
<?php
$domains = array(‘home.pl’, ‘w3c.org’);

function creation_date($domain) {
$lines = explode("\n", `whois $domain`);
foreach($lines as $line) {
if(strpos(strtolower($line), ‘created’) !== false) {
return $line;
}
}

return false;
}

foreach($domains as $d) {
echo creation_date($d) . "\n";
}
[/php]

source: http://snipplr.com/view.php?codeview&id=48040

2. IP Address of visitor’s connection

[php]
//Return the visitor’s IP address
function get_ip(){
if (isset($_SERVER["REMOTE_ADDR"]))
{
$ip=$_SERVER["REMOTE_ADDR"] . ‘ ‘;
} else if ( isset($_SERVER["HTTP_X_FORWARDED_FOR"]) ) {
$ip=$_SERVER["HTTP_X_FORWARDED_FOR"] . ‘ ‘;
} else if ( isset($_SERVER["HTTP_CLIENT_IP"]) ) {
$ip=$_SERVER["HTTP_CLIENT_IP"] . ‘ ‘;
}
return $ip;
}
[/php]

source : http://phpsnaps.com/snaps/view/ip-address-of-visitors-connection

3. PHP ffmpeg Upload Script

[php]
<?php
/*
Video Upload and thumbnail generator with ffmpeg. This code is written by John Anderson of Vermont Internet Design. For support please contact [email protected]. I provide support at the rate of $50 per hr.

http://www.vermontinternetdesign.com/index.php?topic=522.msg1499

*/

// size input prevents buffer overrun exploits.
function sizeinput($input, $len){
(int)$len;
(string)$input;
$n = substr($input, 0,$len);
$ret = trim($n);
$out = htmlentities($ret, ENT_QUOTES);
return $out;
}
//Check the file is of correct format. function checkfile($input){
$ext = array(‘mpg’, ‘wma’, ‘mov’, ‘flv’, ‘mp4′, ‘avi’, ‘qt’, ‘wmv’, ‘rm’);
$extfile = substr($input['name'],-4);
$extfile = explode(‘.’,$extfile);
$good = array();
$extfile = $extfile[1];
if(in_array($extfile, $ext)){
$good['safe'] = true;
$good['ext'] = $extfile;
}else{
$good['safe'] = false;
}
return $good;
}
$user_id = $_SESSION['table_id'];
// if the form was submitted process request if there is a file for uploading
if($_POST && array_key_exists("vid_file", $_FILES)){
//$uploaddir is for videos before conversion
$uploaddir = ‘uploads/videos/';
//$live_dir is for videos after converted to flv
$live_dir = ‘uploads/live/';
//$live_img is for the first frame thumbs.
$live_img = ‘uploads/images/';
$seed = rand(1,2009) * rand(1,10);
$upload = $seed. basename($_FILES['vid_file']['name']);
$uploadfile = $uploaddir .$upload;
$vid_title = sizeinput($_POST['vid_title'], 50);
$vid_desc = sizeinput($_POST['vid_description'], 200);
$vid_cat = (int)$_POST['vid_cat'];
$vid_usr_ip = $_SERVER['REMOTE_ADDR'];
$safe_file = checkfile($_FILES['vid_file']);
if($safe_file['safe'] == 1){
if (move_uploaded_file($_FILES['vid_file']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.<br/>";
$base = basename($uploadfile, $safe_file['ext']);
$new_file = $base.’flv';
$new_image = $base.’jpg';
$new_image_path = $live_img.$new_image;
$new_flv = $live_dir.$new_file;
//ececute ffmpeg generate flv
exec(‘ffmpeg -i ‘.$uploadfile.’ -f flv -s 320×240 ‘.$new_flv.”);
//execute ffmpeg and create thumb
exec(‘ffmpeg -i ‘.$uploadfile.’ -f mjpeg -vframes 1 -s 150×150 -an ‘.$new_image_path.”);
echo ‘Thank You For Your Video!<br>';
//create query to store video

$sql = ‘INSERT INTO videos (vid_cat_id, vid_user, vid_title, vid_desc, vid_file_name, image_file, vid_usr_ip) VALUES(\”.$vid_cat.’\’, \”.$user_id.’\’, \”.$vid_title.’\’, \”.$vid_desc.’\’, \”.$new_file.’\’, \”.$new_image.’\’, \”.$vid_usr_ip.’\’)';
$mysql = new mysqli(‘localhost’, ‘user’, ‘Pass&d’, ‘databasename’);
echo ‘<img src="’.$new_image_path.’" /><br/>
<h3>’.$vid_title.'</h3>';
mysqli_query($mysql, $sql) or die(mysqli_error($mysql));
} else {
echo "Possible file upload attack!\n";
print_r($_FILES);
}

}else{

echo ‘Invalid File Type Please Try Again. You file must be of type
.mpg, .wma, .mov, .flv, .mp4, .avi, .qt, .wmv, .rm';

}
}
?>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
<p align="left">Please upload Your video. Thumbnails of your videos are based on the first frame of your video. <br /><h3>Please allow up to a minute for your video to upload. </h3>
</p>
<table width="600" border="0" align="center" cellpadding="2" cellspacing="2">
<tr>
<td width="260" align="left" colspan="3"><div align="center">
<h3>Upload your Video ! </h3>
</div></td>
</tr>
<tr>
<td width="260" align="left"> </td>
<td width="326" align="left"> </td>
</tr>
<tr>
<td align="left">Title Of Video : </td>
<td align="left"><input name="vid_title" type="text" id="vid_title" /></td>
</tr>
<tr>
<td align="left">File: .mov, .avi, .wma , .mpeg : </td>
<td align="left"><input name="vid_file" type="file" id="vid_file" /></td>
</tr>
<tr>
<td align="left">Description:</td>
<td align="left"><textarea name="vid_description" id="vid_description"></textarea></td>
</tr>
<tr>
<td align="left">Category:</td>
<td align="left"><select name="vid_cat">
<option value="1" selected="selected">Video</option>
<option value="2">Cat1</option>
<option value="3">Cat2</option>
<option value="4">Cat3</option>
<option value="5">Cat4</option>
</select>
</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Upload Video" /></td>
</tr>
</table>

</form>
[/php]

source : http://phpsnaps.com/snaps/view/php-ffmpeg-upload-script/

4. PHP pagination class

PHP pagination class for displaying database results in pages

[php]
<?
class pagination
{
public function __construct()
{
}
public function calculate_pages($total_rows, $rows_per_page, $page_num)
{
$arr = array();
// calculate last page
$last_page = ceil($total_rows / $rows_per_page);
// make sure we are within limits
$page_num = (int) $page_num;
if ($page_num < 1)
{
$page_num = 1;
}
elseif ($page_num > $last_page)
{
$page_num = $last_page;
}
$upto = ($page_num – 1) * $rows_per_page;
$arr['limit'] = ‘LIMIT ‘.$upto.’,’ .$rows_per_page;
$arr['current'] = $page_num;
if ($page_num == 1)
$arr['previous'] = $page_num;
else
$arr['previous'] = $page_num – 1;
if ($page_num == $last_page)
$arr['next'] = $last_page;
else
$arr['next'] = $page_num + 1;
$arr['last'] = $last_page;
$arr['info'] = ‘Page (‘.$page_num.’ of ‘.$last_page.’)';
$arr['pages'] = $this->get_surrounding_pages($page_num, $last_page, $arr['next']);
return $arr;
}
function get_surrounding_pages($page_num, $last_page, $next)
{
$arr = array();
$show = 5; // how many boxes
// at first
if ($page_num == 1)
{
// case of 1 page only
if ($next == $page_num) return array(1);
for ($i = 0; $i < $show; $i++)
{
if ($i == $last_page) break;
array_push($arr, $i + 1);
}
return $arr;
}
// at last
if ($page_num == $last_page)
{
$start = $last_page – $show;
if ($start < 1) $start = 0;
for ($i = $start; $i < $last_page; $i++)
{
array_push($arr, $i + 1);
}
return $arr;
}
// at middle
$start = $page_num – $show;
if ($start < 1) $start = 0;
for ($i = $start; $i < $page_num; $i++)
{
array_push($arr, $i + 1);
}
for ($i = ($page_num + 1); $i < ($page_num + $show); $i++)
{
if ($i == ($last_page + 1)) break;
array_push($arr, $i);
}
return $arr;
}
}
?>
[/php]

source : http://phpsnaps.com/snaps/view/php-pagination-class

5. Clean URL

Cleans a URL string, for SEO friendly links

[php]
<?php

function cleanURL($string)
{
$url = str_replace("’", ”, $string);
$url = str_replace(‘%20′, ‘ ‘, $url);
$url = preg_replace(‘~[^\\pL0-9_]+~u’, ‘-‘, $url); // substitutes anything but letters, numbers and ‘_’ with separator
$url = trim($url, "-");
$url = iconv("utf-8", "us-ascii//TRANSLIT", $url); // you may opt for your own custom character map for encoding.
$url = strtolower($url);
$url = preg_replace(‘~[^-a-z0-9_]+~’, ”, $url); // keep only letters, numbers, ‘_’ and separator
return $url;
}

// echo cleanURL("Shelly’s%20Greatest%20Poem%20(2008)"); // shellys-greatest-poem-2008

?>
[/php]

source : phpsnaps.com/snaps/view/clean-url

6. generate a preview image from an FLV file on-the-fly, or to save

generate a preview image from an FLV

[php]
<?php

// references http://www.longtailvideo.com/support/forum/Modules/12661/External-PHP-with-FFmpeg-using-readfile-

// generate a preview image from an FLV file on-the-fly, or to save

// call with: ffmpeg_image.php?file=video.flv&time=00:00:05&browser=true

// call with: ffmpeg_image.php?file=video.flv&percent=75.3&browser=true

// no time defaults to "00:00:01" (one second), no browser defaults to "true"

$videofile = (isset($_GET['file'])) ? strval($_GET['file']) : ‘video.flv';

$image = substr($videofile, 0, strlen($videofile) – 4);

$time = (isset($_GET['time'])) ? strval($_GET['time']) : ’00:00:01′;

// debug (" File: ", $videofile);

// debug (" Image: ", $image);

// debug (" Time: ", $time);

// check time format

if (!preg_match(‘/\d\d:\d\d:\d\d/’, $time))

{

$time = "00:00:00";

}

if (isset($_GET['percent']))

{

$percent = $_GET['percent'];

// debug (" Percent: ", $percent);

ob_start();

exec("/usr/bin/ffmpeg -i \"". $videofile . "\" 2>&1");

$duration = ob_get_contents();

ob_end_clean();

// debug ("Duration: ", $duration);

preg_match(‘/Duration: (.*?),/’, $duration, $matches);

$duration = $matches[1];

// debug ("Duration: ", $duration);

$duration_array = split(‘:’, $duration);

$duration = $duration_array[0] * 3600 + $duration_array[1] * 60 + $duration_array[2];

$time = $duration * $percent / 100;

// debug (" Time: ", $time);

$time = intval($time/3600) . ":" . intval(($time-(intval($time/3600)*3600))/60) . ":" . sprintf("%01.3f", ($time-(intval($time/60)*60)));

// debug (" Time: ", $time);

}

$browser = (isset($_GET['browser'])) ? strval($_GET['browser']) : ‘true';

// debug (" Browser: ", $browser);

if ($browser == "true")

{

header(‘Content-Type: image/png’);

exec("/usr/bin/ffmpeg -vcodec png -i \"" . $videofile . "\" -ss " . $time . " -vframes 1 -f image2 -");

//header(‘Content-Type: image/jpeg’);

//exec("/usr/bin/ffmpeg -vcodec mjpeg -i \"" . $videofile . "\" -ss " . $time . " -vframes 1 -f image2 -");

}

else
{

exec("/usr/bin/ffmpeg -vcodec png -i \"" . $videofile . "\" -ss " . $time . " -vframes 1 -f image2 \"" . $image . "\"%d.png");

//exec("/usr/bin/ffmpeg -vcodec mjpeg -i \"" . $videofile . "\" -ss " . $time . " -vframes 1 -f image2 \"" . $image . "\"%d.jpg");

}
?>
[/php]

source : http://phpsnaps.com/snaps/view/generate-a-preview-image-from-an-flv-file-on-the-fly-or-to-save

7. Cross domain file check

[php]
$imgfile="http://www.crossdomain.com/image.jpg";
try
{
$k=@file_get_contents($imgfile);

} catch (Exception $e) {
$k=false;
}

if($k!=false)
{
$result .= "<img src=’$imgfile’>";

}
else
{
$result.="no image file";
}
[/php]

source : http://snipplr.com/view/29872/

8. MySQL Dump

Creates a backup of a MySQL database in SQL format.

[php]
if (!function_exists(‘mysql_dump’)) {

function mysql_dump($database) {

$query = ”;

$tables = @mysql_list_tables($database);
while ($row = @mysql_fetch_row($tables)) { $table_list[] = $row[0]; }

for ($i = 0; $i < @count($table_list); $i++) {

$results = mysql_query(‘DESCRIBE ‘ . $database . ‘.’ . $table_list[$i]);

$query .= ‘DROP TABLE IF EXISTS `’ . $database . ‘.’ . $table_list[$i] . ‘`;’ . lnbr;
$query .= lnbr . ‘CREATE TABLE `’ . $database . ‘.’ . $table_list[$i] . ‘` (‘ . lnbr;

$tmp = ”;

while ($row = @mysql_fetch_assoc($results)) {

$query .= ‘`’ . $row['Field'] . ‘` ‘ . $row['Type'];

if ($row['Null'] != ‘YES’) { $query .= ‘ NOT NULL'; }
if ($row['Default'] != ”) { $query .= ‘ DEFAULT \” . $row['Default'] . ‘\”; }
if ($row['Extra']) { $query .= ‘ ‘ . strtoupper($row['Extra']); }
if ($row['Key'] == ‘PRI’) { $tmp = ‘primary key(‘ . $row['Field'] . ‘)'; }

$query .= ‘,’. lnbr;

}

$query .= $tmp . lnbr . ‘);’ . str_repeat(lnbr, 2);

$results = mysql_query(‘SELECT * FROM ‘ . $database . ‘.’ . $table_list[$i]);

while ($row = @mysql_fetch_assoc($results)) {

$query .= ‘INSERT INTO `’ . $database . ‘.’ . $table_list[$i] .’` (‘;

$data = Array();

while (list($key, $value) = @each($row)) { $data['keys'][] = $key; $data['values'][] = addslashes($value); }

$query .= join($data['keys'], ‘, ‘) . ‘)’ . lnbr . ‘VALUES (\” . join($data['values'], ‘\’, \”) . ‘\’);’ . lnbr;

}

$query .= str_repeat(lnbr, 2);

}

return $query;

}

}
[/php]

source : http://snipplr.com/view/173/mysql-dump/

9. Nice URLS PHP .htaccess

[php]
.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ $1.php [L,QSA]
# http://domain/about -> http://domain/about.php

————————————————–

.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
# http://domain/about -> http://domain/index.php?q=about

<?php
// $url_data is an array
$url_data = explode("/",$HTTP_SERVER_VARS['PATH_INFO']);
?>
[/php]

source : http://snipplr.com/view.php?codeview&id=4562

10. Underscore Strings

[php]
<?php
function string_to_underscore_name($string) {
$string = preg_replace(‘/[\'"]/’, ”, $string);
$string = preg_replace(‘/[^a-zA-Z0-9]+/’, ‘_’, $string);
$string = strtolower(trim($string, ‘_’));
return $string;
}
echo string_to_underscore_name("13: inside movie films“`””—\//\Bye!?");
//Output: 13_inside_movie_films_bye
?>
[/php]

source : http://snipplr.com/view.php?codeview&id=4848

11. Anti-SQL Injection Function

[php]
function cleanuserinput($dirty){
if (get_magic_quotes_gpc()) {
$clean = mysql_real_escape_string(stripslashes($dirty));
}else{
$clean = mysql_real_escape_string($dirty);
}
return $clean;
}

[/php]

source : http://snipplr.com/view.php?codeview&id=2742

12. PHP Functions to Clean User Input

[php]
<?php
function cleanInput($input) {

$search = array(
‘@<script[^>]*?>.*?</script>@si’, // Strip out javascript
‘@<[\/\!]*?[^<>]*?>@si’, // Strip out HTML tags
‘@<style[^>]*?>.*?</style>@siU’, // Strip style tags properly
‘@<![\s\S]*?–[ \t\n\r]*>@’ // Strip multi-line comments
);

$output = preg_replace($search, ”, $input);
return $output;
}
?>
<?php
function sanitize($input) {
if (is_array($input)) {
foreach($input as $var=>$val) {
$output[$var] = sanitize($val);
}
}
else {
if (get_magic_quotes_gpc()) {
$input = stripslashes($input);
}
$input = cleanInput($input);
$output = mysql_real_escape_string($input);
}
return $output;
}
?>
[/php]

source : http://snipplr.com/view.php?codeview&id=50799