MultiCurl class * @author Vadym Timofeyev <[email protected]> http://weblancer.net/users/tvv/ * @copyright 2007-2010 Vadym Timofeyev * @license http://www.gnu.org/licenses/lgpl-3.0.txt * @version 1.07 * @since PHP 5.0 * @example examples/example.php How to use MultiCurl class library. MultiCurl.class.php PHP: <?php /** * MultiCurl class provides a convenient way to execute parallel HTTP(S) * requests via PHP MULTI CURL extension with additional restrictions. * For example: start 100 downloads with 2 parallel sessions, and get only * first 100 Kb per session. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3.0 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * @author Vadym Timofeyev <[email protected]> http://weblancer.net/users/tvv/ * @copyright 2007-2010 Vadym Timofeyev * @license http://www.gnu.org/licenses/lgpl-3.0.txt * @version 1.07 * @since PHP 5.0 * @example examples/example.php How to use MultiCurl class library. */ abstract class MultiCurl { /** * Maximal number of CURL multi sessions. Default: 10 sessions. * * @var integer */ private $maxSessions = 10; /** * Maximal size of downloaded content. Default: 10 Mb (10 * 1024 * 1024). * * @var integer */ private $maxSize = 10485760; /** * Common CURL options (used for all requests). * * @var array */ private $curlOptions; /** * Current CURL multi sessions. * * @var array */ private $sessions = array(); /** * Class constructor. Setup primary parameters. * * @param array $curlOptions Common CURL options. */ public function __construct($curlOptions = array()) { $this->setCurlOptions($curlOptions); } /** * Class destructor. Close opened sessions. */ public function __destruct() { foreach ($this->sessions as $i => $sess) { $this->destroySession($i); } } /** * Adds new URL to query. * * @param mixed $url URL for downloading. * @param array $curlOptions CURL options for current request. */ public function addUrl($url, $curlOptions = array()) { // Check URL if (!$url) { throw new Exception('URL is empty!'); } // Check array of URLs if (is_array($url)) { foreach ($url as $s) { $this->addUrl($s, $curlOptions); } return; } // Check query while (count($this->sessions) == $this->maxSessions) { $this->checkSessions(); } // Init new CURL session $ch = curl_init($url); foreach ($this->curlOptions as $option => $value) { curl_setopt($ch, $option, $value); } foreach ($curlOptions as $option => $value) { curl_setopt($ch, $option, $value); } // Init new CURL multi session $mh = curl_multi_init(); curl_multi_add_handle($mh, $ch); $this->sessions[] = array($mh, $ch, $url); $this->execSession(array_pop(array_keys($this->sessions))); } /** * Waits CURL milti sessions. */ public function wait() { while (count($this->sessions)) { $this->checkSessions(); } } /** * Executes all active CURL multi sessions. */ protected function checkSessions() { foreach ($this->sessions as $i => $sess) { if (curl_multi_select($sess[0]) != -1) { $this->execSession($i); } } } /** * Executes CURL multi session, check session status and downloaded size. * * @param integer $i A session id. */ protected function execSession($i) { list($mh, $ch) = $this->sessions[$i]; while (($mrc = curl_multi_exec($mh, $act)) == CURLM_CALL_MULTI_PERFORM); if (!$act || $mrc != CURLM_OK || curl_getinfo($ch, CURLINFO_SIZE_DOWNLOAD) >= $this->maxSize) { $this->closeSession($i); } } /** * Closes session. * * @param integer $i A session id. */ protected function closeSession($i) { list(, $ch, $url) = $this->sessions[$i]; $content = !curl_error($ch) ? curl_multi_getcontent($ch) : null; $info = curl_getinfo($ch); $this->destroySession($i); $this->onLoad($url, $content, $info); } /** * Destroys session. * * @param integer $i A session id. */ protected function destroySession($i) { list($mh, $ch,) = $this->sessions[$i]; curl_multi_remove_handle($mh, $ch); curl_close($ch); curl_multi_close($mh); unset($this->sessions[$i]); } /** * Gets maximal number of CURL multi sessions. * * @return integer Maximal number of CURL multi sessions. */ public function getMaxSessions() { return $this->maxSessions; } /** * Sets maximal number of CURL multi sessions. * * @param integer $maxSessions Maximal number of CURL multi sessions. */ public function setMaxSessions($maxSessions) { if ((int)$maxSessions <= 0) { throw new Exception('Max sessions number must be bigger then zero!'); } $this->maxSessions = (int)$maxSessions; } /** * Gets maximal size limit for downloaded content. * * @return integer Maximal size limit for downloaded content. */ public function getMaxSize() { return $this->maxSize; } /** * Sets maximal size limit for downloaded content. * * @param integer $maxSize Maximal size limit for downloaded content. */ public function setMaxSize($maxSize) { if ((int)$maxSize <= 0) { throw new Exception('Max size limit must be bigger then zero!'); } $this->maxSize = (int)$maxSize; } /** * Gets CURL options for all requests. * * @return array CURL options. */ public function getCurlOptions() { return $this->curlOptions; } /** * Sets CURL options for all requests. * * @param array $curlOptions CURL options. */ public function setCurlOptions($curlOptions) { if (!array_key_exists(CURLOPT_FOLLOWLOCATION, $curlOptions)) { $curlOptions[CURLOPT_FOLLOWLOCATION] = 1; } $curlOptions[CURLOPT_RETURNTRANSFER] = 1; $this->curlOptions = $curlOptions; } /** * OnLoad callback event. * * @param string $url URL for downloading. * @param string $content Downloaded content. * @param array $info CURL session information. */ protected abstract function onLoad($url, $content, $info); /** * Checks CURL extension, etc. */ public static function checkEnvironment() { if (!extension_loaded('curl')) { throw new Exception('CURL extension not loaded'); } } } example.php PHP: <?php include_once '../MultiCurl.class.php'; class MyMultiCurl extends MultiCurl { protected function onLoad($url, $content, $info) { print "[$url] $content "; print_r($info); } } try { $mc = new MyMultiCurl(); $mc->setMaxSessions(2); // limit 2 parallel sessions (by default 10) $mc->setMaxSize(10240); // limit 10 Kb per session (by default 10 Mb) $mc->addUrl('http://google.com'); $mc->addUrl('http://yahoo.com'); $mc->addUrl('http://altavista.com'); $mc->wait(); } catch (Exception $e) { die($e->getMessage()); } README Code: README (MultiCurl class) ========================================= NAME: MultiCurl class VERSION: 1.07 AUTHOR: Vadym Timofeyev <[email protected]> http://weblancer.net/users/tvv/ DESCRIPTION: MultiCurl class provides a convenient way to execute parallel HTTP(S) requests via PHP MULTI CURL extension with additional restrictions. For example: start 100 downloads with 2 parallel sessions, and get only first 100 Kb per session. Supported features: - Set query for CURL multi sessions. The main idea you can use only limited number of parallel requests. If you add next request and the query is fully filled the script waits while one or some previous CURL multi sessions will be completed. - Set maximal size limit for downloaded content. Please note: it is possible to download rather more bytes than the limit because download operation uses internal buffer. - Set common CURL options for all requests. - Set separate CURL options for different requests if it is necessary. SYNOPSIS: <?php include_once 'MultiCurl.class.php'; class MyMultiCurl extends MultiCurl { protected function onLoad($url, $content, $info) { print "[$url] $content "; print_r($info); } } try { $mc = new MyMultiCurl(); $mc->setMaxSessions(2); // limit 2 parallel sessions (by default 10) $mc->setMaxSize(10240); // limit 10 Kb per session (by default 10 Mb) $mc->addUrl('http://google.com'); $mc->addUrl('http://yahoo.com'); $mc->addUrl('http://altavista.com'); $mc->wait(); } catch (Exception $e) { die($e->getMessage()); } ?> COPYRIGHT: Copyright (c) 2007 Vadym Timofeyev. All rights reserved. This software is released under the GNU Lesser General Public License. Please read the disclaimer at the top of the MultiCurl.class.php file.
bSQL bSQL класс для работы с MySQL Писалось для себя, но решил доработать и выложить. PHP: <?php class bSQL { var $server = 'localhost'; var $port = false; var $name = ''; var $user = 'root'; var $password = ''; var $charset = 'cp1251'; var $protect = true; var $db; var $ts; /* * Author: Boolean * ICQ: 543929; * Home: codingworld.ru * Functions: * connect() * connected() * set_charset() * select_db() * query() * get_results() * filter() * secure() * dump_table() * dump() * disconnect() * error() * Errors: * 1 = MysqlConnect; * 2 = Select DB; * 3 = Query; * 4 = Not connected */ #Function Connect; function connect(){ $this->db = @mysql_connect($this->server, $this->user, $this->password, $this->port); if (! $this->db){ $this->error(1,mysql_error()); return false; } else { $this->set_charset($this->charset); $this->select_db($this->name); } return true; } #function connected ? function connected(){ if ($this->db) return true; return false; } #function set charsets function set_charset($charset){ if ($this->connected()){ $this->query("SET names ".$charset); $this->query("SET character_set_client = ".$charset); $this->query("SET character_set_connection = ".$charset); $this->query("SET character_set_results = ".$charset); return true; }else{ $this->error(4,"Not connected to database"); return false; } } #function select_db; function select_db($name){ if ($this->connected()){ if ( ! mysql_select_db($name, $this->db)){ $this->error(2,mysql_error()); return false; } return true; }else{ $this->error(4,"Not connected to database"); return false; } } # function query!; function query($query){ if ($this->connected()){ if ($this->protect){ if ( ! $this->secure($query) ){ $this->error(5,"Hacking attempt"); exit; } } $this->ts = mysql_query($query, $this->db); if ( ! $this->ts){ $this->error(3,mysql_error()); return false; } return true; }else{ $this->error(4,"Not connected to database"); return false; } } #function get results; function get_results($query,$v = false){ if ($this->connected()){ if ($v) $query = str_replace(array("%v","'%v'"), $this->filter($v),$query); $this->query($query); while ( $res = mysql_fetch_array($this->ts) ) $result[] = $res; if (count($result) == 1) $result = $result[0]; return $result; }else{ $this->error(4,"Not connected to database"); return false; } } #function filter value function filter($value){ if ($this->connected()){ if ($value === NULL){ $value = "NULL"; }elseif ( is_numeric($value) ){ $value = intval($value); }else{ $value = "'".mysql_real_escape_string($value)."'"; } return $value; }else{ $this->error(4,"Not connected to database"); return false; } } #function secure ? very simple. function secure($query){ $securepattern1 = "/UNION(.*)?(SELECT|DROP|UPDATE|DELETE|REPLACE|INSERT|INTO|OUTFILE)/i"; $securepattern2 = "/(.*)?(\#|--|\/\*)/i"; if ( preg_match($securepattern1,$query) || preg_match($securepattern2,$query) ){ return false; } return true; } #function dump table function dump_table($table){ if ($this->connected()){ $result = ""; $tmp = $this->get_results("SHOW CREATE TABLE `".$table."`"); $result .= $tmp[1].";\r\n\r\n"; $this->query("SELECT * FROM `".$table."`"); $begin = true; while ( $data = mysql_fetch_assoc($this->ts) ){ if ($begin){ $result .= "\r\nINSERT INTO `".$table."` VALUES\r\n\t"; }else{ $result .= ",\r\n\t"; } foreach ($data as $column => $value){ $data[$column] = $this->filter($value); } $result .= "(".implode(", ",$data).")"; $begin = false; } $result .=";\r\n\r\n"; return $result; }else{ $this->error(4,"Not connected to database"); return false; } } #function dump db =] function dump(){ if ($this->connected()){ $tables = $this->get_results("SHOW TABLES"); $result = ""; for($t = 0; $t <= count($tables)-1; $t++ ){ $result .= $this->dump_table($tables[$t][0]); } return $result; }else{ $this->error(4,"Not connected to database"); return false; } } #function disconnect; function disconnect(){ if ($this->connected()){ mysql_close($this->db); unset ($this->db); return true; }else{ $this->error(4,"Not connected to database"); return false; } } #function error; function error($type,$message){ echo "<html><head><title>MySQL Error</title><style>*{ font-family: Verdana; font-size: 11px;}</style></head><body>"; if ( $type == 1){ echo "<B>Warning:</B> Problem connecting to database."; }elseif($type == 2){ echo "<B>Warning:</B> Could not select database."; }elseif($type == 3){ echo "<B>Warning:</B> Bad SQL Query."; }elseif ($type == 4){ echo "<B>Warning:</B> Not connected."; }elseif ($type == 5){ echo "<B>wtf?</B>"; }else{ echo "<B>Warning:</B> MySQL Error."; } echo "<br /><textarea cols='50' rows='7'>".$message."</textarea></body></html>"; exit; return; } } ?> Example: PHP: <?php $boolean = new bSQL; $boolean -> user = "root"; $boolean -> password = "toor"; $boolean -> name = "mybd"; $boolean -> connect(); print_r( $boolean -> get_results("SELECT * FROM `news` WHERE `id`=%v",$_REQUEST['id']) ); $boolean -> disconnect(); ?> Запросы проходят 'проверку' на 'безопасность', по средствам регулярных выражений. Так же есть функция фильтра. оч простая. (c) Boolean
Функция генерации случного цветового кода: PHP: function colorrand(){ return '#'.dechex(mt_rand(0,255)).dechex(mt_rand(0,255)).dechex(mt_rand(0,255)); }
2 функции легкого кодирования и де кодирования в ACCII набор символов и обратно полезны при проблемах с кодировкой в бд, так же можно модифицировать ключи при кодинге и получаться легкая доп защита ваших данных PHP: function codstr($str){ $arrmass= str_split($str); for($i=0;$i<=count($arrmass)-1;$i++){ if ($i==0) $arrmass[$i]=(ord($arrmass[$i])); if ($i>0) $arrmass[$i]="/".(ord($arrmass[$i])); } $codstr= implode($arrmass); return $codstr; } function recodstr($str){ $arrmass=explode("/", $str); for($i=0;$i<=count($arrmass)-1;$i++){ $arrmass[$i]=chr($arrmass[$i]); } $codstr= implode($arrmass); return $codstr; }