Skip to content

Posts from the ‘PHP’ Category

5
Mar

checklist de segurança no php

Ao con­fig­u­rar o php é necessário ter em atenção alguns aspec­tos de segurança.

; php.ini
allow_url_fopen = Off ; Dis­able URLs for file han­dling functions

register_globals = Off ; Make sure this hell­ish fiend is dead

open_basedir = /var/www/htdocs/files ; Restrict file han­dling func­tions to a subdirectory

safe_mode = Off ; Dis­able this, the next is often more prac­ti­cal
safe_mode_gid = On ; Enable safe mode with group check
safe_mode_exec_dir = /var/www/binaries ; Restrict exe­cu­tion func­tions to this direc­tory
safe_mode_allowed_env_vars = PHP_ ; Restrict access to envi­ron­ment variables

max_execution_time = 30 ; Max script exe­cu­tion time
max_input_time = 60 ; Max time spent pars­ing inputs
memory_limit = 16M ; Max mem­ory size used by one script
upload_max_filesize = 2M ; Max upload file size
post_max_size = 8M ; Max post size

display_errors = Off ; Do not show errors on screen

log_errors = On ; Log errors to log file

expose_php = Off ; Hide pres­ence of PHP

# Apache con­fig­u­ra­tion or .htac­cess

Order allow,deny
Deny from all

22
Out

sapo sessions php

sapoPHP

Ontem fui a assi­s­tir a uma sessão de php

Aqui fica um pequeno resumo da sessão :

Opti­miza­ção de código

Usar sem­pre que pos­sivel require_once em vez de include.

Nas strings usar o explode em vez do preg_split.

Usar arrays o php tra­balha bem com arrays.

Evi­tar gravar as sessões e cook­ies em ficheiros, pois o acesso ao filesys­tem é sem­pre mais lento, de prefer­ên­cia uti­lizar o memcached.

Reduzir cic­los, querys , stats, remote resquests.

Não mis­tu­rar HTML no meio da lóg­ica . HTML Deve ser HTML.

Evi­tar as men­sagens de erro do php, warn­ings, notices pois se apare­cem é má programação.

<– Apache –>

Direc­tory index

Se o nosso ficheiro de index é index.php deve estar logo na 1ª linha do direc­tory index.

A maior parte dos casos temos.. index.html,index.js, index.asp, index.htm e só no fim é que aparece o index.php

.htac­cess

Se não esta­mos a uti­lizar ficheiros .htac­cess desli­gar o mesmo do apache.

Evi­tar os symlinks.

Novi­dades do PHP 5

Name­space

Reflec­tion

Late Sta­tic Binding

Inter­face

Final Class

anony­mous function

clone

SPL – Stan­dard PHP library

SOLR

DATETIME

definir um date_default (sem­pre que se tra­balha com datas)

Time­zone

Memcache(d)

PECL

SQL – PDO

Data­Base access layer

Sim­ple XML

Web­ser­vices

O auth

SOAP

Streams

- Stream filters

–Stream con­texts

–Stream erros

Magic quotes

Fil­ter sanitize

Spe­cial chars

Suhos­in­PATH

desac­ti­var CURL

desac­ti­var remote links

Mail

Banir Ficheiros / binary

Zend server

Zend plat­form

Zend guard

Zend stu­dio edit (debug)

APC (op code cache)

Strace

XDe­bug

Web­griad

Boas Práti­cas

Uti­lizar ficheiros de con­fig, classes, definir sem­pre o time zone, classe debug, classe pro­ce­dure, classe log, fire php.

Smarty Tem­plates

Quem usa ?

Zend , xcart, xoops, open

Objec­tivo

Sep­a­rar a lóg­ica da apresentação

Estru­tura de pas­tas do smarty
libs
tem­plates
templates_c
cache

As smarty tem­plates aten­uam o cross site (XSS – injecção e colo­cação de exploits)

Frame­works php

Log4PHP

Como usar o smarty ?

10
Out

download php 6

O php 6 sofreu alter­ações impor­tantes a nível de segu­rança, que vem mel­hor em muito esta lin­guagem de pro­gra­mação, abaixo poderão ver a lista de alter­açoes. esta nova ver­são 6 só deve estar disponível no final do ano.

http://www.ibm.com/developerworks/opensource/library/os-php-future/?ca=dgr-lnxw01PHP-Future

Down­load php

29
Set

30 dicas boas para quem se está a iniciar no PHP

30 dicas boas para quem se está a ini­ciar no php.

http://net.tutsplus.com/tutorials/php/30-php-best-practices-for-beginners/

29
Set

ligar postgres com PHP

Arquivos de Configuração

O post­gres pos­sui basi­ca­mente 2 arquivos de con­fig­u­rações respon­sáveis pela conexão, eles são:

  1. postgresql.conf aqui você pre­cisa definir que o seu banco de dados irá rece­ber conexão através de TCP/IP, até a ver­são 7.9 do post­gres esta con­fig­u­ração era feita assim:
    tcpip_socket = true

    A partir da versão 8 isso é feito assim: listen_addresses = ‘*’ port = 5432

  2. pg_hba.conf este é o arquivo que define quem pode aces­sar o que e de qual forma: para per­mi­tir que qual­quer IP possa aces­sar qual­quer banco adi­cione esta linha no arquivo host    all          all         0.0.0.0 0.0.0.0       pass­word Se quiser que ape­nas 1 IP especí­fico possa aces­sar a máquina então host    all          all         200.200.200.200/32      pass­word A palavra pass­word define que para você aces­sar o banco tem que dig­i­tar a senha, existe a palavra trust que diz ao banco para nao pedir senha então tenha cuidado com este tipo de configuração

Após mexer nestes dois arquivos reini­cie o banco. Para aces­sar o seu banco através do ter­mi­nal use o comando: psql –h 200.200.200.200 –U post­gres –d banco Fique atento aos fire­wall pois eles podem bar­rar a sua conexão com o banco, e mais uma dica para que a conexão possa ser esta­b­ele­cida no Cen­tOS é necessário desati­var o SELinux, que por padrão na insta­lação fica ati­vado: vim /etc/sysconfig/selinux e con­fig­ure  o SELINUX=disabled

Exem­plo de Conexão PHP para Teste

try {
	$db = new PDO("pgsql:host=localhost dbname=datacentro user=postgres password=data1234");

	$sql = 'SELECT * FROM pessoa';
	foreach ($db->query($sql) as $row) {
		print $row['cod'] . "\t";
		print $row['nome'] . "\t";
	}

} catch (PDOException  $e) {
   print $e->getMessage();
}
die("fim");

Refer­ên­cia

http://battisti.etc.br/2009/09/28/postgres-permission-denied-is-server-running/http://www.cyberciti.biz/faq/postgresql-remote-access-or-connection/

http://dickrips.wordpress.com/2009/01/16/apache-php-postgresql-no-centos-e-fedora

31
Jul

Open cart php

Open­Cart é uma platafroma de comér­cio online baseado em PHP. Esta plataforma suporta o sis­tema de “car­rinho de com­pras” e per­mite a cri­ação de uma solução de comér­cio eletrónico, ideal para peque­nas empre­sas a um custo minimo.

opencart thumb OpenCart

Entre as suas car­ac­ter­is­ti­cas mais intere­sas­ntes encontram-se a pos­si­bil­i­dade de criar cat­e­go­rias, pro­du­tos e mar­cas, sem qual­quer tipo de lim­ite, o suporte a várias moedas, a pos­si­bil­i­dade dos clientes inserirem reviews dos pro­du­tos, red­i­men­sion­a­mento automático das ima­gens do pro­du­tos e o suporte a mais de 20 sis­temas de paga­mento.

A inter­face é agra­davél e extrema­ma­mente intu­itiva e o back­of­fice é bas­tante funcional.

Um demo deste serviço pode ser exper­i­men­tado aqui, e o down­load está disponivel aqui.

Fonte :

Nél­son Silva escreve no PL todas as quin­tas um artigo sobre Open­Web. Podem encon­trar mais arti­gos como este no seu blog pes­soal.
1
Jul

Download PHP 5.3.0 já saiu

elephpant-elephant-php-logo

Foi lançada a ver­são 5.3.0 do PHP. Segundo a equipa de desen­volvi­mento, esta foi a maior imple­men­tação das ver­sões série 5. Ela traz, além de várias novi­dades, uma porção de bugs foram cor­rigi­dos (mais de 140…).

Algu­mas novi­dades em destaque, são:

Name­spaces

Name­space” é um con­ceito ampla­mente uti­lizado em várias áreas da infor­mática.
Imag­inem um sis­tema oper­a­tivo com dois arquivos com o mesmo nome. Como eles não podem estar den­tro da mesma pasta, certo? Sendo assim, cri­amos links de pas­tas difer­entes para cada um deles.
No PHP seria como criar var­iáveis den­tro de namespaces.

Qual­quer código PHP pode ser colo­cado em name­spaces, mas ape­nas três tipos de código (Class, Funções e Con­stantes) são afec­ta­dos por elas.

A util­i­dade disso é evi­tar prob­le­mas com nomes de var­iáveis do sis­tema ou de pro­gra­mas feitos por ter­ceiros. Tam­bém evita ter que criar nomes lon­gos para os objec­tos para impedir que não haja con­fli­tos com out­ros objec­tos do mesmo nome.

Assim como out­ras funções do PHP (como a header() por exem­plo), os name­spaces devem ser definidos antes de qual­quer echo ou print.

Exis­tem dois tipos de name­spaces: os name­spaces comuns e os sub-namespaces. Veja um exem­plo de declar­ação de name­spaces:
Late Sta­t­icBind­ing

Outra novi­dade é a imple­men­tação do con­ceito de “Late Sta­tic Bind­ing”. Usando Late Sta­t­ics Bind­ings, a res­olução de méto­dos não é feito na classe onde ele foi cri­ado, mas sim de forma hierárquica, seguindo a ordem de exe­cução. Para enten­der mel­hor, veja o exem­plo com­par­a­tivo entre a imple­men­tação que tín­hamos, e a nova possibilidade:

Agora com Sta­tic Bind­ings temos:
GC (Garbage Colector)

Agora é pos­sível armazenar o resul­tado de var­iáveis em cache. Desta forma, mesmo que o estado de sua var­iável mude, é pos­sível recu­perar um valor ante­rior. Veja o exem­plo de uso:

gc_enable (); // activa o cache que irá guardar os resultados

$valor = ‘Primeiro valor’;
echo $valor. ‘‘;
$valor = ‘Segundo valor’;
echo $valor. ‘‘;

$ante­ri­ores = gc_collect_cycles(); // apanha os val­ores ante­ri­ores em cache

$valor = $ante­ri­ores [’valor’] [0]; // apanha a posi­cao 0 da posi­cao de nome ‘valor’

gc_disable($anteriores); // limpa os val­ores apan­hados e desa­loca da memoria

echo $valor . ‘‘;

/*
Esse script irah retornar:

Primeiro valor
Segundo valor
Primeiro valor
*/

?>

Funções Anôn­i­mas

Funções Anôn­i­mas per­mitem criar funções sem um nome especí­fico. Elas são muito úteis quando usadas como parâmet­ros de funções de call­back (como preg_replace_callback), mas podem ter vários out­ras util­i­dades. Veja um exemplo:

Além dessas novas funções, exis­tem alter­ações nos dri­ves de lig­ação com o MySQL, alter­ações de com­por­ta­mento em funções já ampla­mente uti­lizadas como a função ses­sion(), md5(), opendir().

Link para down­load : http://php.net/downloads.php

Fonte: http://samuelcorradi.com.br

21
Jan

50 Extremely Useful PHP Tools

PHP is one of the most widely used open-source server-side script­ing lan­guages that exist today. With over 20 mil­lion indexed domains using PHP, includ­ing major web­sites like Face­book, Digg and Word­Press, there are good rea­sons why many Web devel­op­ers pre­fer it to other server-side script­ing lan­guages, such as Python and Ruby.

PHP is faster (updated), and it is the most used script­ing lan­guage in prac­tice; it has detailed doc­u­men­ta­tion, a huge com­mu­nity, numer­ous ready-to-use scripts and well-supported frame­works; and most impor­tantly, it’s much eas­ier to get started with PHP than with other script­ing lan­guages (Python, for exam­ple). That’s why it makes per­fect sense to pro­vide the huge com­mu­nity of PHP devel­op­ers with an overview of use­ful tools and resources that can make their devel­op­ment process eas­ier and more effective.

This post presents 50 use­ful PHP tools that can sig­nif­i­cantly improve your pro­gram­ming work­flow. Among other things, you’ll find a plethora of libraries and classes that aid in debug­ging, test­ing, pro­fil­ing and code-authoring in PHP.

You may also want to take a look at the fol­low­ing related posts:

Debug­ging Tools

  • Web­grind
    Web­grind is an Xde­bug pro­fil­ing Web front end in PHP 5. It imple­ments a sub­set of the fea­tures of kcachegrind, installs in sec­onds and works on all plat­forms. For quick ‘n’ dirty opti­miza­tions, it does the job.Webgrind
  • Xde­bug
    Xde­bug is one of the most pop­u­lar debug­ging PHP exten­sions. It pro­vides a ton of use­ful data to help you quickly find bugs in your source code. Xde­bug plugs right into many of the most pop­u­lar PHP appli­ca­tions, such as PHPEclipse and phpDesigner.
  • Gubed PHP Debug­ger
    As the name implies, Gubed PHP Debug­ger is a PHP debug­ging tool for hunt­ing down logic errors.
  • DBG
    DBG is a robust and pop­u­lar PHP debug­ger for use in local and remote PHP debug­ging. It plugs into numer­ous PHP IDE’s and can eas­ily be used with the com­mand line.
  • PHP_Debug
    PHP_Debug is an open-source project that gives you use­ful infor­ma­tion about your PHP code that can be used for debug­ging. It can out­put pro­cess­ing times of your PHP and SQL, check the per­for­mance of par­tic­u­lar code blocks and get vari­able dumps in graph­i­cal form, which is great if you need a more visual out­put than the one given to you by print_r() or var_dump().
  • PHP_Dyn
    PHP_Dyn is another excel­lent PHP debug­ging tool that’s open-source. You can trace exe­cu­tion and get an out­put of the argu­ment and return val­ues of your functions.
  • MacGDBp
    MacGDBp is a live PHP debug­ger appli­ca­tion for the Mac OS. It has all the fea­tures you’d expect from a fully fea­tured debug­ger, such as the abil­ity to step through your code and set breakpoints.

Test­ing and Opti­miza­tion Tools

  • PHPUnit
    PHPUnit is a com­plete port of the pop­u­lar JUnit unit test­ing suite to PHP 5. It’s a tool that helps you test your Web application’s sta­bil­ity and scal­a­bil­ity. Writ­ing test cases within the PHPUnit frame­work is easy; here’s how to do it.
  • Sim­pleTest
    Sim­pleTest is a straight­for­ward unit-testing plat­form for PHP appli­ca­tions. To get up and run­ning with Sim­pleTest quickly, read through this prag­matic tuto­r­ial that shows you how to cre­ate a new test case.Simpletest
  • Sele­nium
    Sele­nium Remote Con­trol (RC) is a test tool that allows you to write auto­mated Web appli­ca­tion UI tests in any pro­gram­ming lan­guage against any HTTP web­site using any main­stream JavaScript-enabled browser. It can be used in con­junc­tion with PHPUnit to cre­ate and run auto­mated tests within a Web browser.
  • PHP_CodeSniffer
    PHP_CodeSniffer is a PHP 5 script for detect­ing con­for­mance to a pre­de­fined PHP cod­ing stan­dard. It’s a help­ful tool for main­tain­ing uni­form cod­ing styles for large projects and teams.
  • dBug
    dBug is ColdFusion’s cfDump for PHP. It’s a sim­ple tool for out­putting data tables that con­tain infor­ma­tion about arrays, classes and objects, data­base resources and XML resources, mak­ing it very use­ful for debug­ging purposes.dBug - Screenshot
  • PHP Pro­file Class
    PHP Pro­file Class is an excel­lent PHP pro­fil­ing tool for your Web appli­ca­tions. Using this class will help you quickly and eas­ily gain insight into which parts of your app could use some refac­tor­ing and optimization.

Doc­u­men­ta­tion Tools

  • php­Doc­u­men­tor
    php­Doc­u­men­tor (also known as php­doc and php­docu) is a doc­u­men­ta­tion tool for your PHP source code. It has an innu­mer­able amount of fea­tures, includ­ing the abil­ity to out­put in HTML, PDF, CHM and XML Doc­Book for­mats, and has both a Web-based and command-line inter­face as well as source-code high­light­ing. To learn more about php­Doc­u­men­tor, check out the online man­ual.
  • PHP DOX
    An AJAX-powered PHP doc­u­men­ta­tion search engine that enables you to search titles from all PHP doc­u­men­ta­tion pages.

Secu­rity Tools

  • Securim­age
    Securim­age is a free, open-source PHP CAPTCHA script for gen­er­at­ing com­plex images and CAPTCHA codes to pro­tect forms from spam and abuse.
  • Scav­enger
    Scav­enger is an open-source, real-time vul­ner­a­bil­ity man­age­ment tool. It helps sys­tem admin­is­tra­tors respond to vul­ner­a­bil­ity find­ings, track vul­ner­a­bil­ity find­ings and review accepted and false-positive answered vul­ner­a­bil­i­ties, with­out “nag­ging” them with old vulnerabilities.
  • PHP-IDS
    PHP-IDS (PHP-Intrusion Detec­tion Sys­tem) is a simple-to-use, well-structured, fast and state-of-the-art secu­rity layer for your PHP-based Web application.
  • Pixy: PHP Secu­rity Scan­ner
    Pixy is a Java pro­gram that per­forms auto­matic scans of PHP 4 source code, aimed to detect XSS and SQL injec­tion vul­ner­a­bil­i­ties. Pixy takes a PHP pro­gram as input and cre­ates a report that lists pos­si­ble vul­ner­a­ble points in the pro­gram, along with addi­tional infor­ma­tion for under­stand­ing the vulnerability.

Image Manip­u­la­tion and Graphs

  • PHP/SWF Charts
    PHP/SWF Charts is a pow­er­ful PHP tool that enables you to cre­ate attrac­tive Web charts and graphs from dynamic data. You can use PHP scripts to gen­er­ate and gather data from data­bases, then pass it to this tool to gen­er­ate Flash (SWF) charts and graphs.
  • pChart – a chart-drawing PHP library
    pChart is a PHP class-oriented frame­work designed to cre­ate aliased charts. Most of today’s chart libraries have a cost; this one is free. Data can be retrieved from SQL queries or CSV files or can be man­u­ally provided.Chart - Screenshot
  • WideIm­age
    WideIm­age is a PHP library for dynamic image manip­u­la­tion and pro­cess­ing for PHP 5. To be able to use the library, you should have the GD PHP exten­sion installed on your Web server.
  • Mag­ick­Wand For PHP
    Mag­ick­Wand For PHP is a PHP mod­ule suite for work­ing with the ImageMag­ick API, which lets you cre­ate, com­pose and edit bitmap images. It’s a use­ful tool for quickly incor­po­rat­ing image-editing fea­tures in your PHP applications.

PHP Code Beautifier

  • PHP_Beautifier
    PHP Beau­ti­fier is a PEAR pack­age for auto­mat­i­cally for­mat­ting and “beau­ti­fy­ing” PHP 4 and PHP 5 source code.
  • PHP­Code­Beau­ti­fier
    PHP­Code­Beau­ti­fier is a tool that saves you from hours of refor­mat­ting code to suit your own way of pre­sent­ing it. A GUI ver­sion allows you to process files visu­ally; a command-line ver­sion can be batched or inte­grated with other tools (like CVS, Sub­Ver­sion, IDE, etc.); and there is also an inte­grated tool of PHPEdit.
  • GeSHi – Generic Syn­tax High­lighter
    GeSHi is designed to be a sim­ple but pow­er­ful high­light­ing class, with the goal of sup­port­ing a wide range of pop­u­lar lan­guages. Devel­op­ers can eas­ily add new lan­guages for high­light­ing and define eas­ily cus­tomiz­able out­put formats.

Version-Control Sys­tems

  • Phing
    Phing is a pop­u­lar project version-control sys­tem for PHP. It is a use­ful tool for orga­niz­ing and main­tain­ing dif­fer­ent builds of your project.
  • xinc
    xinc is a con­tin­u­ous inte­gra­tion server version-control sys­tem writ­ten in PHP 5 (i.e. con­tin­u­ous builds instead of nightly builds). It works great with other sys­tems such as Sub­ver­sion and Phing.

Use­ful Exten­sions, Util­i­ties and Classes

  • Sim­plePie
    Sim­plePie is a PHP class that helps you work with RSS feeds. Check out the online RSS and Atom feed reader, which demon­strates a sim­ple Web appli­ca­tion that uses SimplePie.SimplePie - Screenshot
  • HTML Puri­fier
    HTML Puri­fier is a standards-compliant HTML fil­ter library writ­ten in PHP. HTML Puri­fier not only removes all mali­cious code (bet­ter known as XSS) with a thor­oughly audited, secure yet per­mis­sive white list, it also makes sure your doc­u­ments are standards-compliant. Open source and highly customizable.
  • TCPDF
    TCPDF is an open-source PHP class for gen­er­at­ing PDF documents.
  • html­SQL
    html­SQL is a unique tool. It is a PHP class for query­ing HTML val­ues in an SQL-like syn­tax. Check out the live demon­stra­tion of how html­SQL works.
  • The Great­est PHP Snip­pet File Ever (Using Quick­text for Notepad++)
    “A lit­tle some­thing for all coders: a snip­pets file that I use for PHP cod­ing. This is designed to be used with Quick­text for Notepad++, but feel free to adapt it to what­ever text edi­tor you prefer.”
  • Cre­ole
    Cre­ole is a data­base abstrac­tion layer for PHP5. It abstracts PHP’s native database-specific API to cre­ate more portable code while also pro­vid­ing devel­op­ers with a clean, fully object-oriented inter­face based loosely on the API for Java’s JDBC.
  • PHPLinq
    LINQ is a com­po­nent that adds native data query­ing capa­bil­i­ties to PHP using a syn­tax rem­i­nis­cent of SQL. It defines a set of query oper­a­tors that can be used to query, project and fil­ter data in arrays, enu­mer­able classes, XML, rela­tional data­bases and third-party data sources. [<a href=“http://phpimpact.wordpress.com/2008/05/29/30-useful-php-classes-and-components/” onclick=“javascript:_gaq.push([’_trackEvent’,‘outbound-article’,‘http://phpimpact.wordpress.com’]);”>via]
  • PHP­Math­Pub­lisher
    With Php­Math­Pub­lisher, you can pub­lish math­e­mat­i­cal doc­u­ments on the Web using only a PHP script (no LaTeX pro­grams on the server and no MathML).Math - Screenshot
  • php­MyAd­min
    If you’re work­ing with PHP, there’s a big chance you’re set up in a LAMP con­fig­u­ra­tion. php­MyAd­min is Web-based tool for man­ag­ing, build­ing, import­ing, export­ing and explor­ing MySQL databases.
  • PHPEx­cel
    PHPEx­cel is a set of use­ful PHP classes for work­ing with Microsoft Excel files. PHPEx­cel allows you to read Excel files and write to them. This is use­ful for dynam­i­cally gen­er­at­ing Excel spread­sheets for downloading.
  • Phormer
    Phormer is a PHP-based photo gallery man­age­ment appli­ca­tion that helps you to store, cat­e­go­rize and trim your pho­tos online.
  • xajax PHP Class Library
    xajax is a PHP class for eas­ily work­ing with PHP AJAX appli­ca­tions. It gives you an easy-to-use API for quickly man­ag­ing AJAX-related tasks. Check out the xajax Mul­ti­plier demo and the Graf­fiti Wall demo to see the xajax PHP class in action.
  • PHP User Class
    PHP User Class is an excel­lent script that helps you cre­ate a sys­tem for user authen­ti­ca­tion (i.e. reg­is­tra­tion, log in, account pro­file, etc.). It’s a use­ful util­ity to have around if you require user reg­is­tra­tion for your Web applications.
  • PHP-GTK
    PHP-GTK is a PHP exten­sion for the GTK+ toolkit (a robust toolkit for devel­op­ing GUIs). It is a suite of use­ful OOP func­tions and classes to help you rapidly build cross-platform, client-side GUI’s for your application.

PHP Online Tools and Resources

  • Minify!
    Minify is a PHP 5 app that can com­bine mul­ti­ple CSS or JavaScript files, com­press their con­tent (i.e. remove unnec­es­sary white space and com­ments) and serve the results with HTTP encod­ing (via Gzip/deflate) and head­ers that allow opti­mal client-side caching. This will help you fol­low sev­eral of Yahoo!’s Rules for High Per­for­mance Web­sites.minify - Screenshot
  • HTTP_StaticMerger: Auto­matic “merg­ing” of CSS and JavaScript files
    This library auto­mat­i­cally merges sets of sta­tic files (CSS or JavaScript) and speeds up page load­ing (by low­er­ing the num­ber of HTTP queries). It is rec­om­mended to use this together with caching reverse-proxy to min­i­mize the response time.
  • PHP Object Gen­er­a­tor
    PHP Object Gen­er­a­tor is an open-source Web-based tool that helps you quickly con­struct PHP objects and lever­age object-oriented pro­gram­ming (OOP) prin­ci­ples in your code.Php Object Generator - Screenshot
  • gotAPI/PHP
    gotAPI is a use­ful online tool for quickly look­ing up PHP func­tions and classes. Also check out the Quick PHP look-up wid­get exam­ple in case you’d like to include this awe­some look-up fea­ture on your website.gotAPI/PHP - Screenshot
  • koders
    koders is a search engine for open-source and down­load­able code. It cur­rently has over a bil­lion lines of code indexed and isn’t lim­ited to just PHP.
  • PECL
    PECL is a direc­tory of all known PHP exten­sions and a host­ing facil­ity for down­load­ing and devel­op­ing PHP extensions.

In-Browser Tools (Fire­fox Add-Ons)

  • FirePHP
    FirePHP is a Fire­fox exten­sion that allows you to log data in Fire­bug. It has a vari­ety of use­ful log­ging fea­tures, such as the abil­ity to change your error and excep­tion han­dling on the fly and to log errors directly to the Fire­bug con­sole. To learn more about what FirePHP can do, check out the FirePHP guide on how to use FirePHP. For devel­op­ers using the Zend PHP frame­work, you might find this guide on using FirePHP with Zend useful.FirePHP - Screenshot
  • phpLangEd­i­tor
    phpLangEd­i­tor is a very handy Fire­fox add-on for trans­lat­ing lan­guage files and vari­ables in your script.phpLangEditor - Screenshot
  • PHP Lookup
    PHP Lookup is a built-in search bar to help you quickly look up ref­er­ences to PHP syntax.
  • PHP Man­ual Search
    PHP Man­ual Search is a handy search bar that searches offi­cial PHP doc­u­men­ta­tion from within your Web browser.

Frame­works for PHP

  • Dwoo
    Dwoo is a PHP 5 tem­plate engine posi­tioned as an alter­na­tive to Smarty. It is (nearly) fully com­pat­i­ble with its tem­plates and plug-ins, but it is being writ­ten from scratch and is aimed to go one step fur­ther with a cleaner code base.
  • CodeIgniter
    CodeIgniter is a pow­er­ful, high-performance, open-source PHP frame­work that helps you author PHP appli­ca­tions rapidly. CodeIgniter is known for hav­ing a light foot­print, thereby reduc­ing your server’s work. You can get up and run­ning with CodeIgniter in a jiffy: it has an awe­some online man­ual, a cou­ple of help­ful video tuto­ri­als and an active user forum.CodeIgniter - Screenshot
  • YII Frame­work
    Here is a high-performance component-based PHP frame­work that is sup­posed to be more effi­cient than CodeIgniter, CakePHP, ZF and Sym­fony. An opti­mal solu­tion for devel­op­ing large-scale Web appli­ca­tions. Yii sup­ports MVC, DAO/ActiveRecord, I18N/L10N, caching, jQuery-based AJAX sup­port, authen­ti­ca­tion and role-based access con­trol, scaf­fold­ing, input val­i­da­tion, wid­gets, events, them­ing and Web services.
  • Net­Beans
    A ded­i­cated PHP cod­ing envi­ron­ment and com­plete inte­gra­tion with web stan­dards. The Net­Beans PHP edi­tor is dynam­i­cally inte­grated with Net­Beans HTML, JavaScript and CSS edit­ing fea­tures such as syn­tax high­light­ing and the JavaScript debug­ger. Net­Beans IDE 6.5 fully sup­ports iter­a­tive devel­op­ment, so test­ing PHP projects fol­lows the clas­sic pat­terns famil­iar to web developers.
  • Solar
    Solar is a PHP 5 devel­op­ment frame­work for Web appli­ca­tions derived from the Savant tem­plat­ing engine. Solar uses the MVC archi­tec­tural pat­tern and has a host of classes and func­tions for secur­ing your Web app against SQL injec­tion, cross-website script­ing (XSS) and other com­mon exploits.Solar - Screenshot
  • sym­fony
    sym­fony is an open-source PHP 5 Web appli­ca­tion frame­work that is well known for its mod­u­lar­ity and use­ful library of classes. To get up and run­ning as fast as pos­si­ble, you should check out the prag­matic sym­fony online tuto­r­ial called “The sym­fony 1.2 advent cal­en­dar tuto­r­ial,” which takes you through a step-by-step exam­ple of build­ing your own symfony-based Web application.
  • PEARPHP Exten­sion and Appli­ca­tion Repos­i­tory
    PEAR is a pop­u­lar frame­work and dis­tri­b­u­tion sys­tem for reusable PHP com­po­nents. The pur­pose of the frame­work is to pro­vide a struc­tured library of open-source code for PHP users, a sys­tem for code dis­tri­b­u­tion and pack­age main­te­nance and a stan­dard style for PHP code.
  • Pro­pel
    Pro­pel is an Object-Relational Map­ping (ORM) frame­work for PHP 5. It allows you to access your data­base using a set of objects, pro­vid­ing a sim­ple API for stor­ing and retriev­ing data.
  • {{macro}} tem­plate engine
    {{macro}} com­piles ini­tial tem­plates into exe­cutable PHP scripts with very clean syn­tax (much cleaner than WACT and Smarty) and exe­cutes them very fast. The engine doesn’t use an XML-like syn­tax; there are only two data scopes, global and local, and no more data sources (all data is dis­played with reg­u­lar PHP vari­ables); and the sys­tem sup­ports all WACT fea­tures such as tem­plates wrap­ping and including.minify - Screenshot
  • Zend Frame­work
    The Zend Frame­work by Zend Tech­nolo­gies (the cre­ators of PHP’s script­ing engine) is a pop­u­lar PHP Web appli­ca­tion frame­work that embraces the prin­ci­ples of PHP OOP; it’s very exten­si­ble and has built-in util­i­ties for work­ing with free Web ser­vice APIs, such as those of Google, Flickr and Ama­zon.
  • Qcodo
    Qcodo is an excel­lent open-source PHP Web appli­ca­tion frame­work. It’s sub­di­vided into two parts: (1) Code Gen­er­a­tor, and (2) Qforms. Code Gen­er­a­tor han­dles the cre­ation of object code and PHP and HTML front-end code from your data model. Qforms is an intu­itive sys­tem for han­dling and cre­at­ing com­plex PHP-driven HTML Web forms. Check out demos of appli­ca­tions that use Qcodo and pre­sen­ta­tional mate­r­ial that cov­ers Qcodo.Qcodo - Screenshot
  • SAJAX
    SAJAX is a JavaScript and AJAX appli­ca­tion frame­work that works well with PHP (as well as sev­eral other server-side script­ing lan­guages). See SAJAX at work by going to Wall live demon­stra­tion.
  • Smarty
    Smarty is a pop­u­lar PHP tem­plat­ing sys­tem to help you sep­a­rate PHP logic and front-end code (HTML, CSS, JavaScript). It will keep your projects mod­u­lar and eas­ier to maintain.
  • CakePHP
    CakePHP is one of the lead­ing PHP frame­works for cre­at­ing robust, fully-featured Web appli­ca­tions. CakePHP has an exten­sive and well-organized online man­ual. If you want to learn via video tuto­ri­als, check out the CakePHP screen­casts.CakePHP - Screenshot
  • Savant2
    Savant2 is another pop­u­lar object-oriented PHP tem­plat­ing sys­tem. Instead of a spe­cial syn­tax unique to Savant2, you use PHP syn­tax to develop your project’s template.
  • PHP­Spec
    PHP­Spec is a sim­ple and intu­itive PHP frame­work. It fol­lows the Behavior-Driven Devel­op­ment prin­ci­ple and there­fore allows you to write behavior-oriented code, often­times in plain English.

PHP IDEs and Editors

  • PHPEclipse
    PHPEclipse is a pop­u­lar PHP source-code edi­tor that is open source and runs on all the major oper­at­ing sys­tems, such as Win­dows, Linux and Mac OS. It has all the fea­tures you’d expect from a PHP source-code edi­tor, such as code-folding, syn­tax high­light­ing, hover-over tool tips and sup­port for XDe­bug and DBG.PHPEclipse - Screenshot
  • PhpED
    PhpED is an excel­lent IDE for Win­dows users. It is one of the most robust and feature-packed IDEs cur­rently out on the mar­ket and has use­ful fea­tures such as a built-in source-code pro­filer to find bot­tle­necks in your PHP source code and excel­lent inte­gra­tion with third-party apps and ser­vices just as front-end code validation.PhpED - Screenshot
  • phpDe­signer
    phpDe­signer is a light­weight PHP editor/IDE that also han­dles front-end code and markup remark­ably well. Check out the phpDe­signer online tuto­ri­als, as well as screen­casts on phpDe­signer to help you learn more about the IDE.phpDesigner - Screenshot
  • Zend Stu­dio
    Zend Stu­dio is an excel­lent PHP IDE for Eclipse. It’ll help you develop, deploy and man­age Rich Inter­net Appli­ca­tions (RIAs) in an intu­itive interface.Zend Studio - Screenshot
  • Aptana PHP
    Aptana PHP is an open-source IDE extension/plug-in to be used in con­junc­tion with Aptana Stu­dio. To learn more, be sure to check out the online doc­u­men­ta­tion about Aptana PHP.
  • PDT
    PDT is a PHP Devel­op­ment Tools frame­work that’s part of the Eclipse project. PDT includes all the nec­es­sary tools for you to cre­ate PHP-based Web applications.
  • VS.Php
    VS.Php is a PHP IDE for MS Visual Stu­dio, mak­ing it a great IDE for recently con­verted ASP devel­op­ers who have used MS VS to develop Web appli­ca­tions. To get you up and run­ning ASAP with VS.Php, check out Jcx.Software’s online tuto­ri­als as well as its online doc­u­men­ta­tion.
  • PHPEdit
    PHPEdit is an excel­lent PHP editor/IDE with a ton of use­ful fea­tures and a very intu­itive user inter­face. To learn more about why PHPEdit is a good IDE, read the 10 rea­sons to use PHPEdit and view the intro­duc­tory screen­cast about PHPEdit.

Sources and Resources

smash­ing­magazine

7
Jan

SSH2 & PHP Howto Guide: SSH Connections Made Easy in PHP

PHP doesn’t come with native sup­port for mak­ing SSH con­nec­tions via the libssh2 libraries. You must use the PECL SSH2 exten­sions. Installing them can be tricky, but Kevin van Zon­n­eveld does a great job explain­ing how to install them over here. So I won’t go there. The new ver­sion, 0.11.0, also seems to be com­pil­ing more reli­ably for everyone.

Unfor­tu­nately, the library is sparsely doc­u­mented, and still buggy in some places. And most of the com­ments posted on http://www.php.net/ssh2 are just plain wrong! Kudos to Mike Sul­li­van for fix­ing some of the issues with non-blocking I/O (And let’s not for­get to thank Sara Gole­mon for writ­ing it to begin with!). I list the most con­spic­u­ous prob­lems at the bot­tom of this blog entry for inter­ested par­ties. Every­one else can use our wrap­pers to smooth over some of the kinks and make most com­mon tasks triv­ial to perform.

Our wrap­per is released under GNU license and can be used, for exam­ple, as follows:

$php_ssh2 = new SSH2('YOURHOST.COM');
$php_ssh2->loginWithPassword('YOUR_LOGIN', 'YOUR_PASSWORD');
echo $php_ssh2->execCommandBlock('find /cat/food');

All Per­ti­nent Features:

$php_ssh2->execCommandBlockNoOutput()

allows exe­cu­tion of a script ignor­ing out­put. Note that with­out block­ing exe­cu­tion man­u­ally, 2 ssh2_execs will exe­cute asy­chro­nously. So it should also be used for shell scripts that have no out­put. Why? If you never check for data, it will never block — yes, even in block­ing mode! This is sub­tle … until it clicks.

$php_ssh2->setLogReads($setting = true)

enables or dis­ables read log­ging on the cur­rent SSH2 stream.

$php_ssh2->setLogWrites($setting = true)

enables or dis­ables write log­ging on the cur­rent SSH2 stream.

$php_ssh2->getShell($set_blocking = false, $term_type = 'vt102' ... )

opens a shell for the user — gen­er­ally not needed and much harder to work with.

$php_ssh2->waitPrompt($prompt_regex = '> $', &$buf = '', $timeout_secs = 0)

waits for a spec­i­fied prompt $prompt_regex (expressed as a reg­u­lar expres­sion) for $timeout_secs (or 0 to block for­ever). Returns true or false, leaves response (whether match­ing or not) buffer in &$buf parameter.

$php_ssh2->writePrompt($command, $add_newline = true)

writes the spec­i­fied out­put to stream. Returns what it was able to write.

The rest of the func­tions are fairly self-explanatory. Check out the library here —
http://www.seoegghead.com/software/ssh2-php-wrappers.seo

Problems/Gotchas I’ve Observed in PECL SSH2

1. Non-blocking mode buggy and/or core­dumps in ver­sions < 0.11.0. So make sure you upgrade.
2. FreeBSD Ports cur­rently reports a patched “usr/ports/security/pecl-ssh2? ver­sion 0.10.0 as 0.11.0 (Not strictly a PECL SSH2 prob­lem, but worth not­ing as it caused me grief).
3. stream_set_timeout() does not work at all with SSH2 streams — silently always returns false.
4. stream_select() does not work with SSH2 streams — but prints a warn­ing.
5. One must pass NULL to $pty — not false (like some com­ments on php.net claim), not “” — oth­er­wise LFs (“\n”) will get changed to CRLFs (“\r\n”). Text files will mostly sur­vive this, but binary data will be cor­rupted! This took us a solid hour to debug and involved a hex-editor.

As a con­se­quence of some of the above, there is no good way to do non-blocking I/O in ver­sions < 0.11.0. Period. No time­outs, no polling, no select­ing. If you need non-blocking I/O to work reli­ably, you must upgrade to 0.11.0.

seoeg­gheadv

9
Dez

PHP — Controlo de erros (Debug)

Analise dos logs enquanto se desenvolve

Um dos erros muito comuns no desen­volvi­mento em qual­quer lin­guagem inter­pre­tada é não usar­mos a total­i­dade das van­ta­gens da análise de logs. No PHP para um uso mais efi­ciente do relatório de erros e avi­sos, a pro­priedade error_reporting, no ficheiro php.ini, dev­erá ser definida como E_ALL.

error_reporting  =  E_ALL

Para um desen­volvi­mento mais efec­tivo, desligo sem­pre a visu­al­iza­ção de erros no “screen”, preferindo a análise dos mes­mos no ficheiro de log. Para isso defino o display_errors como desligado.

display_errors = Off

Neces­si­ta­mos ainda, de indicar ao PHP para efec­tuar o log dos erros para um ficheiro e indicar qual o cam­inho para o ficheiro onde dese­jamos gravar as men­sagens de erro.

log_errors = On ; Dese­jamos gravar as men­sagens em ficheiro

error_log = “/var/logs/php.log” ; Cam­inho para o ficheiro onde dese­jamos gravar as mensagens

Depois basta abrir uma con­sola onde estou a mon­i­tor­izar toda a activi­dade do ficheiro de log do php.

tail –f /var/logs/php.log

Xde­bug

A exten­são XDe­bug para PHP per­mite efec­tuar pro­fill­ing e debug­ging de uma forma muito sim­ples, com funções como xdebug_memory_usage( ), que nos per­mite anal­isar o uso da memória do script cur­rente, que tam­bém tem cor­re­spon­dente na ver­são nativa do php, memory_get_usage(), a função xdebug_call_class(), que per­mite saber em que class foi o método invo­cado, entre muitas outras.

A exten­são XDe­bug pro­por­ciona uma mel­ho­ria na visu­al­iza­ção de men­sagens de erro, podendo-se obser­var o cam­inho de exe­cução do script até ao momento em que acon­te­ceu o erro, por exemplo.

Mais infor­mações sobre a exten­são na página da mesma.

Bad Behavior has blocked 25 access attempts in the last 7 days.