توجه ! این یک نسخه آرشیو شده میباشد و در این حالت شما عکسی را مشاهده نمیکنید برای مشاهده کامل متن و عکسها بر روی لینک مقابل کلیک کنید : مجموعه کدهای بدرد بخور در php
djmohammad
December 17th, 2013, 00:58
با سلام خوب در این تاپیک می خوام مجموعه ای از کدهای بدرد بخور جدید رو برای شما قرار بدم
function clean_none_ascii($output) {
$output = preg_replace('/[^(x20-x7F)]*/','', $output);
return $output;
}
طریقه استفاده از کد بالا :
$output = "Clean this copy of invalid non ASCII äócharacters.";echo clean_non_ascii($output);
djmohammad
December 17th, 2013, 01:06
تجزیه رشته
function string_parser($string,$replacer)
{
$result = str_replace(array_keys($replacer), array_values($replacer),$string);
return $result;
}
طریقه استفاده :
$string = 'The {b}anchor text{/b} is the {b}actual word{/b} or words used {br}to describe the link {br}itself';
$replace_array = array('{b}' => '<b>','{/b}' => '</b>','{br}' => '');
$email_args = array('from'=>'my_email@testserver.com <mr. Sender>','to' =>'test_recipient@testgmail.com <camila>, test_recipient2@testgmail.com <anderson>','cc' =>'test_cc123_recipient@testgmail.com <christopher>, test_cc321_recipient2@testgmail.com <francisca>','subject' =>'This is my Subject Line','message' =>'<b style="color:red;">This</b> is my <b>HTML</b> message. This message will be sent using <b style="color:green;">PHP mail</b>.',); if(php_html_email($email_args)){echo 'Mail Sent';}
<!--
email - Email address in gravatar
rating - rating of Gravatar(G, PG, R, X)
size - size of gravatar
default - URL of default gravatar to use or use various options : http://j.mp/SUmEq9
-->
<img src="<?php gravatar('emailaddress@sgmail.com','G',32,'monster id'); ?>" />
djmohammad
December 17th, 2013, 01:15
اتوماتیک لینک کردن تمام آدرس ها و ایمیل ها
function autolink($message) {
//Convert all urls to links
$message = preg_replace('#([s|^])(www)#i', '$1http://$2', $message);
$pattern = '#((http|https|ftp|telnet|news|gopher|file|wais)://[^s]+)#i';
$replacement = '<a href="$1" target="_blank">$1</a>';
$message = preg_replace($pattern, $replacement, $message);
/* Convert all E-mail matches to appropriate HTML links */
$pattern = '#([0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*.';
$pattern .= '[a-wyz][a-z](fo|g|l|m|mes|o|op|pa|ro|seum|t|u|v|z)?)#i';
$replacement = '<a href="mailto:1">1</a>';
$message = preg_replace($pattern, $replacement, $message);
return $message;
}
طریقه استفاده :
$my_string = strip_tags('this http://www.cdcv.com/php_tutorial/strip_tags.php make clickable text and this email bobby23432@fakserver.com');
echo autolink($my_string);
function truncate($text, $length = 0)
{
if ($length > 0 && strlen($text) > $length) // Truncate the item text if it is too long.
{
$tmp = substr($text, 0, $length); // Find the first space within the allowed length.
$tmp = substr($tmp, 0, strrpos($tmp, ' '));
if (strlen($tmp) >= $length - 3) { // If we don't have 3 characters of room, go to the second space within the limit.
$tmp = substr($tmp, 0, strrpos($tmp, ' '));
}
$text = $tmp.'...';
}
return $text;
}
طریقه استفاده :
$string = 'The behavior will not truncate an individual word, it will find the first space that is within the limit and truncate.';
echo truncate($string,60);
djmohammad
December 19th, 2013, 04:02
خلاصه کردن یک رشته
مثال :
“Really long title” to “Really…title”.
function abridge($text, $length = 50, $intro = 30)
{
// Abridge the item text if it is too long.
if (strlen($text) > $length)
{
// Determine the remaining text length.
$remainder = $length - ($intro + 3);
// Extract the beginning and ending text sections.
$beg = substr($text, 0, $intro);
$end = substr($text, strlen($text) - $remainder);
$string = 'The behavior will not truncate an individual word, it will find the first space that is within the limit and truncate.';
echo abridge($string,60);
djmohammad
December 19th, 2013, 04:04
دریافت اطلاعات از یک آدرس (Get JSON data from a URL (cURL
if(file_exists($imagePath) && $checkValidImage) //Continue only if 2 given parameters are true
{
//Image looks valid, resize.
if(resizeImage($imagePath,$destPath,$NewImageWidth ,$NewImageHeight,$Quality))
{
echo $file.' resize Success!';
/*
Now Image is resized, may be save information in database?
*/
آرایه data رو میبایست دستی ویرایش کنید! دراینجا تصویر اول JPG و تصویر دوم PNG هستش که میتونید بنابه نیازتون توابع رو تغییر بدید!
دراصل کار اصلی این کد درج تصویر دوم بصورت Transparent بر روی تصویر اول هست!
djmohammad
December 19th, 2013, 04:18
تابعی مفید برای اینکد کردن url ها.
وقتی مفیده که بخواین مثلا از rss که لینک هاش حاوی کلمات فارسی هست، url صفحه ای رو گرفته سپس اون صفحه رو با cUrl بخواین باز کنید.
function safe_urlencode($txt){
// Skip all URL reserved characters plus dot, dash, underscore and tilde..
$result = preg_replace_callback("/[^-\._~:\/\?#\\[\\]@!\$&'\(\)\*\+,;=]+/",
function ($match) {
// ..and encode the rest!
return rawurlencode($match[0]);
}, $txt);
return ($result);
}
djmohammad
December 19th, 2013, 04:19
با استفاده از این تکه کد می تونید تاریخ و ساعت رو به شکل های ۲ دقیقه پیش ، ۱ ساعت و ۱۰ دقیقه پیش نمایش بدید
public function Timeago($time,$format='Y/m/d H:i:s'){
$now=time();
طرز استفاده هم به این صورت هست شما زمان رو به عنوان پارامتر می فرستید و تابع خروجی مناسب رو برمی گردونه
مثال
ورودی -> 1378461081 ====> خروجی -> دیروز ساعت 14:21:21
ورودی -> strtotime('-5 mins') ====> خروجی -> ۵ دقیقه پیش
ورودی -> strtotime('+5 mins') ====> خروجی -> ۵ دقیقه بعد
djmohammad
December 19th, 2013, 04:20
با استفاده از کد زیر میتوانیم هر فایلی را تا تعداد999 تکه splitکنیم. در ضمن این کد قابلیت rejoinفایل های split شده را دارد.
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;
نمایش فهرست فایلها (شامل فایلهای با اسامی فارسی) !
شاید مشکل عدم نمایش درست اسامی فایلهای فارسی برای خیلیها دردسرساز شده باشه. این کد مشکلتون رو رفع میکنه:
<?
// 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 getTheCountry(){
$ipForCo=$_SERVER['REMOTE_ADDR'];
$getCo=file_get_contents_curl('http://ip2country.sourceforge.net/ip2c.php?ip='.$ipForCo.'&format=JSON');
$json_Co=json_decoder($getCo);
return $json_Co['country_code'];
}
djmohammad
December 19th, 2013, 04:27
HighLight کردن کدهای HTML درون متن :
<?php
function highlight_html($string, $decode = TRUE){
$tag = '#0000ff';
$att = '#ff0000';
$val = '#8000ff';
$com = '#34803a';
$find = array(
'~(\s[a-z].*?=)~', // Highlight the attributes
'~(<\!--.*?-->)~s', // Hightlight comments
'~("[a-zA-Z0-9\/].*?")~', // Highlight the values
'~(<[a-z].*?>)~', // Highlight the beginning of the opening tag
'~(</[a-z].*?>)~', // Highlight the closing tag
'~(&.*?;)~', // Stylize HTML entities
);
$replace = array(
'<span style="color:'.$att.';">$1</span>',
'<span style="color:'.$com.';">$1</span>',
'<span style="color:'.$val.';">$1</span>',
'<span style="color:'.$tag.';">$1</span>',
'<span style="color:'.$tag.';">$1</span>',
'<span style="font-style:italic;">$1</span>',
);
if($decode)
$string = htmlentities($string);
return '<pre>'.preg_replace($find, $replace, $string).'</pre>';
}
echo highlight_html('
<!-- This is an
HTML comment -->
<a href="home.html" style="color:blue;">Home</a>
<p>Go & here.</p>
<!-- This is an HTML comment -->
<form action="/login.php" method="post">
<input type="text" value="User Name" />
</form>
');
?>
djmohammad
December 19th, 2013, 04:28
یکی از کدهایی که به زحمت گیرتون میاد !!
پاک کردن کامل یک دایرکتوری به همراه تمام محتویات درونش :
function full_delete($path)
{
$realPath = realpath($path);
if (!file_exists($realPath))
return false;
$DirIter = new RecursiveDirectoryIterator($realPath);
$fileObjects = new RecursiveIteratorIterator($DirIter, RecursiveIteratorIterator::CHILD_FIRST);
foreach ($fileObjects as $name => $fileObj) {
if ($fileObj->isDir())
rmdir($name);
else
unlink($name);
}
rmdir($realPath);
return true;
}
djmohammad
December 19th, 2013, 04:29
تولید نقشه سایت (Site Map) :
<?php
// Please edit these values before running your script.
// The Url of the site - the last '/' is needed
$url = 'http://localhost/mycms/';
// Where the root of the site is with relation to this file.
$root_dir = '../mycms';
// Allowed extensions to consider in sitemap
$extensions = array(
'htm',
'html',
'php'
);
// Stuff to be ignored...
// Ignore the file/folder if these words appear anywhere in the name
$always_ignore = array(
'.inc',
'admin',
'image'
);
//These files will not be linked in the sitemap.
$ignore_files = array(
'404.php',
'error.php',
'config.php',
'include.inc'
);
//The script will not enter these folders
$ignore_dirs = array(
'.svn',
'admin',
'css',
'cvs',
'images',
'inc',
'includes',
'js',
'lib',
'stats',
'styles',
'system',
'uploads'
);
// Stop editing now - Configurations are over !
// Values from array 1
PRINT '<select name="Words">';
// for each value of the array assign a variable name word
FOREACH($ddArray1 AS $word){
PRINT '<option value="'.$word.'">'.$word.'</option>';
}
PRINT '</select>';
//Values from array 2
PRINT '<select name="Words">';
// for each key of the array assign a variable name $let
// for each value of the array assign a variable name $word
FOREACH($ddArray2 AS $let=>$word){
PRINT '<option value="'.$let.'">'.$word.'</option>';
}
PRINT '</select>';
?>
djmohammad
December 19th, 2013, 04:35
GD barchart demo
<?PHP
// bars.php3 - Bar chart on gif image
// Note: uses the gd library
// This code will display a bar chart based on random values
// Different colors are used to display bars and a gif images
// is used for the background. Use the following link to include
// the example into your web-site
// <img src="./bars.php3" border="0">
//
// The background image can be found at
/*
* Displays, recursively, the contents of a tree given a starting
* point.
*
* Parameters:
* $parent - the parent node (not listed in the directory). Node
* 0 is the root node.
*
* $maxdepth (optional) - maximum number of recursion levels. -1
* (the default value) means no limits.
*
* $ancestors (optional) - an array of the ancestor nodes in the
* current branch of the tree, with the node closest to the
* top at index 0.
*
* Global variables used:
* $child_nodes
* $node_data
* $last_child
*
* Global variables modified:
* The array pointers in $child_nodes will be modified.
*/
FUNCTION display_directory($parent, $showdepth = 0, $ancestors = FALSE) {
GLOBAL $child_nodes, $node_data, $last_child;
RESET($child_nodes[$parent]);
$size = SIZEOF($child_nodes[$parent]);
$lastindex = $size - 1;
IF (!$ancestors) {
$ancestors = ARRAY();
}
$depth = SIZEOF($ancestors);
PRINTF( '<div id="node_%d" class="dirEntry" visibility="%s">',
$parent, $showdepth > 0 ? 'show' : 'hide');
WHILE (LIST($index, $node) = EACH($child_nodes[$parent])) {
/*
For each of the uptree nodes:
If an uptree node is not the last one on its depth
of the branch, there should be a line instead of a blank
before this node's icon.
*/
FOR ($i = 0; $i < $depth; $i++) {
$up_parent = (int)$node_data[$ancestors[$i]][ 'parent'];
$last_node_on_generation = $last_child[$up_parent];
$uptree_node_on_generation = $ancestors[$i];
IF ($last_node_on_generation == $uptree_node_on_generation) {
icon( "blank");
} ELSE {
icon( "line");
}
}
IF ($child_nodes[$node]) { // has children, i.e. it is a folder
$conn_icon = "plus";
$expand = TRUE;
} ELSE {
$conn_icon = "join";
$expand = FALSE;
}
IF ($index == $lastindex) {
$conn_icon .= "bottom";
} ELSEIF ($depth == 0 && $index == 0) {
$conn_icon .= "top";
}
IF ($expand) {
PRINTF( "<a href=\"javascript<b></b>:document.layers['node_%d'].visibility='show'\">", $node);
}
icon($conn_icon, "connImg_$node");
IF ($expand) {
PRINT( "</a>");
}
$icon = $node_data[$node][ 'icon'];
IF (!$icon) {
$type = $node_data[$node][ 'type'];
$icon = $GLOBALS[ 'dirent_icons'][$type];
}
icon($icon, "nodeImg_$node");
$name = $node_data[$node][ 'name'];
PRINTF( '?<font size="%d">%s</font><br%c>', -1, $name, 10);
IF ($child_nodes[$node]) {
$newdepth = $showdepth;
IF ($newdepth > 0) {
$newdepth--;
}
$new_ancestors = $ancestors;
$new_ancestors[] = $node;
display_directory($node, $newdepth, $new_ancestors);
}
}
PRINT( "</div\n>");
}
FUNCTION setup_directory($parent, $maxdepth)
{
GLOBAL $dirent_icons, $child_nodes, $node_data, $last_child;
$dirent_icons = sql_assoc( 'SELECT id,icon FROM dirent_types');
$query = 'SELECT id,parent,type,icon,name '.
'FROM directory '.
'ORDER BY parent,name';
$child_nodes = ARRAY();
$node_data = ARRAY();
$res = sql($query);
WHILE (LIST($id, $parent, $type, $icon, $name) = db_fetch_row($res)) {
$child_nodes[(int)$parent][] = $id;
$node_data[$id] = ARRAY( 'id' => $id,
'parent' => $parent,
'type' => $type,
'icon' => $icon,
'name' => $name);
$last_child[(int)$parent] = $id;
}
}
?>
// convert a date into a string that tells how long
// ago that date was.... eg: 2 days ago, 3 minutes ago.
FUNCTION ago($d) {
$c = GETDATE();
$p = ARRAY('year', 'mon', 'mday', 'hours', 'minutes', 'seconds');
$display = ARRAY('year', 'month', 'day', 'hour', 'minute', 'second');
$factor = ARRAY(0, 12, 30, 24, 60, 60);
$d = datetoarr($d);
FOR ($w = 0; $w < 6; $w++) {
IF ($w > 0) {
$c[$p[$w]] += $c[$p[$w-1]] * $factor[$w];
$d[$p[$w]] += $d[$p[$w-1]] * $factor[$w];
}
IF ($c[$p[$w]] - $d[$p[$w]] > 1) {
RETURN ($c[$p[$w]] - $d[$p[$w]]).' '.$display[$w].'s ago';
}
}
RETURN '';
}
// you can replace this if need be. This converts the dates
// returned from a mysql date string into an array object similar
// to that returned by getdate().
FUNCTION datetoarr($d) {
PREG_MATCH("/([0-9]{4})(\\-)([0-9]{2})(\\-)([0-9]{2}) ([0-9]{2})(\\:)([0-9]{2})(\\:)([0-9]{2})/", $d, $matches);
RETURN ARRAY(
'seconds' => $matches[10],
'minutes' => $matches[8],
'hours' => $matches[6],
'mday' => $matches[5],
'mon' => $matches[3],
'year' => $matches[1],
);
}
?>
djmohammad
December 19th, 2013, 04:40
Output as Word Doc format
<?PHP
$query = "SELECT * FROM TABLE WHERE data = '$data'";
// 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;
?>
// If you are using PHP4 then you need to use this code:
// (because the "ftp_chmod" command is just available in PHP5+)
if (!function_exists('ftp_chmod')) {
function ftp_chmod($ftp_stream, $mode, $filename){
return ftp_site($ftp_stream, sprintf('CHMOD %o %s', $mode, $filename));
}
}
// try to chmod the new file to 666 (writeable)
if (ftp_chmod($conn_id, 0666, $ftp_path) !== false) {
print $ftp_path . " chmoded successfully to 666\n";
} else {
print "could not chmod $file\n";
}
// close the FTP stream
ftp_close($conn_id);
?>
djmohammad
December 19th, 2013, 04:51
جداسازی اعداد از رشته :
<?php
// extract numbers from a string
// http://php.snippetdb.com
$string = "The 1. Quick and 2. Brown fox said 3. (!@*(#!@*";
یک فانکشن خیلی خیلی باحال ! تولید متن رنگارنگ (منظور موج رنگها) :
<?
//simple to use!
echo fadeText('ff0000','0000ff','this is the text that will be faded!');
function getColor($startc, $endc, $percentc)
{
$r1=hexdec(substr($startc,-6,2));
$g1=hexdec(substr($startc,-4,2));
$b1=hexdec(substr($startc,-2,2));
<?php
// example HTML code: (could also come from an URL)
$html = '<html>
<head>
<title>links</title>
</head>
<body>
<a href="link1.htm" title="Link title 1" target="_blank">Link #1</a>
<a href="link2.htm" title="Link title 2" target="_blank">Link #2</a>
<a href="link3.htm" title="Link title 3" target="_blank">Link #3</a>
</body>
</html>';
// check if DomXML is available:
if (!function_exists('DomDocument')){
die('DomXML extension is not available :-(');
}
print '<pre>';
// create new DOM object:
$dom = new DomDocument();
// load HTML code:
$dom->loadHtml($html);
// get tags by tagname (all <a> tags / links):
$tags = $dom->getElementsByTagName('a');
// loop trough all links:
foreach ($tags as $a){
print '<b>' . $a->nodeValue . '</b>';
// does this tag have attributes:
if ($a->hasAttributes()){
یک مثال ساده برای تولید پیج داینامیک بوسیله لینکها و Mysql :
<!---------------------------------- Change File name To links.php -------------------->
<!-- links.php -->
<a href="links.php?id=1">File 1</a>
<a href="links.php?id=2">File 2</a>
<a href="links.php?id=3">File 3</a>
<?php
// Load the database connections
include 'db.php';
//check to see if one of the links were clicked
echo '<div>';
if(isset($_GET['id'])){
// Make a safe string
$id = mysql_real_escape_string($_GET['id']);
// Query the database
$sql = mysql_query("SELECT * FROM table_name WHERE id='$id'");
if(mysql_num_rows($sql) == 1){
// If one row was found, create an array of the row
$row = mysql_fetch_array($sql);
// echo the column 'content' (change 'content' to your column name)
echo '<p>'.$row['content'].'</p>';
}else{
// Row was not found
echo '<p>File Not Found.</p>';
}
}else{
// the id parameter in the url was not set
echo '<p>Invalid URL.</p>';
}
echo '</div>';
?>
(با فرض اینکه کد فوق رو به اسم pim.php ذخیره کرده باشین).
کاربرد اصلی این اسکریپت برای وقتی هست که میخواین یک تصویر رو بصورت تکه تکه نشون بدین و با CSS تنظیم کنید تا کنار هم ظاهر بشه. دیگه نیازی نیست توی Photoshop یا سایر برنامه ها تصویر رو برش بدین و توی فایلهای جداگانه ذخیره کنید و در فضای هاست هم صرفه جویی میشه چون برای هر فایل جداگانه، هدرهای تصویر ذخیره میشن و این یعنی تکرار هدرها. کد فوق رو با کمی تغییر میتونید برای سایر انواع تصویر مثل png و... هم استفاده کنید.
موفق باشید.
<?php
// This will return a number of how many more characters the longest string has
function str_compare_length($str1, $str2){
$len1 = strlen($str1);
$len2 = strlen($str2);
if($str1 > $str2){
return $len1 - $len2;
}else{
return $len2 - $len1;
}
}
echo str_compare_length("This is the first string", "This is the second string");
?>
djmohammad
June 23rd, 2014, 02:13
با سلام
امروز می خواهم کدی را به شما معرفی کنم که با اون می تونید معین کنید که کاربری که لاگین کرده به سایت در صورتی که طی زمان خاصی فعالیتی در سایت انجام ندهد آن را logout کنیم ....
//توسط : محمد عبدالهی
//Host5.ir
<?php
# Start a session
session_start();
# Check if a user is logged in
function isLogged(){
if($_SESSION['logged']){ # When logged in this variable is set to TRUE
return TRUE;
}else{
return FALSE;
}
}
# Log a user Out
function logOut(){
$_SESSION = array();
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
session_destroy();
}
# Session Logout after in activity
function sessionX(){
$logLength = 1800; # time in seconds :: 1800 = 30 minutes
$ctime = strtotime("now"); # Create a time from a string
# If no session time is created, create one
if(!isset($_SESSION['sessionX'])){
# create session time
$_SESSION['sessionX'] = $ctime;
}else{
# Check if they have exceded the time limit of inactivity
if(((strtotime("now") - $_SESSION['sessionX']) > $logLength) && isLogged()){
# If exceded the time, log the user out
logOut();
# Redirect to login page to log back in
header("Location: /login.php");
exit;
}else{
# If they have not exceded the time limit of inactivity, keep them logged in
$_SESSION['sessionX'] = $ctime;
}
}
}
# Run Session logout check
sessionX();
?>