پاسخ : مجموعه کدهای بدرد بخور در php
Find days between dates #1
کد PHP:
<?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."";
?>
پاسخ : مجموعه کدهای بدرد بخور در php
Graphical tree like Explorer
کد PHP:
<?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<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;
}
}
?>
پاسخ : مجموعه کدهای بدرد بخور در php
Handy SORT BY box+No SQL INjection
کد PHP:
<?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>
پاسخ : مجموعه کدهای بدرد بخور در php
How many days ago
کد PHP:
<?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],
);
}
?>
پاسخ : مجموعه کدهای بدرد بخور در php
Output as Word Doc format
کد PHP:
<?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;
?>
پاسخ : مجموعه کدهای بدرد بخور در php
Perfect Highlighting Function
کد PHP:
<?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;
}
?>
پاسخ : مجموعه کدهای بدرد بخور در php
تابع preg برای حروف فارسی
کد PHP:
<?php
preg_match("/[\x{0600}-\x{06FF}\x]{1,32}/u", 'محمد عبدالهی');
?>
پاسخ : مجموعه کدهای بدرد بخور در php
تشخیص موقعیت از روی IP :
کد PHP:
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;
}
}
پاسخ : مجموعه کدهای بدرد بخور در php
تعداد طرفداران صفحه شما در FaceBook :
کد PHP:
<?php
function fb_fan_count($facebook_name) {
// Example: https://graph.facebook.com/host5.ir
$data = json_decode(file_get_contents("https://graph.facebook.com/".$facebook_name));
echo $data->likes;
}
?>
پاسخ : مجموعه کدهای بدرد بخور در php
مشاهده میزان حافظه مصرفی اسکریپت شما:
کد PHP:
<?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
*/
?>