PDA

توجه ! این یک نسخه آرشیو شده میباشد و در این حالت شما عکسی را مشاهده نمیکنید برای مشاهده کامل متن و عکسها بر روی لینک مقابل کلیک کنید : مجموعه کدهای بدرد بخور در php



djmohammad
December 17th, 2013, 00:58
با سلام خوب در این تاپیک می خوام مجموعه ای از کدهای بدرد بخور جدید رو برای شما قرار بدم

امیدوارم مفید باشه


تشکر هم یادتون نره :)

djmohammad
December 17th, 2013, 01:00
دریافت پسوند فایل



function get_extension($filename)
{
$myext = substr($filename, strrpos($filename, '.'));
return str_replace('.','',$myext);
}


طریقه استفاده از کد بالا




$filename = 'this_myfile.cd.doc';
echo get_extension($filename)

djmohammad
December 17th, 2013, 01:01
حذف پسوند فایل



function RemoveExtension($strName)
{
$ext = strrchr($strName, '.');
if($ext !== false)
{
$strName = substr($strName, 0, -strlen($ext));
}
return $strName;
}


طریقه استفاده از کد :




echo RemoveExtension('myfile.ho');

djmohammad
December 17th, 2013, 01:02
بدست آوردن اندازه فایل



function format_size($size) {
$sizes = array(" Bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
if ($size == 0) { return('n/a'); } else {
return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]); }
}


طریقه استفاده از کد بالا :



$thefile = filesize('test_file.mp3')
echo format_size($thefile);

djmohammad
December 17th, 2013, 01:04
حذف کاراکترهای غیر ASCII را از رشته




function clean_none_ascii($output) {
$output = preg_replace('/[^(x20-x7F)]*/','', $output);
return $output;
}


طریقه استفاده از کد بالا :




$output = "Clean this copy of invalid non ASCII äócharacters.";echo clean_non_ascii($output);

djmohammad
December 17th, 2013, 01:06
تجزیه رشته




function string_parser($string,$replacer)
{
$result = str_replace(array_keys($replacer), array_values($replacer),$string);
return $result;
}


طریقه استفاده :




$string = 'The {b}anchor text{/b} is the {b}actual word{/b} or words used {br}to describe the link {br}itself';
$replace_array = array('{b}' => '<b>','{/b}' => '</b>','{br}' => '');

echo string_parser($string,$replace_array);

djmohammad
December 17th, 2013, 01:08
ارسال ایمیل با بدنه html





function php_html_email($email_args) {
$headers = 'MIME-Version: 1.0' . "rn";
$headers .= 'Content-type: text/html; charset=UTF-8' . "rn";
$headers .= 'To:'.$email_args['to'] . "rn";
$headers .= 'From:'.$email_args['from'] . "rn";
if(!empty($email_args['cc'])){$headers .= 'Cc:'.$email_args['cc'] . "rn";}
$message_body = '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
$message_body .= '<title>'.$email_args["subject"].'</title>';
$message_body .= '</head><body>';
$message_body .= $email_args["message"];
$message_body .= '</body></html>';
if(@mail($email_args['to'], $email_args['subject'], $message_body, $headers))
{
return true;
}else{
return false;
}
}


طریقه استفاده :




$email_args = array('from'=>'my_email@testserver.com <mr. Sender>','to' =>'test_recipient@testgmail.com <camila>, test_recipient2@testgmail.com <anderson>','cc' =>'test_cc123_recipient@testgmail.com <christopher>, test_cc321_recipient2@testgmail.com <francisca>','subject' =>'This is my Subject Line','message' =>'<b style="color:red;">This</b> is my <b>HTML</b> message. This message will be sent using <b style="color:green;">PHP mail</b>.',); if(php_html_email($email_args)){echo 'Mail Sent';}

djmohammad
December 17th, 2013, 01:10
فهرست فایلها در یک دایرکتوری





function listDirFiles($DirPath)
{
if($dir = opendir($DirPath)){
while(($file = readdir($dir))!== false){
if(!is_dir($DirPath.$file))
{
echo "filename: $file";
}
}
}
}




طریقه استفاده :




listDirFiles('home/some_folder/');

djmohammad
December 17th, 2013, 01:12
قرار دادن گراواتار شخصی در سایت خود



function gravatar($email, $rating = false, $size = false, $default = false) {
$out = "http://www.gravatar.com/avatar.php?gravatar_id=".md5($email);
if($rating && $rating != '')
$out .= "&amp;rating=".$rating;
if($size && $size != '')
$out .="&amp;size=".$size;
if($default && $default != '')
$out .= "&amp;default=".urlencode($default);
echo $out;
}




طریقه استفاده :




<!--
email - Email address in gravatar
rating - rating of Gravatar(G, PG, R, X)
size - size of gravatar
default - URL of default gravatar to use or use various options : http://j.mp/SUmEq9
-->
<img src="<?php gravatar('emailaddress@sgmail.com','G',32,'monster id'); ?>" />

djmohammad
December 17th, 2013, 01:15
اتوماتیک لینک کردن تمام آدرس ها و ایمیل ها





function autolink($message) {
//Convert all urls to links
$message = preg_replace('#([s|^])(www)#i', '$1http://$2', $message);
$pattern = '#((http|https|ftp|telnet|news|gopher|file|wais)://[^s]+)#i';
$replacement = '<a href="$1" target="_blank">$1</a>';
$message = preg_replace($pattern, $replacement, $message);

/* Convert all E-mail matches to appropriate HTML links */
$pattern = '#([0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*.';
$pattern .= '[a-wyz][a-z](fo|g|l|m|mes|o|op|pa|ro|seum|t|u|v|z)?)#i';
$replacement = '<a href="mailto:1">1</a>';
$message = preg_replace($pattern, $replacement, $message);
return $message;
}



طریقه استفاده :




$my_string = strip_tags('this http://www.cdcv.com/php_tutorial/strip_tags.php make clickable text and this email bobby23432@fakserver.com');
echo autolink($my_string);

djmohammad
December 17th, 2013, 01:21
گرفتن آدرس خروجی از صفحه فعلی




function curPageURL() {
$pageURL = 'http';
if (!empty($_SERVER['HTTPS'])) {$pageURL .= "s";}
$pageURL .= "://";
if ($_SERVER["SERVER_PORT"] != "80") {
$pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} else {
$pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
return $pageURL;
}



طریقه استفاده از کد بالا :





echo curPageURL();

djmohammad
December 18th, 2013, 14:20
کوتاه کردن متن های طولانی




function truncate($text, $length = 0)
{
if ($length > 0 && strlen($text) > $length) // Truncate the item text if it is too long.
{
$tmp = substr($text, 0, $length); // Find the first space within the allowed length.
$tmp = substr($tmp, 0, strrpos($tmp, ' '));
if (strlen($tmp) >= $length - 3) { // If we don't have 3 characters of room, go to the second space within the limit.
$tmp = substr($tmp, 0, strrpos($tmp, ' '));
}
$text = $tmp.'...';
}
return $text;
}


طریقه استفاده :




$string = 'The behavior will not truncate an individual word, it will find the first space that is within the limit and truncate.';
echo truncate($string,60);

djmohammad
December 19th, 2013, 04:02
خلاصه کردن یک رشته



مثال :
“Really long title” to “Really…title”.





function abridge($text, $length = 50, $intro = 30)
{
// Abridge the item text if it is too long.
if (strlen($text) > $length)
{
// Determine the remaining text length.
$remainder = $length - ($intro + 3);

// Extract the beginning and ending text sections.
$beg = substr($text, 0, $intro);
$end = substr($text, strlen($text) - $remainder);

// Build the resulting string.
$text = $beg . '...' . $end;
}
return $text;
}


طریقه استفاده :




$string = 'The behavior will not truncate an individual word, it will find the first space that is within the limit and truncate.';
echo abridge($string,60);

djmohammad
December 19th, 2013, 04:04
دریافت اطلاعات از یک آدرس (Get JSON data from a URL (cURL





function get_my_json_data($json_url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $json_url);
curl_close($ch);
return json_decode($json_data);
}



طریقه استفاده :





$the_data = get_my_json_data('http://graph.facebook.com/btaylor');
echo '<pre>';
print_r($the_data);
echo '</pre>';
echo $the_data->name;



اگر شما مشکلی در رابطه با روش CURL روبرو هستید، شما می تونید از روش های جایگزین با استفاده از file_get_contents پی اچ پی استفاده کنید.




function get_json_data($json_url)
{
$json_data = file_get_contents($json_url);
return json_decode($json_data);
}

djmohammad
December 19th, 2013, 04:05
تغییر اندازه گروهی عکس ها در یک پوشه




<?php
//Maximize script execution time
ini_set('max_execution_time', 0);

//Initial settings, Just specify Source and Destination Image folder.
$ImagesDirectory = '/home/public_html/websites/images/'; //Source Image Directory End with Slash
$DestImagesDirectory = '/home/public_html/websites/images/new/'; //Destination Image Directory End with Slash
$NewImageWidth = 500; //New Width of Image
$NewImageHeight = 500; // New Height of Image
$Quality = 80; //Image Quality

//Open Source Image directory, loop through each Image and resize it.
if($dir = opendir($ImagesDirectory)){
while(($file = readdir($dir))!== false){

$imagePath = $ImagesDirectory.$file;
$destPath = $DestImagesDirectory.$file;
$checkValidImage = @getimagesize($imagePath);

if(file_exists($imagePath) && $checkValidImage) //Continue only if 2 given parameters are true
{
//Image looks valid, resize.
if(resizeImage($imagePath,$destPath,$NewImageWidth ,$NewImageHeight,$Quality))
{
echo $file.' resize Success!';
/*
Now Image is resized, may be save information in database?
*/

}else{
echo $file.' resize Failed!';
}
}
}
closedir($dir);
}

//Function that resizes image.
function resizeImage($SrcImage,$DestImage, $MaxWidth,$MaxHeight,$Quality)
{
list($iWidth,$iHeight,$type) = getimagesize($SrcImage);
$ImageScale = min($MaxWidth/$iWidth, $MaxHeight/$iHeight);
$NewWidth = ceil($ImageScale*$iWidth);
$NewHeight = ceil($ImageScale*$iHeight);
$NewCanves = imagecreatetruecolor($NewWidth, $NewHeight);

switch(strtolower(image_type_to_mime_type($type)))
{
case 'image/jpeg':
case 'image/png':
case 'image/gif':
$NewImage = imagecreatefromjpeg($SrcImage);
break;
default:
return false;
}

// Resize Image
if(imagecopyresampled($NewCanves, $NewImage,0, 0, 0, 0, $NewWidth, $NewHeight, $iWidth, $iHeight))
{
// copy file
if(imagejpeg($NewCanves,$DestImage,$Quality))
{
imagedestroy($NewCanves);
return true;
}
}
}

?>

djmohammad
December 19th, 2013, 04:06
فعال کردن نمایش خطا در php







ini_set('display_errors', 1);
error_reporting(E_ALL);

djmohammad
December 19th, 2013, 04:07
بررسی کد های مخرب و تروجان در وب سایت و ایمیل کردن کردن اطلاعات





// Point to script that scans your site
$ScanResult = file_get_contents("http://www.YOURSITE.com/secret-folder/lookforbadguys.php",0);
if($ScanResult)
{
$to = 'youremail@yoursite.com'; // your email address
$headers = 'MIME-Version: 1.0' . "rn";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "rn";

// Mail result
mail($to, 'Malicious code scan result', $ScanResult, $headers);
}

djmohammad
December 19th, 2013, 04:08
تشخیص حجم فایل یک لینک
مثلا حجم یک فایل زیپ یک لینک دانلود رو که از سایت دیگه است رو مشخص میکنه




<?php
$remoteFile = 'http://download.thinkbroadband.com/5MB.zip';
$ch = curl_init($remoteFile);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$data = curl_exec($ch);
curl_close($ch);
if ($data === false) {
echo 'cURL failed';
exit;
}

$contentLength = 'unknown';
$status = 'unknown';
if (preg_match('/^HTTP\/1\.[01] (\d\d\d)/', $data, $matches)) {
$status = (int)$matches[1];
}
if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
$contentLength = (float)$matches[1];
}


//echo 'HTTP Status: ' . $status . "\n";
//echo 'Content-Length: ' . $contentLength;




function format_bytes($contentLength) {
$units = array(' B', ' KB', ' MB', ' GB', ' TB');
for ($i = 0; $contentLength >= 1024 && $i < 4; $i++) $contentLength /= 1024;
return round($contentLength, 2).$units[$i];
}

echo format_bytes($contentLength);


?>

djmohammad
December 19th, 2013, 04:10
حذف اولین کاراکتر از رشته:





echo substr("12345678", 1); // 2345678

djmohammad
December 19th, 2013, 04:11
محاسبه تعداد فایل در دایرکتوری:




$dir_path = "media/"; $wcount = count(glob("" .$dir_path. "*.jpg"));

djmohammad
December 19th, 2013, 04:13
فشرده سازی خودکار فایلهای CSS با PHP





<?php
ob_start('compress');
header('Content-Type: text/css');
function compress($buffer) {
/* remove comments */
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
/* remove tabs and newlines, etc. */
$buffer = str_replace(array("\r\n", "\r", "\n", "\t"), '', $buffer);
/* remove unnecessary whitspaces */
$buffer = preg_replace('#[\s]{2,}#', ' ', $buffer);
return $buffer;
}

/* your css files */
if(isset($_GET['css']) && file_exists($_GET['css'])) {
require_once $_GET['css'];
}

ob_end_flush();
?>



مثالی از نحوه استفاده :




<link href="csscompress.php?css=style.css" rel="stylesheet" type="text/css"/>

djmohammad
December 19th, 2013, 04:14
تولید خودکار لینک کوتاه برای URLهای شما






function getTinyUrl($url) {
return file_get_contents('http://tinyurl.com/api-create.php?url=' . $url);
}

djmohammad
December 19th, 2013, 04:15
بدست آوردن اندازه فایلها با واحد B و KB و MB و... بطور خودکار :





<?php
function FormatSize($url, $remote = false, $precision = 2) {
$bytes = 0;
if(!$remote) {
if(file_exists($url)) {
$bytes = filesize($url);
}
}
else {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Not necessary unless the file redirects
$data = curl_exec($ch);
curl_close($ch);
if ($data === false) {
return -1;
}
if (preg_match('#Content-Length: (\d+)#i', $data, $matches)) {
$bytes = trim($matches[1]);
}
}
settype($bytes, 'double');
$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
$len = count($units);
for ($i = 0; $bytes >= 1024 && $i < $len; $i++) {
$bytes /= 1024;
}
return round($bytes, $precision) . $units[$i];
}
/* Usage Samples:
echo '<p>' . FormatSize('images/logo.png') . '</p>' . PHP_EOL;
echo '<p>' . FormatSize('http://www.google.com/images/srpr/logo4w.png', true) . '</p>' . PHP_EOL;
*/
?>



این اسکریپت حتی سایز فایل سایتهای دیگه و حتی لینک فایلهای RapidShare و... رو هم میتونه استخراج کنه.

djmohammad
December 19th, 2013, 04:16
درج Overlay و Watermark بر روی تصاویر:




header('Content-type: image/png');

## Red :: 0 - 255
## Green :: 0 - 255
## Blue :: 0 - 255
## Alpha :: 0 - 127

$data = array(
'file_1' => 'image_1.jpg',
'file_2' => 'image_2.png',
'position_x' => 80,
'position_y' => 90,
'watermark' => 'MostafaEs'
);

$font = array(
'family' => 'fonts/agencyb.ttf',
'rotate' => 0,
'size' => 17,
);

// Image Size
list($width_1, $height_1) = getimagesize($data['file_1']);
list($width_2, $height_2) = getimagesize($data['file_2']);

// Image Create
$image_1 = imagecreatefromjpeg($data['file_1']);
$image_2 = imagecreatefrompng($data['file_2']);

// Frame Create
$photoFrame_1 = imagecreatetruecolor($width_1, $height_1);
$photoFrame_2 = imagecreatetruecolor($width_2, $height_2);

// Frame (1)
imagecopyresampled($photoFrame_1, $image_1, 0, 0, 0, 0, $width_1, $height_1, imagesx($image_1), imagesy($image_1));

// Frame (2)
$transparent = imagecolorallocatealpha($photoFrame_2, 0, 0, 0, 127);
imagefill($photoFrame_2, 0, 0, $transparent);
imagecopyresampled($photoFrame_2, $image_2, 0, 0, 0, 0, $width_2, $height_2, imagesx($image_2), imagesy($image_2));

// Copy Frame
imagecopy($photoFrame_1, $photoFrame_2, $data['position_x'], $data['position_y'], 0, 0, imagesx($photoFrame_2), imagesy($photoFrame_2));

// Image Watermark
$box = imagettfbbox($font['size'], $font['rotate'], $font['family'], $data['watermark']);

$colors = array(
'black' => imagecolorallocatealpha($photoFrame_1, 0, 0, 0, 0),
'white' => imagecolorallocatealpha($photoFrame_1, 255, 255, 255, 0),
'red' => imagecolorallocatealpha($photoFrame_1, 255, 0, 0, 75),
'green' => imagecolorallocatealpha($photoFrame_1, 0, 255, 0, 75),
'blue' => imagecolorallocatealpha($photoFrame_1, 0, 0, 255, 75),

'custom-1' => imagecolorallocatealpha($photoFrame_1, 209, 163, 104, 5)
);

$width = imagesx($photoFrame_1);
$height = imagesy($photoFrame_1);

$margin_top = $height-35;
$margin_right = $height-3;
$margin_left = $width-3;
$margin_bottom = 3;

imagefilledrectangle($photoFrame_1, $margin_left, $margin_right, $margin_bottom, $margin_top, $colors['custom-1']);
imagettftext($photoFrame_1, $font['size'], $font['rotate'], ($width-$box[4])/2, ($height-10), $colors['black'], $font['family'], $data['watermark']);

imagepng($photoFrame_1);

imagedestroy($image_1);
imagedestroy($image_2);
imagedestroy($photoFrame_1);
imagedestroy($photoFrame_2);



آرایه data رو میبایست دستی ویرایش کنید! دراینجا تصویر اول JPG و تصویر دوم PNG هستش که میتونید بنابه نیازتون توابع رو تغییر بدید!
دراصل کار اصلی این کد درج تصویر دوم بصورت Transparent بر روی تصویر اول هست!

djmohammad
December 19th, 2013, 04:18
تابعی مفید برای اینکد کردن url ها.
وقتی مفیده که بخواین مثلا از rss که لینک هاش حاوی کلمات فارسی هست، url صفحه ای رو گرفته سپس اون صفحه رو با cUrl بخواین باز کنید.




function safe_urlencode($txt){
// Skip all URL reserved characters plus dot, dash, underscore and tilde..
$result = preg_replace_callback("/[^-\._~:\/\?#\\[\\]@!\$&'\(\)\*\+,;=]+/",
function ($match) {
// ..and encode the rest!
return rawurlencode($match[0]);
}, $txt);
return ($result);
}

djmohammad
December 19th, 2013, 04:19
با استفاده از این تکه کد می تونید تاریخ و ساعت رو به شکل های ۲ دقیقه پیش ، ۱ ساعت و ۱۰ دقیقه پیش نمایش بدید




public function Timeago($time,$format='Y/m/d H:i:s'){
$now=time();

if(is_string($time) && strlen(intval($time))!=10){
$time=strtotime($time);
}
$ago='پیش';
if($now<$time){
$diff=$time-$now;
$ago='بعد';
}else $diff=$now-$time;

if($diff<30) $output='همین حالا';
else if($diff>=30 && $diff<60) $output=$diff.' ثانیه '.$ago;
else if($diff>=60 && $diff<120) $output='کمتر از '.($diff/60).' دقیقه'.$ago;
else if($diff>=120 && $diff<3600){
$min=intval($diff/60);
$sec=intval($diff-($min*60));
$output=$min.' دقیقه'.($sec!=0?' و '.$sec.' ثانیه ':' ').$ago;
}else if($diff>=3600 && $diff<(24*3600)){
$h=intval($diff/3600);
$min=intval(($diff-($h*3600)) / 60);
$output=$h.' ساعت'.($min!=0?' و '.$min.' دقیقه ':' ').$ago;
}else if($diff>=(24*3600) && $diff<(2*24*3600)){
if($ago=='پیش') $output='دیروز';
else $output='فردا';
$output.=' ساعت '.date('H:i:s',$time);
}else $output=date($format,$time);

return $output;
}



طرز استفاده هم به این صورت هست شما زمان رو به عنوان پارامتر می فرستید و تابع خروجی مناسب رو برمی گردونه
مثال
ورودی -> 1378461081 ====> خروجی -> دیروز ساعت 14:21:21
ورودی -> strtotime('-5 mins') ====> خروجی -> ۵ دقیقه پیش
ورودی -> strtotime('+5 mins') ====> خروجی -> ۵ دقیقه بعد

djmohammad
December 19th, 2013, 04:20
با استفاده از کد زیر میتوانیم هر فایلی را تا تعداد999 تکه splitکنیم. در ضمن این کد قابلیت rejoinفایل های split شده را دارد.





<pre class="brush: php;" style="direction:ltr;">$filename = "http://www.iyinet.com/my-big-file.zip";

$targetfolder = '/tmp';

$piecesize = 10; // splitted file size in MB

$buffer = 1024;
$piece = 1048576*$piecesize;
$current = 0;
$splitnum = 1;

if(!file_exists($targetfolder)) {
if(mkdir($targetfolder)) {
echo "Created target folder $targetfolder".br();
}
}

if(!$handle = fopen($filename, "rb")) {
die("Unable to open $filename for read! Make sure you edited filesplit.php correctly!".br());
}

$base_filename = basename($filename);

$piece_name = $targetfolder.'/'.$base_filename.'.'.str_pad($splitnum, 3, "0", STR_PAD_LEFT);
if(!$fw = fopen($piece_name,"w")) {
die("Unable to open $piece_name for write. Make sure target folder is writeable.".br());
}
echo "Splitting $base_filename into $piecesize Mb files ".br()."(last piece may be smaller in size)".br();
echo "Writing $piece_name...".br();
while (!feof($handle) and $splitnum < 999) {
if($current < $piece) {
if($content = fread($handle, $buffer)) {
if(fwrite($fw, $content)) {
$current += $buffer;
} else {
die("filesplit.php is unable to write to target folder. Target folder may not have write permission! Try chmod +w target_folder".br());
}
}
} else {
fclose($fw);
$current = 0;
$splitnum++;
$piece_name = $targetfolder.'/'.$base_filename.'.'.str_pad($splitnum, 3, "0", STR_PAD_LEFT);
echo "Writing $piece_name...".br();
$fw = fopen($piece_name,"w");
}
}
fclose($fw);
fclose($handle);
echo "Done! ".br();
exit;

function br(){
return (!empty($_SERVER['SERVER_SOFTWARE']))?'':"\n";
}

djmohammad
December 19th, 2013, 04:21
با استفاده از این کد می تونید خروجی اکسل بگیرید :





function xlsBOF() {
echo pack("ssssss", 0x809, 0x8, 0x0, 0x10, 0x0, 0x0);
return;
}
//*********************************************
function xlsEOF() {
echo pack("ss", 0x0A, 0x00);
return;
}
//*********************************************
function xlsWriteNumber($Row, $Col, $Value) {
echo pack("sssss", 0x203, 14, $Row, $Col, 0x0);
echo pack("d", $Value);
return;
}
//*********************************************
function xlsWriteLabel($Row, $Col, $Value ) {
$L = strlen($Value);
echo pack("ssssss", 0x204, 8 + $L, $Row, $Col, 0x0, $L);
echo $Value;
return;
}
//*********************************************
header("Pragma: public");
header("Expires: 0");

header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
header('Content-Type: application/vnd.ms-excel; charset=utf-8');
header("Content-Disposition: attachment;filename=Xsl-Ghorbani.xls ");
header("Content-Transfer-Encoding: binary ");


xlsBOF();
//*********************************************
xlsWriteLabel(0,0,"test test test test test");//خروجی اکسل برای بچه های گل برنامه نویس
//*********************************************
// Make column labels. (at line 3)
xlsWriteLabel(2,1,"First Name");
xlsWriteLabel(2,2,"Last Name");
xlsWriteLabel(2,3,"E-mail");
xlsWriteLabel(2,4,"Phone");
xlsWriteLabel(2,5,"Message");
xlsWriteLabel(2,6,"B First Name");
xlsWriteLabel(2,7,"B Last Name");
xlsWriteLabel(2,8,"B Phone");
xlsWriteLabel(2,9,"B E-mail");
xlsWriteLabel(2,10,"B Stuff");
$xlsRow = 3;

//************while($row=mysql_fetch_array($result)) {


xlsWriteLabel($xlsRow,1,"Reza");////$row['fname']
xlsWriteLabel($xlsRow,2,"Ghorbani");
xlsWriteLabel($xlsRow,3,"php_seo@yahoo.com");
xlsWriteLabel($xlsRow,4,"09119171500");
xlsWriteLabel($xlsRow,5,"Berid halesho bebarid");
xlsWriteLabel($xlsRow,6,"bfname");
xlsWriteLabel($xlsRow,7,"blname");
xlsWriteLabel($xlsRow,8,"btel");
xlsWriteLabel($xlsRow,9,"bemail");
xlsWriteLabel($xlsRow,10,"bstuff");
$xlsRow++;
////////////////////// }
xlsEOF();
exit();

djmohammad
December 19th, 2013, 04:22
کد کردن و دیکد کردن




function encryptDecrypt($key, $string, $decrypt)
{
if($decrypt)
{
$decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5($key), base64_decode($string), MCRYPT_MODE_CBC, md5(md5($key))), "12");
return $decrypted;
}else{
$encrypted = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5($key), $string, MCRYPT_MODE_CBC, md5(md5($key))));
return $encrypted;
}
}



طریقه استفاده :




echo encryptDecrypt('password', 'encrypt-decrypt this',0);

djmohammad
December 19th, 2013, 04:23
تولید رشته تصادفی





function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLM NOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}



طریقه استفاده :




echo generateRandomString(20);

djmohammad
December 19th, 2013, 04:24
نمایش فهرست فایلها (شامل فایلهای با اسامی فارسی) !
شاید مشکل عدم نمایش درست اسامی فایلهای فارسی برای خیلیها دردسرساز شده باشه. این کد مشکلتون رو رفع میکنه:






$files = scandir('.');
foreach($files as $file) {
echo iconv('windows-1256', 'utf-8', $file).''.PHP_EOL;
}

djmohammad
December 19th, 2013, 04:26
این هم چک کشور با ای پی :





<?
// Let me start off by saying I do not take full credit for this!
// I needed a way to get my traffic's country for Adverts...
// for some reason, json_decode wasn't working, so this is an alternative.

// json_decoder function from PHP.net
// file_get_contents_curl basic data retrieval function

// how to use:
// include('country.php');
// $userCountry=getTheCountry();
// output is 2 character country code, US, CA, etc...

function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);

return $data;
}

function json_decoder($json)
{
$comment = false;
$out = '$x=';

for ($i=0; $i<strlen($json); $i++)
{
if (!$comment)
{
if (($json[$i] == '{') || ($json[$i] == '[')) $out .= ' array(';
else if (($json[$i] == '}') || ($json[$i] == ']')) $out .= ')';
else if ($json[$i] == ':') $out .= '=>';
else $out .= $json[$i];
}
else $out .= $json[$i];
if ($json[$i] == '"' && $json[($i-1)]!="\\") $comment = !$comment;
}
eval($out . ';');
return $x;
}

function getTheCountry(){
$ipForCo=$_SERVER['REMOTE_ADDR'];
$getCo=file_get_contents_curl('http://ip2country.sourceforge.net/ip2c.php?ip='.$ipForCo.'&format=JSON');
$json_Co=json_decoder($getCo);
return $json_Co['country_code'];
}

djmohammad
December 19th, 2013, 04:27
HighLight کردن کدهای HTML درون متن :





<?php
function highlight_html($string, $decode = TRUE){
$tag = '#0000ff';
$att = '#ff0000';
$val = '#8000ff';
$com = '#34803a';
$find = array(
'~(\s[a-z].*?=)~', // Highlight the attributes
'~(&lt;\!--.*?--&gt;)~s', // Hightlight comments
'~(&quot;[a-zA-Z0-9\/].*?&quot;)~', // Highlight the values
'~(&lt;[a-z].*?&gt;)~', // Highlight the beginning of the opening tag
'~(&lt;/[a-z].*?&gt;)~', // Highlight the closing tag
'~(&amp;.*?;)~', // Stylize HTML entities
);
$replace = array(
'<span style="color:'.$att.';">$1</span>',
'<span style="color:'.$com.';">$1</span>',
'<span style="color:'.$val.';">$1</span>',
'<span style="color:'.$tag.';">$1</span>',
'<span style="color:'.$tag.';">$1</span>',
'<span style="font-style:italic;">$1</span>',
);
if($decode)
$string = htmlentities($string);
return '<pre>'.preg_replace($find, $replace, $string).'</pre>';
}

echo highlight_html('
<!-- This is an
HTML comment -->
<a href="home.html" style="color:blue;">Home</a>
<p>Go &amp; here.</p>
<!-- This is an HTML comment -->
<form action="/login.php" method="post">
<input type="text" value="User Name" />
</form>
');
?>

djmohammad
December 19th, 2013, 04:28
یکی از کدهایی که به زحمت گیرتون میاد !!

پاک کردن کامل یک دایرکتوری به همراه تمام محتویات درونش :





function full_delete($path)
{
$realPath = realpath($path);
if (!file_exists($realPath))
return false;
$DirIter = new RecursiveDirectoryIterator($realPath);
$fileObjects = new RecursiveIteratorIterator($DirIter, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($fileObjects as $name => $fileObj) {
if ($fileObj->isDir())
rmdir($name);
else
unlink($name);
}
rmdir($realPath);
return true;
}

djmohammad
December 19th, 2013, 04:29
تولید نقشه سایت (Site Map) :






<?php
// Please edit these values before running your script.
// The Url of the site - the last '/' is needed
$url = 'http://localhost/mycms/';
// Where the root of the site is with relation to this file.
$root_dir = '../mycms';
// Allowed extensions to consider in sitemap
$extensions = array(
'htm',
'html',
'php'
);
// Stuff to be ignored...
// Ignore the file/folder if these words appear anywhere in the name
$always_ignore = array(
'.inc',
'admin',
'image'
);
//These files will not be linked in the sitemap.
$ignore_files = array(
'404.php',
'error.php',
'config.php',
'include.inc'
);
//The script will not enter these folders
$ignore_dirs = array(
'.svn',
'admin',
'css',
'cvs',
'images',
'inc',
'includes',
'js',
'lib',
'stats',
'styles',
'system',
'uploads'
);
// Stop editing now - Configurations are over !

// This function extracts pages
function getPages($currentDir) {
global $url, $extensions, $always_ignore, $ignore_files, $ignore_dirs, $root_dir;
$pages = array();
chdir($currentDir);
$ext = '{';
foreach($extensions as $extension) {
$ext .= '*.'.$extension.',';
}
$ext = substr($ext, 0, -1);
$ext .= '}';
$files = glob($ext, GLOB_BRACE);
foreach($files as $file) {
$flag = true;
if(in_array($file, $ignore_files)) {
$flag = false;
}
else {
foreach($always_ignore as $ignore) {
if(strpos($file, $ignore) !== false) {
$flag = false;
}
}
}
if($flag) {
$pages[] = $url.($currentDir != $root_dir ? $currentDir.'/' : '').$file;
}
}
$dirs = glob('{*,*.*}', GLOB_BRACE | GLOB_ONLYDIR);
foreach($dirs as $dir) {
$flag = true;
if(in_array($dir, $ignore_dirs)) {
$flag = false;
}
else {
foreach($always_ignore as $ignore) {
if(strpos($dir, $ignore) !== false) {
$flag = false;
}
}
}
if($flag) {
$pages = array_merge($pages, getPages(preg_replace('#\\\\#', '/', $dir)));
chdir('..');
}
}
return $pages;
}
function generateSiteMap() {
global $root_dir;
$currentDir = getcwd();
$all_pages = getPages($root_dir);
chdir($currentDir);
$output = '';
$output .= '<?xml version="1.0" encoding="UTF-8"?>'.PHP_EOL;
$output .= '<urlset xmlns="http://www.google.com/schemas/sitemap/0.84" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.google.com/schemas/sitemap/0.84 http://www.google.com/schemas/sitemap/0.84/sitemap.xsd">'.PHP_EOL;
//Process the files
foreach ($all_pages as $link) {
//Find the modified time.
if(preg_match('#index\.\w{3,4}$#', $link)) {
$link = preg_replace('#index\.\w{3,4}$#', '', $link);
}
$output .= ' <url>'.PHP_EOL;
$output .= ' <loc>'.htmlentities($link).'</loc>'.PHP_EOL;
$output .= ' </url>'.PHP_EOL;
}
$output .= '</urlset>'.PHP_EOL;
return $output;
}

$currentDir = preg_replace('#\\\\#', '/', getcwd());
header('Content-Type: text/xml');
echo generateSiteMap();
chdir($currentDir);
?>

djmohammad
December 19th, 2013, 04:30
Copy a remote file to your site







FUNCTION copy_file($url,$filename){

$file = FOPEN ($url, "rb");

IF (!$file) RETURN FALSE; ELSE {
$fc = FOPEN($filename, "wb");

WHILE (!FEOF ($file)) {
$line = FREAD ($file, 1028);
FWRITE($fc,$line);
}

FCLOSE($fc);
RETURN TRUE;
}
}

djmohammad
December 19th, 2013, 04:32
Copy File From Server






<?PHP

$inputfile = FOPEN("http://the-remote-server.com/inputfile.txt", "r");
$outputfile = FOPEN("outputfile.txt", "w");
ECHO "File opened...";
$data = '';

WHILE (!FEOF($inputfile)) {
$data .= FREAD($inputfile, 8192);
}

ECHO "Data read...";
FWRITE($outputfile, $data);
ECHO "transfered data";
FCLOSE ($inputfile);
FCLOSE ($outputfile);

ECHO "Done.";

?>

djmohammad
December 19th, 2013, 04:33
Create Basic PDF





<?PHP

$cpdf = cpdf_open(0);
cpdf_page_init($cpdf, 1, 0, 595, 842, 1.0);
cpdf_add_outline($cpdf, 0, 0, 0, 1, "Page 1");
cpdf_begin_text($cpdf);
cpdf_set_font($cpdf, "Times-Roman", 30, "WinAnsiEncoding");
cpdf_set_text_rendering($cpdf, 1);
cpdf_text($cpdf, "Times Roman outlined", 50, 750);
cpdf_end_text($cpdf);
cpdf_moveto($cpdf, 50, 740);
cpdf_lineto($cpdf, 330, 740);
cpdf_stroke($cpdf);
cpdf_finalize($cpdf);
HEADER("Content-type: application/pdf");
cpdf_output_buffer($cpdf);
cpdf_close($cpdf);

?>

djmohammad
December 19th, 2013, 04:34
Create a drop down menu from an array list





<?PHP

// array contents array 1, value
$ddArray1 = ARRAY('Red','Green','Blue','Orange');

// array contents array 2, key => value
$ddArray2 = ARRAY('r'=>'Red','b'=>'Blue','g'=>'Green','o'=>'Or ange');

// Values from array 1
PRINT '<select name="Words">';

// for each value of the array assign a variable name word
FOREACH($ddArray1 AS $word){
PRINT '<option value="'.$word.'">'.$word.'</option>';
}
PRINT '</select>';

//Values from array 2
PRINT '<select name="Words">';

// for each key of the array assign a variable name $let
// for each value of the array assign a variable name $word

FOREACH($ddArray2 AS $let=>$word){
PRINT '<option value="'.$let.'">'.$word.'</option>';
}
PRINT '</select>';

?>

djmohammad
December 19th, 2013, 04:35
GD barchart demo






<?PHP

// bars.php3 - Bar chart on gif image
// Note: uses the gd library
// This code will display a bar chart based on random values
// Different colors are used to display bars and a gif images
// is used for the background. Use the following link to include
// the example into your web-site
// <img src="./bars.php3" border="0">
//
// The background image can be found at

HEADER( "Content-type: image/gif");
HEADER( "Expires: Mon, 17 Aug 1998 12:51:50 GMT");

$im = imagecreatefromgif( "gradient.gif");

// Allocate colors
$red=ImageColorAllocate($im,255,0,0);
$green=ImageColorAllocate($im,0,255,0);
$blue=ImageColorAllocate($im,0,0,255);
$yellow=ImageColorAllocate($im,255,255,0);
$cyan=ImageColorAllocate($im,0,255,255);

// Determine size of image
$x=imagesx($im);
$y=imagesy($im);

// Initialize random number generator
SRAND(MKTIME());

// Create some bars
$v=RAND(); $v=$v/32768*200;
ImageFilledRectangle($im,10,200-$v,60,200,$red);
$v=RAND(); $v=$v/32768*200;
ImageFilledRectangle($im,70,200-$v,120,200,$green);
$v=RAND(); $v=$v/32768*200;
ImageFilledRectangle($im,130,200-$v,180,200,$blue);
$v=RAND(); $v=$v/32768*200;
ImageFilledRectangle($im,190,200-$v,240,200,$yellow);
$v=RAND(); $v=$v/32768*200;
ImageFilledRectangle($im,250,200-$v,300,200,$cyan);

// Display modified image
ImageGif($im);
// Release allocated ressources
ImageDestroy($im);
?>

djmohammad
December 19th, 2013, 04:36
Find days between dates #1






<?PHP

$dt=ARRAY("27.01.1985","12.09.2008");
$dates=ARRAY();
$i=0;
WHILE(STRTOTIME($dt[1])>=STRTOTIME("+".$i." day",STRTOTIME($dt[0])))
$dates[]=DATE("Y-m-d",STRTOTIME("+".$i++." day",STRTOTIME($dt[0])));

FOREACH($dates AS $value) ECHO $value."";

?>

djmohammad
December 19th, 2013, 04:37
Graphical tree like Explorer






<?PHP

/*
Here are the database definitions used in this code.
It should be fairly east to adapt it to another database.
*/

/*
CREATE TABLE dirent_types (
id INTEGER NOT NULL,
icon VARCHAR(50),
name VARCHAR(50),
PRIMARY KEY(id)
);

INSERT INTO dirent_types VALUES(1, 'folderclosed', 'Directory');
INSERT INTO dirent_types VALUES(2, 'document', 'File');

CREATE TABLE directory (
id INTEGER NOT NULL,
parent INTEGER REFERENCES directory(id),
name VARCHAR(200),
icon VARCHAR(50),
type INTEGER REFERENCES dirent_types(id),
url VARCHAR(200),
PRIMARY KEY(id)
);

DROP INDEX directory_idx;

CREATE UNIQUE INDEX directory_idx ON directory(parent, name);

CREATE SEQUENCE dirent_id;

"CREATE PROCEDURE insert_dir_entry
(name VARCHAR, parent INTEGER, type INTEGER)
RETURNS(id INTEGER)
BEGIN
EXEC SQL WHENEVER SQLERROR ABORT;
EXEC SEQUENCE dirent_id.NEXT INTO id;
EXEC SQL PREPARE c_insert
INSERT INTO directory
(id, parent, type, name)
VALUES(?, ?, ?, ?);
EXEC SQL EXECUTE c_insert USING (id, parent, type, name);
EXEC SQL DROP c_insert;
END";

CALL insert_dir_entry('My Computer', NULL, 1);
CALL insert_dir_entry('Network Neighbourhood', NULL, 1);
CALL insert_dir_entry('lucifer.guardian.no', 2, 1);
CALL insert_dir_entry('rafael.guardian.no', 2, 1);
CALL insert_dir_entry('uriel.guardian.no', 2, 1);
CALL insert_dir_entry('Control Panel', NULL, 1);
CALL insert_dir_entry('Services', 6, 1);
CALL insert_dir_entry('Apache', 7, 2);
CALL insert_dir_entry('Solid Server 2.2', 7, 2);

*/

FUNCTION icon($icon, $name = '', $width = 0, $height = 0) {
GLOBAL $DOCUMENT_ROOT;
$icon_loc = '/pics/menu';
$file = "$DOCUMENT_ROOT$icon_loc/$icon.gif";
IF (!$width || !$height) {
$iconinfo = GETIMAGESIZE($file);
IF (!$width) {
$width = $iconinfo[0];
}
IF (!$height) {
$height = $iconinfo[1];
}
}
PRINTF( '<img%s border=0 align=top src="/pics/menu/%s.gif" '.
'width="%d" height="%d">', $name ? " name=\"$name\"" : '',
$icon, $width, $height);
}

/*
* Displays, recursively, the contents of a tree given a starting
* point.
*
* Parameters:
* $parent - the parent node (not listed in the directory). Node
* 0 is the root node.
*
* $maxdepth (optional) - maximum number of recursion levels. -1
* (the default value) means no limits.
*
* $ancestors (optional) - an array of the ancestor nodes in the
* current branch of the tree, with the node closest to the
* top at index 0.
*
* Global variables used:
* $child_nodes
* $node_data
* $last_child
*
* Global variables modified:
* The array pointers in $child_nodes will be modified.
*/
FUNCTION display_directory($parent, $showdepth = 0, $ancestors = FALSE) {
GLOBAL $child_nodes, $node_data, $last_child;
RESET($child_nodes[$parent]);
$size = SIZEOF($child_nodes[$parent]);
$lastindex = $size - 1;
IF (!$ancestors) {
$ancestors = ARRAY();
}
$depth = SIZEOF($ancestors);
PRINTF( '<div id="node_%d" class="dirEntry" visibility="%s">',
$parent, $showdepth > 0 ? 'show' : 'hide');
WHILE (LIST($index, $node) = EACH($child_nodes[$parent])) {
/*
For each of the uptree nodes:
If an uptree node is not the last one on its depth
of the branch, there should be a line instead of a blank
before this node's icon.
*/
FOR ($i = 0; $i < $depth; $i++) {
$up_parent = (int)$node_data[$ancestors[$i]][ 'parent'];
$last_node_on_generation = $last_child[$up_parent];
$uptree_node_on_generation = $ancestors[$i];
IF ($last_node_on_generation == $uptree_node_on_generation) {
icon( "blank");
} ELSE {
icon( "line");
}
}
IF ($child_nodes[$node]) { // has children, i.e. it is a folder
$conn_icon = "plus";
$expand = TRUE;
} ELSE {
$conn_icon = "join";
$expand = FALSE;
}
IF ($index == $lastindex) {
$conn_icon .= "bottom";
} ELSEIF ($depth == 0 && $index == 0) {
$conn_icon .= "top";
}
IF ($expand) {
PRINTF( "<a href=\"javascript<b></b>:document.layers['node_%d'].visibility='show'\">", $node);
}
icon($conn_icon, "connImg_$node");
IF ($expand) {
PRINT( "</a>");
}
$icon = $node_data[$node][ 'icon'];
IF (!$icon) {
$type = $node_data[$node][ 'type'];
$icon = $GLOBALS[ 'dirent_icons'][$type];
}
icon($icon, "nodeImg_$node");
$name = $node_data[$node][ 'name'];
PRINTF( '?<font size="%d">%s</font><br%c>', -1, $name, 10);
IF ($child_nodes[$node]) {
$newdepth = $showdepth;
IF ($newdepth > 0) {
$newdepth--;
}
$new_ancestors = $ancestors;
$new_ancestors[] = $node;
display_directory($node, $newdepth, $new_ancestors);
}
}
PRINT( "</div\n>");
}
FUNCTION setup_directory($parent, $maxdepth)
{
GLOBAL $dirent_icons, $child_nodes, $node_data, $last_child;
$dirent_icons = sql_assoc( 'SELECT id,icon FROM dirent_types');
$query = 'SELECT id,parent,type,icon,name '.
'FROM directory '.
'ORDER BY parent,name';
$child_nodes = ARRAY();
$node_data = ARRAY();
$res = sql($query);
WHILE (LIST($id, $parent, $type, $icon, $name) = db_fetch_row($res)) {
$child_nodes[(int)$parent][] = $id;
$node_data[$id] = ARRAY( 'id' => $id,
'parent' => $parent,
'type' => $type,
'icon' => $icon,
'name' => $name);
$last_child[(int)$parent] = $id;
}
}
?>

djmohammad
December 19th, 2013, 04:38
Handy SORT BY box+No SQL INjection




<?PHP

$selected = ARRAY();

$orderby = $_GET[orderby];
IF(!$orderby) { $orderby = 'price_asc'; }

IF($orderby == 'price_asc')
{
$orderby_query = "order by price asc";
}
ELSE IF($orderby == 'price_desc')
{
$orderby_query = "order by price desc";
}
ELSE IF($orderby == 'name')
{
$orderby_query = "order by name";
}
ELSE { UNSET($orderby); }

// If $orderby was valid set the selected sort option for the form.

IF($orderby)
{
$selected[$orderby] = 'selected';
}

// Now run your SQL query with the $orderby_query variable. Ex:

$query = "select * from products $orderby_query";

// SQL code goes here..

?>

Sort by
<form method=get style="display: inline;" name='orderby_form'>
<input type=hidden name='param1' value="<?PHP PRINT $param1; ?>">
<input type=hidden name='param2' value="<?PHP PRINT $param2; ?>">
<select name=orderby onChange="orderby_form.submit();">
<option value='name' <?PHP PRINT $selected[$orderby]; ?>>Name</option>
<option value='price_asc' <?PHP PRINT $selected[$orderby]; ?>>Price (Low - High)</option>
<option value='price_desc' <?PHP PRINT $selected[$orderby]; ?>>Price (High - Low)</option>
</select>
</form>

djmohammad
December 19th, 2013, 04:39
How many days ago





<?PHP

// convert a date into a string that tells how long
// ago that date was.... eg: 2 days ago, 3 minutes ago.
FUNCTION ago($d) {
$c = GETDATE();
$p = ARRAY('year', 'mon', 'mday', 'hours', 'minutes', 'seconds');
$display = ARRAY('year', 'month', 'day', 'hour', 'minute', 'second');
$factor = ARRAY(0, 12, 30, 24, 60, 60);
$d = datetoarr($d);
FOR ($w = 0; $w < 6; $w++) {
IF ($w > 0) {
$c[$p[$w]] += $c[$p[$w-1]] * $factor[$w];
$d[$p[$w]] += $d[$p[$w-1]] * $factor[$w];
}
IF ($c[$p[$w]] - $d[$p[$w]] > 1) {
RETURN ($c[$p[$w]] - $d[$p[$w]]).' '.$display[$w].'s ago';
}
}
RETURN '';
}

// you can replace this if need be. This converts the dates
// returned from a mysql date string into an array object similar
// to that returned by getdate().
FUNCTION datetoarr($d) {
PREG_MATCH("/([0-9]{4})(\\-)([0-9]{2})(\\-)([0-9]{2}) ([0-9]{2})(\\:)([0-9]{2})(\\:)([0-9]{2})/", $d, $matches);
RETURN ARRAY(
'seconds' => $matches[10],
'minutes' => $matches[8],
'hours' => $matches[6],
'mday' => $matches[5],
'mon' => $matches[3],
'year' => $matches[1],
);
}

?>

djmohammad
December 19th, 2013, 04:40
Output as Word Doc format





<?PHP

$query = "SELECT * FROM TABLE WHERE data = '$data'";

$result = MYSQL_QUERY($query);
$count = MYSQL_NUM_FIELDS($result);

FOR ($i = 0; $i < $count; $i++){
IF (ISSET($header))
$header .= MYSQL_FIELD_NAME($result, $i)."\t";
ELSE
$header = MYSQL_FIELD_NAME($result, $i)."\t";
}

WHILE ($row = MYSQL_FETCH_ROW($result)){
$line = '';

FOREACH ($row AS $value)
{
IF (!ISSET($value) || $value == '')
$value = "\t";
ELSE
{
$value = STR_REPLACE('"', '""', $value);
$value = '"'.$value.'"'."\t";
}

$line .= $value;
}

IF (ISSET($data))
$data .= TRIM($line)."\n";
ELSE
$data = TRIM($line)."\n";
}

$data = STR_REPLACE("\r", "", $data);

IF ($data == '')
$data = "\nno matching records\n";

HEADER("Content-Type: application/vnd.ms-word; name='word'");
HEADER("Content-type: application/octet-stream");
HEADER("Content-Disposition: attachment; filename=filename_here.doc");
HEADER("Cache-Control: must-revalidate, post-check=0, pre-check=0");
HEADER("Pragma: no-cache");
HEADER("Expires: 0");

ECHO $header."\n".$data;
EXIT;

?>

djmohammad
December 19th, 2013, 04:41
Perfect Highlighting Function





<?PHP

// highlight words in a string
FUNCTION highlight($text, $search) {
$text = PREG_REPLACE( "/(^|\s|,!|;)(".PREG_QUOTE($search, "/").")(\s|,|!|&|$)/i", "\\1<span class='hlstyle'>\\2</span>\\3", $text );
RETURN $text;
}

?>

djmohammad
December 19th, 2013, 04:43
تابع preg برای حروف فارسی





<?php
preg_match("/[\x{0600}-\x{06FF}\x]{1,32}/u", 'محمد عبدالهی');
?>

djmohammad
December 19th, 2013, 04:44
تشخیص موقعیت از روی IP :





function detect($ip) {
$default = 'UNKNOWN';
if (!is_string($ip) || strlen($ip) < 1 || $ip == '127.0.0.1' || $ip == 'localhost') {
$ip = '8.8.8.8';
}
$curlopt_useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6 (.NET CLR 3.5.30729)';
$url = 'http://ipinfodb.com/ip_locator.php?ip=' . urlencode($ip);
$ch = curl_init();
$curl_opt = array(
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_USERAGENT => $curlopt_useragent,
CURLOPT_URL => $url,
CURLOPT_TIMEOUT => 1,
CURLOPT_REFERER => 'http://' . $_SERVER['HTTP_HOST'],
);
curl_setopt_array($ch, $curl_opt);
ob_start();
curl_exec($ch);
$content = ob_get_contents();
ob_end_clean();
curl_close($ch);

if(preg_match('#<li>City : ([^<]*)</li>#i', $content, $regs)) {
$city = $regs[1];
}
if(preg_match('#<li>State/Province : ([^<]*)</li>#i', $content, $regs)) {
$state = $regs[1];
}

if($city != '' && $state != '') {
$location = $city . ', ' . $state;
return $location;
}
else {
return $default;
}
}

djmohammad
December 19th, 2013, 04:45
تعداد طرفداران صفحه شما در FaceBook :






<?php
function fb_fan_count($facebook_name) {
// Example: https://graph.facebook.com/host5.ir
$data = json_decode(file_get_contents("https://graph.facebook.com/".$facebook_name));
echo $data->likes;
}
?>

djmohammad
December 19th, 2013, 04:46
مشاهده میزان حافظه مصرفی اسکریپت شما:





<?php
echo "Initial: ".memory_get_usage()." bytes \n";
/* prints
Initial: 361400 bytes
*/

// let's use up some memory
for ($i = 0; $i < 100000; $i++) {
$array []= md5($i);
}

// let's remove half of the array
for ($i = 0; $i < 100000; $i++) {
unset($array[$i]);
}

echo "Final: ".memory_get_usage()." bytes \n";
/* prints
Final: 885912 bytes
*/

echo "Peak: ".memory_get_peak_usage()." bytes \n";
/* prints
Peak: 13687072 bytes
*/
?>

djmohammad
December 19th, 2013, 04:48
Whois با PHP :







<?php
function whois_query($domain) {
// fix the domain name:
$domain = strtolower(trim($domain));
$domain = preg_replace('#^http:\/\/#i', '', $domain);
$domain = preg_replace('#^www\.#i', '', $domain);
$domain = explode('/', $domain);
$domain = trim($domain[0]);

// split the TLD from domain name
$_domain = explode('.', $domain);
$lst = count($_domain)-1;
$ext = $_domain[$lst];

// You find resources and lists
// like these on wikipedia:
//
// http://de.wikipedia.org/wiki/Whois
//
$servers = array(
'ac' => 'whois.nic.ac',
'ae' => 'whois.uaenic.ae',
'aero' => 'whois.information.aero',
'at' => 'whois.ripe.net',
'au' => 'whois.aunic.net',
'be' => 'whois.dns.be',
'bg' => 'whois.ripe.net',
'biz' => 'whois.neulevel.biz',
'br' => 'whois.registro.br',
'bz' => 'whois.belizenic.bz',
'ca' => 'whois.cira.ca',
'cc' => 'whois.nic.cc',
'ch' => 'whois.nic.ch',
'cl' => 'whois.nic.cl',
'cn' => 'whois.cnnic.net.cn',
'com' => 'whois.internic.net',
'coop' => 'whois.nic.coop',
'cz' => 'whois.nic.cz',
'de' => 'whois.nic.de',
'edu' => 'whois.internic.net',
'fr' => 'whois.nic.fr',
'gov' => 'whois.nic.gov',
'hu' => 'whois.nic.hu',
'ie' => 'whois.domainregistry.ie',
'il' => 'whois.isoc.org.il',
'in' => 'whois.ncst.ernet.in',
'info' => 'whois.nic.info',
'int' => 'whois.iana.org',
'ir' => 'whois.nic.ir',
'mc' => 'whois.ripe.net',
'mil' => 'rs.internic.net',
'name' => 'whois.nic.name',
'net' => 'whois.internic.net',
'nl' => 'whois.domain-registry.nl'
'org' => 'whois.pir.org',
'ru' => 'whois.ripn.net',
'to' => 'whois.tonic.to',
'tv' => 'whois.tv',
'us' => 'whois.nic.us',
);

if (!isset($servers[$ext]) || !in_array($ext, $servers)) {
die('Error: No matching nic server found!');
}

$nic_server = $servers[$ext];
$output = '';

// connect to whois server:
if ($conn = fsockopen ($nic_server, 43)) {
fputs($conn, $domain."\r\n");
while(!feof($conn)) {
$output .= fgets($conn, 128);
}
fclose($conn);
}
else {
die('Error: Could not connect to ' . $nic_server . '!');
}

return $output;
}
?>

djmohammad
December 19th, 2013, 04:49
فرستادن خطاهای PHP به ایمیل شما بجای نمایش در صفحه:






<?php
// Our custom error handler
function mail_error_handler($number, $message, $file, $line, $vars) {
$email = "
<p>An error ({$number}) occurred on line
<strong>{$line}</strong> and in the <strong>file: {$file}.</strong>
<p> {$message} </p>";

$email .= "<pre>" . print_r($vars, 1) . "</pre>";

$headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n";

// Email the error to someone...
@mail($email, 'PHP_ERROR', 'you@youremail.com', $headers);

// Make sure that you decide how to respond to errors (on the user's side)
// Either echo an error message, or kill the entire project. Up to you...
// The code below ensures that we only "die" if the error was more than
// just a NOTICE.
if (($number !== E_NOTICE) && ($number < 2048)) {
die('There was an error. Please try again later.');
}
}

// We should use our custom function to handle errors.
set_error_handler('mail_error_handler');

// Trigger an error... (var doesn't exist)
echo $somevarthatdoesnotexist;
?>

djmohammad
December 19th, 2013, 04:50
آپلود فایل در FTP :





<?php
// FTP access parameters
$host = 'ftp.example.org';
$usr = 'example_user';
$pwd = 'example_password';

// file to move:
$local_file = './example.txt';
$ftp_path = '/data/example.txt';

// connect to FTP server (port 21)
$conn_id = ftp_connect($host, 21) or die ("Cannot connect to host");

// send access parameters
ftp_login($conn_id, $usr, $pwd) or die("Cannot login");

// turn on passive mode transfers (some servers need this)
// ftp_pasv ($conn_id, true);

// perform file upload
$upload = ftp_put($conn_id, $ftp_path, $local_file, FTP_ASCII);

// check upload status:
print (!$upload) ? 'Cannot upload' : 'Upload complete';
print "\n";

/*
** Chmod the file (just as example)
*/

// If you are using PHP4 then you need to use this code:
// (because the "ftp_chmod" command is just available in PHP5+)
if (!function_exists('ftp_chmod')) {
function ftp_chmod($ftp_stream, $mode, $filename){
return ftp_site($ftp_stream, sprintf('CHMOD %o %s', $mode, $filename));
}
}

// try to chmod the new file to 666 (writeable)
if (ftp_chmod($conn_id, 0666, $ftp_path) !== false) {
print $ftp_path . " chmoded successfully to 666\n";
} else {
print "could not chmod $file\n";
}

// close the FTP stream
ftp_close($conn_id);
?>

djmohammad
December 19th, 2013, 04:51
جداسازی اعداد از رشته :





<?php
// extract numbers from a string
// http://php.snippetdb.com

$string = "The 1. Quick and 2. Brown fox said 3. (!@*(#!@*";

$new_string = ereg_replace("[^0-9]", "", $string);

echo $new_string;

?>

djmohammad
December 19th, 2013, 04:52
یک فانکشن خیلی خیلی باحال ! تولید متن رنگارنگ (منظور موج رنگها) :





<?
//simple to use!
echo fadeText('ff0000','0000ff','this is the text that will be faded!');
function getColor($startc, $endc, $percentc)
{
$r1=hexdec(substr($startc,-6,2));
$g1=hexdec(substr($startc,-4,2));
$b1=hexdec(substr($startc,-2,2));

$r2=hexdec(substr($endc,-6,2));
$g2=hexdec(substr($endc,-4,2));
$b2=hexdec(substr($endc,-2,2));

$pcc = $percentc/100;

$rcc= ($r1+($pcc*($r2-$r1)))*1;
$gcc= ($g1+($pcc*($g2-$g1)))*1;
$bcc= ($b1+($pcc*($b2-$b1)))*1;
$frc= dechex($rcc);
$fgc= dechex($gcc);
$fbc= dechex($bcc);

if (strlen($frc)=="1"){
$frc="0".$frc;
}
if (strlen($fgc)=="1"){
$fgc="0".$fgc;
}
if (strlen($fbc)=="1"){
$fbc="0".$fbc;
}
$dasclr="#".$frc."".$fgc."".$fbc;
return $dasclr;
}

function fadeText($start, $end, $msg)
{
$myString2Fade = $msg;
$endResult="";
$daslen=strlen($myString2Fade);
for ($i=0 ; $i<$daslen ; $i++){
$perc=(100/$daslen)*$i;
if ($myString2Fade[$i]==" "){
$endResult="$endResult ";
} else {
$endResult="$endResult<font color='".getColor($start, $end, $perc)."'>".$myString2Fade[$i]."</font>";
}
}
return $endResult;
}
?>

djmohammad
December 19th, 2013, 04:53
یک مثال برای DOM :





<?php
// example HTML code: (could also come from an URL)
$html = '<html>
<head>
<title>links</title>
</head>
<body>
<a href="link1.htm" title="Link title 1" target="_blank">Link #1</a>
<a href="link2.htm" title="Link title 2" target="_blank">Link #2</a>
<a href="link3.htm" title="Link title 3" target="_blank">Link #3</a>
</body>
</html>';

// check if DomXML is available:
if (!function_exists('DomDocument')){
die('DomXML extension is not available :-(');
}

print '<pre>';

// create new DOM object:
$dom = new DomDocument();

// load HTML code:
$dom->loadHtml($html);

// get tags by tagname (all <a> tags / links):
$tags = $dom->getElementsByTagName('a');

// loop trough all links:
foreach ($tags as $a){

print '<b>' . $a->nodeValue . '</b>';

// does this tag have attributes:
if ($a->hasAttributes()){

// loop trough all attributes:
foreach ($a->attributes as $attribute){
print '- ' . $attribute->name . ': ' . $attribute->value;
print "";
}
}

print "<hr/>";
}

print '</pre>';
?>

djmohammad
December 19th, 2013, 04:54
یک مثال ساده برای تولید پیج داینامیک بوسیله لینکها و Mysql :






<!---------------------------------- Change File name To links.php -------------------->


<!-- links.php -->

<a href="links.php?id=1">File 1</a>
<a href="links.php?id=2">File 2</a>
<a href="links.php?id=3">File 3</a>
<?php
// Load the database connections
include 'db.php';
//check to see if one of the links were clicked
echo '<div>';
if(isset($_GET['id'])){
// Make a safe string
$id = mysql_real_escape_string($_GET['id']);
// Query the database
$sql = mysql_query("SELECT * FROM table_name WHERE id='$id'");
if(mysql_num_rows($sql) == 1){
// If one row was found, create an array of the row
$row = mysql_fetch_array($sql);
// echo the column 'content' (change 'content' to your column name)
echo '<p>'.$row['content'].'</p>';
}else{
// Row was not found
echo '<p>File Not Found.</p>';
}
}else{
// the id parameter in the url was not set
echo '<p>Invalid URL.</p>';
}
echo '</div>';
?>

djmohammad
December 19th, 2013, 04:56
نمایش بخشی از تصویر





<?php
header('Content-type: image/jpeg');
if(!isset($_GET['file']) || !file_exists($_GET['file']) || strtolower(substr($_GET['file'], strrpos($_GET['file'], '.'))) != '.jpg') {
$im = imagecreatetruecolor(100, 100);
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
imagefill($im, 50, 50, $white);
imagestring($im, 5, 30, 40, 'Error', $black);
imagejpeg($im);
imagedestroy($im);
exit();
}
$src = imagecreatefromjpeg($_GET['file']);
$sw = imagesx($src);
$sh = imagesy($src);
$x1 = (isset($_GET['x1']) && is_numeric($_GET['x1']) && $_GET['x1'] >= 0 && $_GET['x1'] < $sw) ? (int) $_GET['x1'] : 0;
$y1 = (isset($_GET['y1']) && is_numeric($_GET['y1']) && $_GET['y1'] >= 0 && $_GET['y1'] < $sh) ? (int) $_GET['y1'] : 0;
$x2 = (isset($_GET['x2']) && is_numeric($_GET['x2']) && $_GET['x2'] >= 0 && $_GET['x2'] < $sw) ? (int) $_GET['x2'] : $sw;
$y2 = (isset($_GET['y2']) && is_numeric($_GET['y2']) && $_GET['y2'] >= 0 && $_GET['y2'] < $sh) ? (int) $_GET['y2'] : $sh;
$tl = array('x' => min ($x1, $x2), 'y' => min($y1, $y2));
$br = array('x' => max ($x1, $x2), 'y' => max($y1, $y2));
$dw = abs($x1 - $x2);
$dh = abs($y1 - $y2);
$dst = imagecreatetruecolor($dw, $dh);
imagecopyresized($dst, $src, 0, 0, $tl['x'], $tl['y'], $dw, $dh, $br['x'], $br['y']);
imagejpeg($dst);
imagedestroy($dst);
imagedestroy($src);
?>




نحوه استفاده :




<img src="pim.php?file=image.jpg&x1=50&y1=50&x2=200&y2=100"/>


(با فرض اینکه کد فوق رو به اسم pim.php ذخیره کرده باشین).
کاربرد اصلی این اسکریپت برای وقتی هست که میخواین یک تصویر رو بصورت تکه تکه نشون بدین و با CSS تنظیم کنید تا کنار هم ظاهر بشه. دیگه نیازی نیست توی Photoshop یا سایر برنامه ها تصویر رو برش بدین و توی فایلهای جداگانه ذخیره کنید و در فضای هاست هم صرفه جویی میشه چون برای هر فایل جداگانه، هدرهای تصویر ذخیره میشن و این یعنی تکرار هدرها. کد فوق رو با کمی تغییر میتونید برای سایر انواع تصویر مثل png و... هم استفاده کنید.
موفق باشید.

djmohammad
December 19th, 2013, 04:58
Backup گرفتن از دیتابیس





<?php
function backup_db($host, $user, $pass, $name, $tables = '*') {
date_default_timezone_set('Asia/Tehran');

$return = '';

mysql_connect($host,$user,$pass) or die('Connection error');
mysql_select_db($name) or die('Database error');
mysql_query('SET NAMES \'utf8\'');
mysql_set_charset('utf8');

if($tables == '*') {
$tables = array();
$result = mysql_query('SHOW TABLES');
while($row = mysql_fetch_row($result)) {
$tables[] = $row[0];
}
mysql_free_result($result);
}
else {
$tables = is_array($tables) ? $tables : explode(',', $tables);
}

foreach($tables as $table) {
$result = mysql_query('SELECT * FROM `'.$table.'`');
$num_fields = mysql_num_fields($result);
$return .= 'DROP TABLE IF EXISTS `'.$table.'`;'.PHP_EOL.PHP_EOL;
$row = mysql_fetch_row(mysql_query('SHOW CREATE TABLE `'.$table.'`'));
$return .= $row[1].';'.PHP_EOL.PHP_EOL;

for ($i = 0; $i < $num_fields; $i++) {
while($row = mysql_fetch_row($result)) {
$return.= 'INSERT INTO `'.$table.'` VALUES(';
for($j = 0; $j < $num_fields; $j++) {
$row[$j] = addslashes($row[$j]);
$row[$j] = str_replace('\n', '\\n', $row[$j]);
if (isset($row[$j])) {
$return .= '\''.$row[$j].'\'';
}
else {
$return .= '\'\'';
}
if ($j < ($num_fields - 1)) {
$return .= ',';
}
}
$return .= ');'.PHP_EOL;
}
}
$return .= PHP_EOL.PHP_EOL.PHP_EOL;
}

$handle = fopen('db-backup-'.$name.'-'.date('Y,m,d-H,i,s').'.sql', 'w');
fwrite($handle, $return);
fclose($handle);
}
?>



مثالی از نحوه استفاده از تابع بالا :





backup_db('localhost', 'root', '', 'your_db_name');

djmohammad
December 19th, 2013, 04:59
جداسازی آدرس ها از متن و تبدیل به لینک :





<?php
function to_link($string){
return preg_replace("~(http|https|ftp|ftps)://(.*?)(\s|\n|[,.?!](\s|\n)|$)~", '<a href="$1://$2">$1://$2</a>$3',$string);
}

$html = 'This line of text has three urls: http://webhostingtalk.ir http://yahoo.com and http://google.com';

echo to_link($html, TRUE);
?>

djmohammad
December 19th, 2013, 05:00
سازنده تگ (Tag Builder)






<?php
function buildTag($tag, $att = array(), $selfColse = FALSE, $inner = ''){
$t = '<'.$tag.' ';
foreach($att as $k => $v){
$t .= $k.'="'.$v.'"';
}
if(!$selfColse)
$t .= '>';
else
$t .= ' />';
if(!$selfColse)
$t .= $inner.'</'.$tag.'>';
return $t;
}
// Example 1:
echo buildTag('input', array('type'=>'button', 'value'=>'WOOT!'), TRUE);

// Example 2:
echo buildTag('div', array('style'=>'border:solid 1px #000'), FALSE, buildTag('a', array('href'=>'http://google.com'), FALSE, 'Google'));
?>

djmohammad
December 19th, 2013, 05:01
کوتاه کردن متن و بستن تگهای بسته نشده !





function shorten_text($str, $limit='100')
{
$array_words = explode(' ', $str);
if(count($array_words) > $limit)
{
$i = 0;
$final = '';
foreach($array_words as $word){
if($limit > $i)
{
$final .= "$word ";
}
$i++;
}
$short = 1;
}
else
{
$final = $str;
}

$tags = array('center' => 'center',
'img=[^\]]*' => 'img',
'url=[^\]]*' => 'url',
'img' => 'img',
'url' => 'url',
'u' => 'u',
'i' => 'i',
'b' => 'b',
'align=[^\]]*' => 'align',
'mail=[^\]]*' => 'mail',
'font=[^\]]*' => 'font',
'size=[^\]]*' => 'size',
'color=[^\]]*' => 'color');
$matches = array();
foreach ($tags as $opentag => $closetag)
{
$closed = preg_match_all("~\[/".$closetag."\]~i", $final, $matches);
$open = preg_match_all("~\[".$opentag."\]~i", $final, $matches);

if ($open > $closed)
{
$final .= "[/".$closetag."]";
}
}

if(isset($short))
{
return "".$final."[....]";
}
else
{
return $final;
}

}
?>

djmohammad
December 19th, 2013, 15:06
برگرداندن همه ی مقادیر تکرار شده در یک آرایه





<?php
function array_repeated($array){
if (!is_array($array))
return false;

$repeated_values = Array();

$array_unique = array_unique($array);

if (count($array) - count($array_unique)){
for ($i=0; $i<count($array); $i++)
{
if (!array_key_exists($i, $array_unique))
$repeated_values[] = $array[$i];
}
}
return $repeated_values;
}
?>

djmohammad
December 19th, 2013, 15:07
جداسازی درخواست AJAX .. مثلا اگه کسی بوسیله AJAX درخواست را ارسال کرد یک عمل دیگه انجام بشه





if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
//If AJAX Request Then
}else{
//something else
}

djmohammad
December 19th, 2013, 15:08
مقایسه ی دو String





<?php
// This will return a number of how many more characters the longest string has
function str_compare_length($str1, $str2){
$len1 = strlen($str1);
$len2 = strlen($str2);
if($str1 > $str2){
return $len1 - $len2;
}else{
return $len2 - $len1;
}
}

echo str_compare_length("This is the first string", "This is the second string");
?>

djmohammad
June 23rd, 2014, 02:13
با سلام

امروز می خواهم کدی را به شما معرفی کنم که با اون می تونید معین کنید که کاربری که لاگین کرده به سایت در صورتی که طی زمان خاصی فعالیتی در سایت انجام ندهد آن را logout کنیم ....




//توسط : محمد عبدالهی
//Host5.ir

<?php
# Start a session
session_start();
# Check if a user is logged in
function isLogged(){
if($_SESSION['logged']){ # When logged in this variable is set to TRUE
return TRUE;
}else{
return FALSE;
}
}

# Log a user Out
function logOut(){
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
session_destroy();
}

# Session Logout after in activity
function sessionX(){
$logLength = 1800; # time in seconds :: 1800 = 30 minutes
$ctime = strtotime("now"); # Create a time from a string
# If no session time is created, create one
if(!isset($_SESSION['sessionX'])){
# create session time
$_SESSION['sessionX'] = $ctime;
}else{
# Check if they have exceded the time limit of inactivity
if(((strtotime("now") - $_SESSION['sessionX']) > $logLength) && isLogged()){
# If exceded the time, log the user out
logOut();
# Redirect to login page to log back in
header("Location: /login.php");
exit;
}else{
# If they have not exceded the time limit of inactivity, keep them logged in
$_SESSION['sessionX'] = $ctime;
}
}
}
# Run Session logout check
sessionX();
?>