-
پاسخ : مجموعه کدهای بدرد بخور در 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
*/
?>
-
پاسخ : مجموعه کدهای بدرد بخور در php
Whois با PHP :
کد 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;
}
?>
-
پاسخ : مجموعه کدهای بدرد بخور در php
فرستادن خطاهای PHP به ایمیل شما بجای نمایش در صفحه:
کد 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
آپلود فایل در FTP :
کد PHP:
<?php
// FTP access parameters
$host = 'ftp.example.org';
$usr = 'example_user';
$pwd = 'example_password';
// file to move:
$local_file = './example.txt';
$ftp_path = '/data/example.txt';
// connect to FTP server (port 21)
$conn_id = ftp_connect($host, 21) or die ("Cannot connect to host");
// send access parameters
ftp_login($conn_id, $usr, $pwd) or die("Cannot login");
// turn on passive mode transfers (some servers need this)
// ftp_pasv ($conn_id, true);
// perform file upload
$upload = ftp_put($conn_id, $ftp_path, $local_file, FTP_ASCII);
// check upload status:
print (!$upload) ? 'Cannot upload' : 'Upload complete';
print "\n";
/*
** Chmod the file (just as example)
*/
// 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);
?>
-
پاسخ : مجموعه کدهای بدرد بخور در php
جداسازی اعداد از رشته :
کد PHP:
<?php
// extract numbers from a string
// http://php.snippetdb.com
$string = "The 1. Quick and 2. Brown fox said 3. (!@*(#!@*";
$new_string = ereg_replace("[^0-9]", "", $string);
echo $new_string;
?>
-
پاسخ : مجموعه کدهای بدرد بخور در php
یک فانکشن خیلی خیلی باحال ! تولید متن رنگارنگ (منظور موج رنگها) :
کد PHP:
<?
//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));
$r2=hexdec(substr($endc,-6,2));
$g2=hexdec(substr($endc,-4,2));
$b2=hexdec(substr($endc,-2,2));
$pcc = $percentc/100;
$rcc= ($r1+($pcc*($r2-$r1)))*1;
$gcc= ($g1+($pcc*($g2-$g1)))*1;
$bcc= ($b1+($pcc*($b2-$b1)))*1;
$frc= dechex($rcc);
$fgc= dechex($gcc);
$fbc= dechex($bcc);
if (strlen($frc)=="1"){
$frc="0".$frc;
}
if (strlen($fgc)=="1"){
$fgc="0".$fgc;
}
if (strlen($fbc)=="1"){
$fbc="0".$fbc;
}
$dasclr="#".$frc."".$fgc."".$fbc;
return $dasclr;
}
function fadeText($start, $end, $msg)
{
$myString2Fade = $msg;
$endResult="";
$daslen=strlen($myString2Fade);
for ($i=0 ; $i<$daslen ; $i++){
$perc=(100/$daslen)*$i;
if ($myString2Fade[$i]==" "){
$endResult="$endResult ";
} else {
$endResult="$endResult<font color='".getColor($start, $end, $perc)."'>".$myString2Fade[$i]."</font>";
}
}
return $endResult;
}
?>
-
پاسخ : مجموعه کدهای بدرد بخور در php
یک مثال برای DOM :
کد PHP:
<?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()){
// loop trough all attributes:
foreach ($a->attributes as $attribute){
print '- ' . $attribute->name . ': ' . $attribute->value;
print "";
}
}
print "<hr/>";
}
print '</pre>';
?>
-
پاسخ : مجموعه کدهای بدرد بخور در php
یک مثال ساده برای تولید پیج داینامیک بوسیله لینکها و Mysql :
کد PHP:
<!---------------------------------- 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>';
?>
-
پاسخ : مجموعه کدهای بدرد بخور در php
نمایش بخشی از تصویر
کد PHP:
<?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);
?>
نحوه استفاده :
کد PHP:
<img src="pim.php?file=image.jpg&x1=50&y1=50&x2=200&y2=100"/>
(با فرض اینکه کد فوق رو به اسم pim.php ذخیره کرده باشین).
کاربرد اصلی این اسکریپت برای وقتی هست که میخواین یک تصویر رو بصورت تکه تکه نشون بدین و با CSS تنظیم کنید تا کنار هم ظاهر بشه. دیگه نیازی نیست توی Photoshop یا سایر برنامه ها تصویر رو برش بدین و توی فایلهای جداگانه ذخیره کنید و در فضای هاست هم صرفه جویی میشه چون برای هر فایل جداگانه، هدرهای تصویر ذخیره میشن و این یعنی تکرار هدرها. کد فوق رو با کمی تغییر میتونید برای سایر انواع تصویر مثل png و... هم استفاده کنید.
موفق باشید.
-
پاسخ : مجموعه کدهای بدرد بخور در php
Backup گرفتن از دیتابیس
کد PHP:
<?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);
}
?>
مثالی از نحوه استفاده از تابع بالا :
کد PHP:
backup_db('localhost', 'root', '', 'your_db_name');
-
پاسخ : مجموعه کدهای بدرد بخور در php
جداسازی آدرس ها از متن و تبدیل به لینک :
کد PHP:
<?php
function to_link($string){
return preg_replace("~(http|https|ftp|ftps)://(.*?)(\s|\n|[,.?!](\s|\n)|$)~", '<a href="$1://$2">$1://$2</a>$3',$string);
}
$html = 'This line of text has three urls: http://webhostingtalk.ir http://yahoo.com and http://google.com';
echo to_link($html, TRUE);
?>
-
پاسخ : مجموعه کدهای بدرد بخور در php
سازنده تگ (Tag Builder)
کد PHP:
<?php
function buildTag($tag, $att = array(), $selfColse = FALSE, $inner = ''){
$t = '<'.$tag.' ';
foreach($att as $k => $v){
$t .= $k.'="'.$v.'"';
}
if(!$selfColse)
$t .= '>';
else
$t .= ' />';
if(!$selfColse)
$t .= $inner.'</'.$tag.'>';
return $t;
}
// Example 1:
echo buildTag('input', array('type'=>'button', 'value'=>'WOOT!'), TRUE);
// Example 2:
echo buildTag('div', array('style'=>'border:solid 1px #000'), FALSE, buildTag('a', array('href'=>'http://google.com'), FALSE, 'Google'));
?>
-
پاسخ : مجموعه کدهای بدرد بخور در php
کوتاه کردن متن و بستن تگهای بسته نشده !
کد PHP:
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;
}
}
?>
-
پاسخ : مجموعه کدهای بدرد بخور در php
برگرداندن همه ی مقادیر تکرار شده در یک آرایه
کد PHP:
<?php
function array_repeated($array){
if (!is_array($array))
return false;
$repeated_values = Array();
$array_unique = array_unique($array);
if (count($array) - count($array_unique)){
for ($i=0; $i<count($array); $i++)
{
if (!array_key_exists($i, $array_unique))
$repeated_values[] = $array[$i];
}
}
return $repeated_values;
}
?>
-
پاسخ : مجموعه کدهای بدرد بخور در php
جداسازی درخواست AJAX .. مثلا اگه کسی بوسیله AJAX درخواست را ارسال کرد یک عمل دیگه انجام بشه
کد PHP:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
//If AJAX Request Then
}else{
//something else
}
-
پاسخ : مجموعه کدهای بدرد بخور در php
مقایسه ی دو String
کد PHP:
<?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");
?>
-
خارج کردن کاربر در صورتی که طی زمان خاصی فعالیتی نداشته باشد
با سلام
امروز می خواهم کدی را به شما معرفی کنم که با اون می تونید معین کنید که کاربری که لاگین کرده به سایت در صورتی که طی زمان خاصی فعالیتی در سایت انجام ندهد آن را logout کنیم ....
کد PHP:
//توسط : محمد عبدالهی
//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();
?>