با سلام خوب در این تاپیک می خوام مجموعه ای از کدهای بدرد بخور جدید رو برای شما قرار بدم
امیدوارم مفید باشه
تشکر هم یادتون نره :)
نمایش نسخه قابل چاپ
با سلام خوب در این تاپیک می خوام مجموعه ای از کدهای بدرد بخور جدید رو برای شما قرار بدم
امیدوارم مفید باشه
تشکر هم یادتون نره :)
دریافت پسوند فایل
طریقه استفاده از کد بالاکد PHP:
function get_extension($filename)
{
$myext = substr($filename, strrpos($filename, '.'));
return str_replace('.','',$myext);
}
کد PHP:
$filename = 'this_myfile.cd.doc';
echo get_extension($filename)
حذف پسوند فایل
طریقه استفاده از کد :کد PHP:
function RemoveExtension($strName)
{
$ext = strrchr($strName, '.');
if($ext !== false)
{
$strName = substr($strName, 0, -strlen($ext));
}
return $strName;
}
کد PHP:
echo RemoveExtension('myfile.ho');
بدست آوردن اندازه فایل
طریقه استفاده از کد بالا :کد PHP:
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]); }
}
کد PHP:
$thefile = filesize('test_file.mp3')
echo format_size($thefile);
حذف کاراکترهای غیر ASCII را از رشته
طریقه استفاده از کد بالا :کد PHP:
function clean_none_ascii($output) {
$output = preg_replace('/[^(x20-x7F)]*/','', $output);
return $output;
}
کد PHP:
$output = "Clean this copy of invalid non ASCII äócharacters.";echo clean_non_ascii($output);
تجزیه رشته
طریقه استفاده :کد PHP:
function string_parser($string,$replacer)
{
$result = str_replace(array_keys($replacer), array_values($replacer),$string);
return $result;
}
کد PHP:
$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);
ارسال ایمیل با بدنه html
طریقه استفاده :کد PHP:
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;
}
}
کد PHP:
$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';}
فهرست فایلها در یک دایرکتوری
کد PHP:
function listDirFiles($DirPath)
{
if($dir = opendir($DirPath)){
while(($file = readdir($dir))!== false){
if(!is_dir($DirPath.$file))
{
echo "filename: $file";
}
}
}
}
طریقه استفاده :
کد PHP:
listDirFiles('home/some_folder/');
قرار دادن گراواتار شخصی در سایت خود
کد PHP:
function gravatar($email, $rating = false, $size = false, $default = false) {
$out = "http://www.gravatar.com/avatar.php?gravatar_id=".md5($email);
if($rating && $rating != '')
$out .= "&rating=".$rating;
if($size && $size != '')
$out .="&size=".$size;
if($default && $default != '')
$out .= "&default=".urlencode($default);
echo $out;
}
طریقه استفاده :
کد PHP:
<!--
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'); ?>" />
اتوماتیک لینک کردن تمام آدرس ها و ایمیل ها
کد PHP:
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;
}
طریقه استفاده :
کد PHP:
$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);
گرفتن آدرس خروجی از صفحه فعلی
کد PHP:
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;
}
طریقه استفاده از کد بالا :
کد PHP:
echo curPageURL();
کوتاه کردن متن های طولانی
طریقه استفاده :کد PHP:
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;
}
کد PHP:
$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);
خلاصه کردن یک رشته
مثال :
“Really long title” to “Really…title”.
طریقه استفاده :کد PHP:
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;
}
کد PHP:
$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);
دریافت اطلاعات از یک آدرس (Get JSON data from a URL (cURL
کد PHP:
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);
}
طریقه استفاده :
کد PHP:
$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 پی اچ پی استفاده کنید.
کد PHP:
function get_json_data($json_url)
{
$json_data = file_get_contents($json_url);
return json_decode($json_data);
}
تغییر اندازه گروهی عکس ها در یک پوشه
کد PHP:
<?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;
}
}
}
?>
فعال کردن نمایش خطا در php
کد PHP:
ini_set('display_errors', 1);
error_reporting(E_ALL);
بررسی کد های مخرب و تروجان در وب سایت و ایمیل کردن کردن اطلاعات
کد PHP:
// 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);
}
تشخیص حجم فایل یک لینک
مثلا حجم یک فایل زیپ یک لینک دانلود رو که از سایت دیگه است رو مشخص میکنه
کد PHP:
<?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);
?>
حذف اولین کاراکتر از رشته:
کد PHP:
echo substr("12345678", 1); // 2345678
محاسبه تعداد فایل در دایرکتوری:
کد PHP:
$dir_path = "media/"; $wcount = count(glob("" .$dir_path. "*.jpg"));
فشرده سازی خودکار فایلهای CSS با PHP
کد 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();
?>
مثالی از نحوه استفاده :
کد PHP:
<link href="csscompress.php?css=style.css" rel="stylesheet" type="text/css"/>
تولید خودکار لینک کوتاه برای URLهای شما
کد PHP:
function getTinyUrl($url) {
return file_get_contents('http://tinyurl.com/api-create.php?url=' . $url);
}
بدست آوردن اندازه فایلها با واحد B و KB و MB و... بطور خودکار :
کد PHP:
<?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 و... رو هم میتونه استخراج کنه.
درج Overlay و Watermark بر روی تصاویر:
کد PHP:
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 بر روی تصویر اول هست!
تابعی مفید برای اینکد کردن url ها.
وقتی مفیده که بخواین مثلا از rss که لینک هاش حاوی کلمات فارسی هست، url صفحه ای رو گرفته سپس اون صفحه رو با cUrl بخواین باز کنید.
کد PHP:
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);
}
با استفاده از این تکه کد می تونید تاریخ و ساعت رو به شکل های ۲ دقیقه پیش ، ۱ ساعت و ۱۰ دقیقه پیش نمایش بدید
کد PHP:
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') ====> خروجی -> ۵ دقیقه بعد
با استفاده از کد زیر میتوانیم هر فایلی را تا تعداد999 تکه splitکنیم. در ضمن این کد قابلیت rejoinفایل های split شده را دارد.
کد PHP:
<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";
}
با استفاده از این کد می تونید خروجی اکسل بگیرید :
کد PHP:
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();
کد کردن و دیکد کردن
کد PHP:
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;
}
}
طریقه استفاده :
کد PHP:
echo encryptDecrypt('password', 'encrypt-decrypt this',0);
تولید رشته تصادفی
کد PHP:
function generateRandomString($length = 10) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLM NOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
طریقه استفاده :
کد PHP:
echo generateRandomString(20);
نمایش فهرست فایلها (شامل فایلهای با اسامی فارسی) !
شاید مشکل عدم نمایش درست اسامی فایلهای فارسی برای خیلیها دردسرساز شده باشه. این کد مشکلتون رو رفع میکنه:
کد PHP:
$files = scandir('.');
foreach($files as $file) {
echo iconv('windows-1256', 'utf-8', $file).''.PHP_EOL;
}
این هم چک کشور با ای پی :
کد PHP:
<?
// 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'];
}
HighLight کردن کدهای HTML درون متن :
کد PHP:
<?php
function highlight_html($string, $decode = TRUE){
$tag = '#0000ff';
$att = '#ff0000';
$val = '#8000ff';
$com = '#34803a';
$find = array(
'~(\s[a-z].*?=)~', // Highlight the attributes
'~(<\!--.*?-->)~s', // Hightlight comments
'~("[a-zA-Z0-9\/].*?")~', // Highlight the values
'~(<[a-z].*?>)~', // Highlight the beginning of the opening tag
'~(</[a-z].*?>)~', // Highlight the closing tag
'~(&.*?;)~', // 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 & here.</p>
<!-- This is an HTML comment -->
<form action="/login.php" method="post">
<input type="text" value="User Name" />
</form>
');
?>
یکی از کدهایی که به زحمت گیرتون میاد !!
پاک کردن کامل یک دایرکتوری به همراه تمام محتویات درونش :
کد PHP:
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;
}
تولید نقشه سایت (Site Map) :
کد PHP:
<?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);
?>
Copy a remote file to your site
کد PHP:
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;
}
}
Copy File From Server
کد PHP:
<?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.";
?>
Create Basic PDF
کد PHP:
<?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);
?>
Create a drop down menu from an array list
کد PHP:
<?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>';
?>
GD barchart demo
کد PHP:
<?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);
?>