حذف پسوند فایل
function RemoveExtension($strName)
{
$ext = strrchr($strName, '.');
if($ext !== false)
{
$strName = substr($strName, 0, -strlen($ext));
}
return $strName;
}
طریقه استفاده
echo RemoveExtension('myfile.ho');
بله
خير
حذف پسوند فایل
function RemoveExtension($strName)
{
$ext = strrchr($strName, '.');
if($ext !== false)
{
$strName = substr($strName, 0, -strlen($ext));
}
return $strName;
}
طریقه استفاده
echo RemoveExtension('myfile.ho');
بدست آردن اندازه فایل
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);
حذف کاراکترهای غیر 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);
تجزیه رشته
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}' => '<br />');
echo string_parser($string,$replace_array);
ارسال ایمیل با بدنه 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 <frabarnamenevisca>',
'subject' =>'This is my Subject Line',
'message' =>'<b style="color:red;">This</b> is my <b>HTML</b> message. <br />This message will be sent using <b style="color:green;">PHP mail</b>.',
);
if(php_html_email($email_args)){
echo 'Mail Sent';
}
فهرست فایلها در یک دایرکتوری
function listDirFiles($DirPath)
{
if($dir = opendir($DirPath)){
while(($file = readdir($dir))!== false){
if(!is_dir($DirPath.$file))
{
echo "filename: $file<br />";
}
}
}
}
طریقه استفاده
listDirFiles('home/some_folder/');
قرار دادن گراواتار شخصی در سایت خود
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;
}
طریقه استفاده
<!--
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'); ?>" />
اتوماتیک لینک کردن تمام آدرس ها و ایمیل ها
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);
گرفتن آدرس خروجی از صفحه فعلی
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();
تابعی برای دانلود فایل
function download($file_path)
{
if ((isset($file_path))&&(file_exists($file_path)))
{
header("Content-length: ".filesize($file_path));
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $file_path . '"');
readfile("$filename");
} else {
echo "Looks like file does not exist!";
}
}
طریقه استفاده
download('/home/this/folder/2914654828_45f73e852.zip')
آخرین ویرایش به وسیله soroush.r70 : جمعه 26 مهر 1392 در 22:42 عصر
کوتاه کردن متن های طولانی
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);
خلاصه کردن یک رشته
مثال :
“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);
دریافت اطلاعات از یک آدرس (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);
}
تغییر اندازه گروهی عکس ها در یک پوشه
<?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!<br />';
/*
Now Image is resized, may be save information in database?
*/
}else{
echo $file.' resize Failed!<br />';
}
}
}
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
ini_set('display_errors', 1);
error_reporting(E_ALL);
بررسی کد های مخرب و تروجان در وب سایت و ایمیل کردن کردن اطلاعات
// 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 باید 5.4.0 و یا بالاتر باشه
کلاس و نمونه کد ضمیمه شد
کاهش حجم فایلهای تصویری به اندازه دلخواه
این کد رو میتونید برحسب نیازتون، کاملتر کنید و برای مثال، با توجه به نوع فرمت (PNG و...) از توابع مناسب برای خوندن و ذخیره کردن تصویر استفاده کنید:
function Resize($file, $size) {
if(!file_exists($file)) {
return;
}
$im = ImageCreateFromJPEG($file);
$quality = 100;
do {
ImageJPEG($im, $file, $quality--);
} while(filesize($file) > $size && $quality > 0);
ImageDestroy($im);
}
برای تغییر سایز رو بقیه چیزها من از این کلاس ساده استفاده میکنم. برای تمام فرمتها هم کار میکنه.
/*
* Author: Simon Jarvis
*/
class SimpleImage {
var $image;
var $image_type;
function load($filename) {
$image_info = getimagesize($filename);
$this->image_type = $image_info[2];
if( $this->image_type == IMAGETYPE_JPEG ) {
$this->image = imagecreatefromjpeg($filename);
} elseif( $this->image_type == IMAGETYPE_GIF ) {
$this->image = imagecreatefromgif($filename);
} elseif( $this->image_type == IMAGETYPE_PNG ) {
$this->image = imagecreatefrompng($filename);
}
}
function save($filename, $image_type=IMAGETYPE_JPEG, $compression=75, $permissions=null) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image,$filename,$compression);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image,$filename);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image,$filename);
}
if( $permissions != null) {
chmod($filename,$permissions);
}
}
function output($image_type=IMAGETYPE_JPEG) {
if( $image_type == IMAGETYPE_JPEG ) {
imagejpeg($this->image);
} elseif( $image_type == IMAGETYPE_GIF ) {
imagegif($this->image);
} elseif( $image_type == IMAGETYPE_PNG ) {
imagepng($this->image);
}
}
function getWidth() {
return imagesx($this->image);
}
function getHeight() {
return imagesy($this->image);
}
function resizeToHeight($height) {
$ratio = $height / $this->getHeight();
$width = $this->getWidth() * $ratio;
$this->resize($width,$height);
}
function resizeToWidth($width) {
$ratio = $width / $this->getWidth();
$height = $this->getheight() * $ratio;
$this->resize($width,$height);
}
function scale($scale) {
$width = $this->getWidth() * $scale/100;
$height = $this->getheight() * $scale/100;
$this->resize($width,$height);
}
function resize($width,$height) {
$new_image = imagecreatetruecolor($width, $height);
imagecopyresampled($new_image, $this->image, 0, 0, 0, 0, $width, $height, $this->getWidth(), $this->getHeight());
$this->image = $new_image;
}
}
گرفتن عکس از صفحه اول یک سایت و ذخیره بر روی هاست یا سیستم خود
function takeImage($url,$dir){
$name = rand(0,9988987);
$address = "http://api.webthumbnail.org?width=500&height=400&screen=1 024&url=".$url;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$address);
$fp = fopen($dir.$name.'.png', 'w');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_exec ($ch);
curl_close ($ch);
fclose($fp);
}
takeImage("https://barnamenevis.org/" ,"./");
سلام
اینم کلاس Helper که چندتا متد بدردبخور داره.
لیست متدها:
- resizeImage تغییر سایز عکس (jpeg, png, gif)
- fa2en تبدیل اعداد فارسی به انگلیسی
- getLocation پیدا کردن موقعیت کاربر توسط IP
- متد zip که Direcotry های تو در تو را هم پشتیبانی میکنه
- copyDirectory همانطور که از اسمش معلومه یک فولدر رو از مبدا به مقصد کپی میکنه (recursive)
- removeDirectoryحذف فولدر یا فولدرهای تو در تو رو به همراه فایل ها
تغییر برچسب زمانی (Timestamp) و عقب/جلو کشیدن اون به تعداد سال، ماه، روز، ساعت، دقیقه، ثانیه - بصورت هجری شمسی
چند وقته میبینم دوستان توی تالار مشکلات زیادی توی محاسبه و ویرایش تاریخهای شمسی دارن. یکی از اونها که خیلی هم رایج هست اینه که میخوان به یه تاریخ مشخصی (درواقع به یک Timestamp مشخص) تعداد سال و ماه و روز و ساعت و دقیقه و ثانیه دلخواه رو اضافه یا ازش کم کنن و این موضوع با احتساب روزهای تقویم شمسی محاسبه بشه. مثلاً اگه میخوان 5 ماه اضافه کنن و اون سال کبیسه است و اسفند هم توی ماههایی که قراره اضافه بشه وجود داره، به اسفند که رسیدن، 30 روز اضافه بشه. این شد که تصمیم گرفتم با کمک کتابخانه JDF یک تابع مفید برای اینکار بنویسم. اینم از تابع:
function changeTimestamp($ts, $years = 0, $months = 0, $days = 0, $hours = 0, $minutes = 0, $seconds = 0) {
require_once 'jdf.php'; // download from http://jdf.scr.ir
// add/subtract years
$operator = ($years < 0 ? -1 : 1);
$years = abs($years);
while($years > 0) {
$daysOfCurrentYear = (tr_num(jdate('L'), $ts) ? 365 : 366);
$ts += ($daysOfCurrentYear * 86400 * $operator);
$years--;
}
// add/subtract months
$operator = ($months < 0 ? -1 : 1);
$months = abs($months);
while($months > 0) {
$daysOfCurrentMonth = tr_num(jdate('t', $ts);
$ts += ($daysOfCurrentMonth * 86400 * $operator);
$months--;
}
// add/subtract days
$operator = ($days < 0 ? -1 : 1);
$days = abs($days);
while($days > 0) {
$ts += (86400 * $operator);
$days--;
}
// add/subtract hours
$ts += ($hours * 3600);
// add/subtract minutes
$ts += ($minutes * 60);
// add/subtract seconds
$ts += $seconds;
return $ts;
}
مزیت این تابع اینه که میتونید با اعداد منفی، زمان به عقب بکشین و با کمک اعداد مثبت، به جلو بیارین. برای مثال، اگه میخواین بدونین یک ماه قبل، دو ساعت و نیم جلوتر از الان، چه Timestamp داشته، اینطوری از تابع فوق استفاده میکنید:
$ts = changeTimestamp(time(), 0, -1, 0, 2, 30, 0);
امیدوارم این کد هم مثل بقیه کدها به درد دوستان بخوره.