Kolektsia serieoznih saitov/forumov po IT

08 03 2007
http://xpoint.ru/

Советы по оптимизации php & mysql

08 03 2007


Советы по оптимизации php & mysql

Тот кто хочет получить высокую проиводительность – не пишет просто быстрые скрипты. Для достижения высокой производительности PHP требуется хорошее понимание работы основных аппаратных средств, операционной системы и другого ПО, типа сервера и базы данных

Оптимизация баз данных

Если запрос занимает много времени воспользуйтесь командой EXPLAIN чтобы узнать каким образом Mysql выполняет этот запрос

Explain Select …

Оптимизация таблиц

Optimize table table_name [,table_name]

Выбирайте самый эффективные типы данных:
- mediumint часто оказывается эффективнее int
- обьявляйте колонки как Not null
- избегайте колонок blob, text и varchar
- первичный ключ таблицы должен быть как можно более коротким
- увеличивайте эффективность индекса – если известно что первые Х символом колонки уникальны то генерируйте индекс по этому числу символов
- не делайте индексы для каждой колонки таблицы

Правильно спроектирование базы данных должны иметь индексы, лучшие индексы те – которые создаются в команде Create table и учавстсвуют в множестве запросов. Лишние индексы замедляют запросы на обновление и удаление.
MySQL использует индексы автоматически, чтобы узнать какие индексы используются в текущем запросе нужно использовать команду Explain

Оптимизация запросов SELECT
Для их оптимизации проверьте можно ли добавить индекс. С помощью explain проверьте какие индексы используются и не следует ли их создать.

Оптимизация запросов INSERT
Этого можно добится используя команду INSERT DELAYED вместо INSERT, Клиент получает потверждение о успеной вставке хотя операция на сервере еще не завершена.
При загрузке данных из файла используйте LOAD DATE INFILE что в 20 раз быстрее чем множественные INSERT
Блокировка таблиц перед вставкой ускоряет эту операцию
LOCK TABLES a WRITE ;
INSERT…
INSERT…
UNLOCK TABLES;

Оптимизация запросов UPDATE
Оптимизируйте команды UPDATE как если бы они были SELECT

Оптимизация запросов DELETE
Для того чтобы удалить все записи из таблицы используйте команду TRUNCATE TABLE table_name вместо DELETE

Оптимизация соединений
Можно устанавливать постоянные соединения и избежать создания нового соединения с базой данных для каждого запроса :
mysql_pconnect

Продолжить чтение "Советы по оптимизации php & mysql"


Настройка обработки пхп в wamp 170

06 03 2007
По умолчанию в пхп ини он ставит short tags = off что форсирует начинать файлы с "

Буфер & Кэширование

05 03 2007
Буфер - область памяти для временного хранения промежуточных данных.

Кэширование - накопление данных в доступном хранилище, с целью их быстрого извлечения по мере надобности. Кэширование ускоряет процесса обработки информации.

PHP : sozdanie peremennih iz texta ili massiva

05 03 2007

Функция eval() заставляет PHP рассматривать обыкновенный текст, содержащийся в переменной, как фрагмент PHP-кода. Говоря языком примеров, результаты работы строк

echo 'Hello, User!';

и

eval("echo \'Hello, User!\';")

будет идентичными.

Вот eval() и поможет нам объявить все переменные из массива $_REQUEST. Выглядит это совсем коротко:

foreach($_REQUEST as $k=>$v)
{
eval("\$$k='$v';");
}

И самый простой метод - extract().

Весь код нашего примера будет выглядеть так:

extract($_REQUEST);

Это самый "тупой" метод, "разворачивающий" в переменные все, что содержится в массиве $_REQUEST. Нет абсолютно никакой гибкости в этом подходе - повлиять на регистрацию переменных или ввести какой-либо контроль вы не сможете, но выглядит очень лаконично.


PHP и Web. Кэширование.

05 03 2007
statia po kashirovaniu : http://www.codenet.ru/webmast/php/caching.php

Ghenerator web interface dlia baz dannih (tipa phpmaker)

05 03 2007
http://www.dbqwiksite.com/
Dosmotreti demku i sdelati vivod

poka cito phpmaker kajetsea proshe i cishe no u etogo softa kajetsea vozmojnostei bolishe, budem posmotreti :-)

HOWTO по оптимизации PHP

05 03 2007
http://www.compdoc.ru/internet/php/howto_optimization_php/

Vibor optimizatora (+cachirovanie) php

01 03 2007
http://www.ipersec.com/index.php?q=fr/bench_ea_vs_apc

xdebug vivodi

01 03 2007
Nastroiki v php.ini

;zend_extension_ts="c:/wamp/php/ext/php_xdebug-2.0.0rc3-5.2.1.dll"
;xdebug.profiler_output_dir = "C:/wamp/tmp/debug"
;xdebug.profiler_enable = 1

;xdebug.trace_output_dir = "C:/wamp/tmp/debug/trace/"
;xdebug.trace_format = 0
;xdebug.auto_trace=on

;xdebug.dump_undefined = on
;xdebug.dump_once = off
;xdebug.dump.SERVER = REMOTE_ADDR,REQUEST_METHOD
;xdebug.dump.REQUEST

------------------------------------
Mogu raspeceatati array v citabelinom vide : xdebug_var_dump($Row);
Mogu otslejivati vipolnenie faila po vremeni, kakie faili i kakie funktsii zapuskaiut - eto delaetsa ustanavlivaia vishe opisannie nastroiki "trace" a potom prosmatrivaiu fail v ukazannoi papke.
Primer faila :


TRACE START [2007-03-01 10:33:44]
0.0024 58392 -> {main}() C:****************\rechercher_compte_ldcom.php:0
0.0148 643248 -> require(C:***************\lib_fonctions.inc.php)
TRACE END [2007-03-01 10:33:44]
-----------------------

Nu i nailucshim ispolizovaniem skoree vsego iavleaetsea sozdanie cachegrid failov i prosmatrivanie ih WinCacheGrid

hotea budu iskati necito podobnoe no citobi rabotalo bez vneshnih prilojenii i citobi vivodila infu v samom scripte.

poka vseo :-)

5 JavaScripts vraiment utiles

28 02 2007
JavaScript revient en force depuis 2004. D'un langage sous-estimé, voire mal vu, il est devenu le point de passage obligé du fameux Web 2.0, et est aujourd'hui un atout pour les utilisateurs plutôt qu'un handicap. Ce regain d'intérêt a amené les développeurs à instaurer des bonnes pratiques, à commencer par professer l'usage de JavaScript non intrusif, ou au moins se dégradant sans perte sur les navigateurs disposant d'une vieille implémentation.

Outre ces bonnes pratiques, nombre de développeurs se sont mis à créer des scripts palliant certains manquent du langage, ou simplement leur facilitant certaines tâches. Nous en regroupant ici cinq des plus importantes, avec code source et explications.


1) getElementById()
L'une des fonctionnalités les plus utilisées du DOM est getElementById(). Désormais reconnue par tous les navigateurs modernes, elle reste cependant inaccessible aux autres. Pour que les scripts modernes puissent cependant fonctionner sur les navigateurs ne reconnaissant pas cette méthode très appréciée, la voici recréée en JavaScript. A placer au début de tout script faisant appel à getElementById().

if (!document.getElementById) {
if (document.all)
document.getElementById=function() {
if ( typeof(document.all[arguments[0]]) != "undefined")
return document.all[arguments[0]];
else
return null;
}
else if (document.layers)
document.getElementById=function() {
if ( typeof(document[arguments[0]]) != "undefined")
return document[arguments[0]];
else
return null;
}
}
L'usage est le même que pour la fonction originale : getElementById("identifiant").

2) getElementsByClass()
Après avoir recréé une fonction JavaScript dans ce même langage, l'étape suivante consiste à pallier aux manques de ce langage. Notamment, nombre de développeurs se sont trouvés frustrés de pouvoir sélectionner un élément que par identifiant avec getElementById(), mais auraient voulu également pouvoir sélectionner l'ensemble des éléments correspondant à une certaine classe - ce que le DOM ne propose pas. De nombreuses versions de getElementsByClass() ont donc été conçues au fil des années. En voici deux. La première a été créée par Dustin Diaz :

function getElementsByClass(searchClass, node, tag) {
var classElements = new Array();
if ( node == null )
node = document;
if ( tag == null )
tag = '*';
var els = node.getElementsByTagName(tag);
var elsLen = els.length;
var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}
La seconde provient de Dylan Schiemann, et propose de passer par les méthodes XPath proposées par le DOM, dans le cadre d'une page XHTML :

function getElementByClassName(needle) {
var xpathResult = document.evaluate('//*[@class = "'needle'"]', document, null, 0, null);
var outArray = new Array();
var item; while (item = xpathResult.iterateNext()) outArray[outArray.length] = item;
return outArray;
}
En l'état, la fonction de Dustin Diaz est plus efficace, car elle offre deux arguments supplémentaires et optionnels : le premier pour préciser que la recherche se fait au sein d'un élément (récupéré via getElementById(), par exemple), la seconde pour limiter la recherche à un nom de balise donnée (on peut également utiliser le joker dans le cas par exemple de sélecteurs multiple).

3) getElementsByAttribute()
Cette fonction est un pas supplémentaire dans l'accès aux balises par JavaScript : viser les balises disposant d'un même attribut d'une valeur donnée. Elle est disponible chez certains parseurs XML. Cette version a été créée par Robert Nyman.

/

Copyright Robert Nyman, http://www.robertnyman.com
Free to use if this text is included
*/
function getElementsByAttribute(oElm, strTagName, strAttributeName, strAttributeValue) {
var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
var arrReturnElements = new Array();
var oAttributeValue = (typeof strAttributeValue != "undefined")? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)") : null;
var oCurrent;
var oAttribute;
for(var i=0; i oCurrent = arrElements[i];
oAttribute = oCurrent.getAttribute(strAttributeName);
if (typeof oAttribute == "string" && oAttribute.length > 0) {
if (typeof strAttributeValue == "undefined" || (oAttributeValue && oAttributeValue.test(oAttribute))){
arrReturnElements.push(oCurrent);
}
}
}
return arrReturnElements;
}
4) $()
La dernière innovation en la matière est la fonction baptisée $(), issue du projet Prototype et qui sert de remplacement efficace à getElementById(). En effet, grâce à elle, un développeur peut remplacer ces appels de la forme var el = document.getElementById('id'); en var el = $('id'). C'est bien sûr plus court, mais $() va plus loin, en donnant la possibilité d'appeller plusieurs id différents pour obtenir un tableau d'éléments à parcourir ensuite : var el = $('id1', 'id2', 'id3');. La version que nous présentons ici est celle de Matthew Pennell :
function $() {
var elements = new Array();
for (var i=0,len=arguments.length;i var element = arguments[i];
if (typeof element == 'string') {
var matched = document.getElementById(element);
if (matched) {
elements.push(matched);
} else {
var allels = (document.all) ? document.all : document.getElementsByTagName('*');
var regexp = new RegExp('(^| )'+element+'( |$)');
for (var i=0,len=allels.length;i }
if (!elements.length) elements = document.getElementsByTagName(element);
if (!elements.length) {
elements = new Array();
var allels = (document.all) ? document.all : document.getElementsByTagName('*');
for (var i=0,len=allels.length;i }
if (!elements.length) {
var allels = (document.all) ? document.all : document.getElementsByTagName('*');
for (var i=0,len=allels.length;i }
} else {
elements.push(element);
}
}
if (elements.length == 1) {
return elements[0];
} else {
return elements;
}
}
L'idée de cette version est d'offrir un raccourci non seulement pour getElementById(), mais également getElementsByTagName() et getElementsByClass(), le tout en une seule fonction. En somme, une boîte à outils entière en une seule fonction simple d'usage : l'auteur la surnomme d'ailleurs getElementsByAnything().

5) domEl()
domEl() est encore une fonction personnelle, créée par Pawal Knapvik, autorisant une manipulation plus rapide du DOM : elle combine plusieurs fonctions afin d'ajouter simplement un nouvel élément HTML au DOM en cours. L'exemple de l'auteur est comme suit :

var link = document.createElement('a');
link.setAttribute('href', 'index.html');
link.appendChild(document.createTextNode('go home'));
document.getElementById('content').appendChild(link);

...devient...

domEl('a', 'go home', [['href', 'index.html']], document.getElementById('content'));

domEl() prend 5 arguments, la plupart optionnels ce qui permet d'avoir plusieurs cas de figure. Le premier donne le type de l'élément à créer, le second le contenu de cet élément, le troisième ses attributs, le quatrième indique dans quel(s) élément(s) celui-ci doit être créé, et le dernier précise si l'élément remplace les éléments existants, ou s'ajoute à eux.

var domEl = function(e,c,a,p,x) {
if(e||c) {
c=(typeof c=='string'||(typeof c=='object'&&!c.length))?[c]:c;
e=(!e&&c.length==1)?document.createTextNode(c[0]):e;
var n = (typeof e=='string')?document.createElement(e) : !(e&&e===c[0])?e.cloneNode(false):e.cloneNode(true);
if(e.nodeType!=3) {
c[0]===e?c[0]='':'';
for(var i=0,j=c.length;i if(a) {for(var i=(a.length-1);i>=0;i--) a[i][0]=='class' ? n.className=a[i][1] : n.setAttribute(a[i][0],a[i][1]);}
}
}
if(!p)return n;
p=(typeof p=='object'&&!p.length)?[p]:p;
for(var i=(p.length-1);i>=0;i--) {
if(x) { while(p[i].firstChild) p[i].removeChild(p[i].firstChild);
if(!e&&!c&&p[i].parentNode) p[i].parentNode.removeChild(p[i]);}
if(n) p[i].appendChild(n.cloneNode(true));
}
}




http://developpeur.journaldunet.com/tutoriel/dht/060512-5-javascripts-vraiment-utiles.shtml

XDEBUG PROFILING MODES

22 02 2007
PROFILING MODES

XDEBUG_PROFILER_LBL (0) default
Line by Line Profile, this is the simplest profiling mode that will display the profiling data sorted by line numbers from smallest to greatest. This profile mode can be used to give you a quick overview of your code's flow as the script progresses, to give you some a general idea about which section(s) of the code optimization efforts should focus on.

XDEBUG_PROFILER_CPU (1)
Execution Time Profile, this is essentially the same profile as line by line, with one notable exception, the function calls are sorted by the amount of time they took to execute, from greatest to smallest.

XDEBUG_PROFILER_NC (2)
When the profiler encounters the same function being called on the same line it will merge the calls to this function on that line into a single entry. This profile mode, which is virtually identical to the line by line profile will sort the profiler data based on number of calls to the same function on the same line. Since it is very rare that you would call the same function on the same line more then once and usually signifies unnecessary code this profile mode enables you to quickly detect and resolve such oversights.

XDEBUG_PROFILER_FS_AV (3)
Average Execution Time Profile, all calls to the same function will be merged into a single entry and the output will be sorted based on the average time each function took to execute, sorted from greatest to smallest. This is probably one of the more useful profiling modes because it allows you to immediately see, which functions are slow and could use improvement.

XDEBUG_PROFILER_FS_SUM (4)
Total Execution Time Profile is almost identical to the Average Execution Time Profile, except this the output is sorted based on the total time calls to a certain function took. Once again a very useful profile, because it allows you to see the cumulative effect of calling a particular function.

XDEBUG_PROFILER_FS_NC (5)
Number of Total Function Calls Profile, will generate a profile similar to Average Execution Time Profile, with the one exception of sorting the data based on the number of calls to a particular function in the entire script. This is very useful in determining, what common functions are used, so that you can either optimize their usage or try to reduce the number of calls to those functions.

XDEBUG_PROFILER_SD_LBL (6)
Line by Line Stack Profile, this profile allows you to see the execution tree of the functions used in the script, allowing you to see the 'flow' of the script and how long each portion took.

XDEBUG_PROFILER_SD_CPU (7)
Execution Time Stack Profile, nearly identical to Line by Line Stack Profile, only now the stack segments are sorted based on the time it took to execute each portion of the code.

XDEBUG_PROFILER_SD_NC (8)
Total Function Calls Stack Profile, same as above, only sorted by number of function calls this time.

PHP : profiling, monitoring, otladka

22 02 2007
http://developpeur.journaldunet.com/tutoriel/php/060608-php-profiling-xdebug.shtml

http://www.xdebug.org/

---
zend_extension_ts = "c:/Program Files/wamp/php/ext/php_xdebug-5.1.1-2.0.0beta5.dll"
xdebug.auto_profile = 1
xdebug.profiler_output_dir = "C:/Program Files/wamp/tmp"
xdebug.profiler_enable = 1
---
Client prosmotra grid failov : http://sourceforge.net/projects/wincachegrind/

PHP Header pour PDF : forcer ouvrir le fichier en ligne

22 02 2007


header('Content-type: application/pdf');
header('Content-Disposition: inline; filename=doc.pdf');
header('Last-Modified: '.gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: pre-check=0, post-check=0, max-age=0');
header('Pragma: anytextexeptno-cache', true);
header('Cache-control: private');
header('Expires: 0');



http://www.asp-php.net/ressources/bouts_de_code.php?id=737

.htaccess na windows

22 02 2007

Voici cette methode.
Creer un fichier texte htaccess.ccc ( ou ce que voulez d'ailleurs : toto.txt sera très bien aussi )
Une fois le fichier ( vide, vous pourrez le coder apres ) creer, lancer votre invité de commande DOS.
(
DEMARRER/EXECUTER
cmd pour XP
command pour 98
)
Ne reste plus qu'a faire
ren htaccess.ccc .htaccess

---------
Mouais ...
Tu lances le Bloc Notes, tu écris ton fichier puis tu fais enregistrer sous et tu le nommes ".htaccess" (entre guillemets) et le resultat est le même



http://www.asp-php.net/ressources/bouts_de_code.php?id=751