Category: PHP

checklist de segurança no php

Ao configurar o php é necessário ter em atenção alguns aspectos de segurança.

; php.ini
allow_url_fopen = Off ; Disable URLs for file handling functions

register_globals = Off ; Make sure this hellish fiend is dead

open_basedir = /var/www/htdocs/files ; Restrict file handling functions to a subdirectory

safe_mode = Off ; Disable this, the next is often more practical
safe_mode_gid = On ; Enable safe mode with group check
safe_mode_exec_dir = /var/www/binaries ; Restrict execution functions to this directory
safe_mode_allowed_env_vars = PHP_ ; Restrict access to environment variables

max_execution_time = 30 ; Max script execution time
max_input_time = 60 ; Max time spent parsing inputs
memory_limit = 16M ; Max memory 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 presence of PHP

# Apache configuration or .htaccess

Order allow,deny
Deny from all

Share and enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Netvibes
  • PDF
  • RSS
  • Slashdot
  • StumbleUpon
  • Twitter

sapo sessions php

sapoPHP

Ontem fui a assistir a uma sessão de php

Aqui fica um pequeno resumo da sessão :

Optimização de código

Usar sempre que possivel require_once em vez de include.

Nas strings usar o explode em vez do preg_split.

Usar arrays o php trabalha bem com arrays.

Evitar gravar as sessões e cookies em ficheiros, pois o acesso ao filesystem é sempre mais lento, de preferência utilizar o memcached.

Reduzir ciclos, querys , stats, remote resquests.

Não misturar HTML no meio da lógica . HTML Deve ser HTML.

Evitar as mensagens de erro do php, warnings, notices pois se aparecem é má programação.

<– Apache –>

Directory index

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

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

.htaccess

Se não estamos a utilizar ficheiros .htaccess desligar o mesmo do apache.

Evitar os symlinks.

Novidades do PHP 5

Namespace

Reflection

Late Static Binding

Interface

Final Class

anonymous function

clone

SPL – Standard PHP library

SOLR

DATETIME

definir um date_default (sempre que se trabalha com datas)

Timezone

Memcache(d)

PECL

SQL – PDO

DataBase access layer

Simple XML

Webservices

O auth

SOAP

Streams

- Stream filters

-Stream contexts

-Stream erros

Magic quotes

Filter sanitize

Special chars

SuhosinPATH

desactivar CURL

desactivar remote links

Mail

Banir Ficheiros / binary

Zend server

Zend platform

Zend guard

Zend studio edit (debug)

APC (op code cache)

Strace

XDebug

Webgriad

Boas Práticas

Utilizar ficheiros de config, classes, definir sempre o time zone, classe debug, classe procedure, classe log, fire php.

Smarty Templates

Quem usa ?

Zend , xcart, xoops, open

Objectivo

Separar a lógica da apresentação

Estrutura de pastas do smarty
libs
templates
templates_c
cache

As smarty templates atenuam o cross site (XSS – injecção e colocação de exploits)

Frameworks php

Log4PHP

Como usar o smarty ?

Share and enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Netvibes
  • PDF
  • RSS
  • Slashdot
  • StumbleUpon
  • Twitter

download php 6

O php 6 sofreu alterações importantes a nível de segurança, que vem melhor em muito esta linguagem de programação, abaixo poderão ver a lista de alteraçoes. esta nova versã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

Download php

Share and enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Netvibes
  • PDF
  • RSS
  • Slashdot
  • StumbleUpon
  • Twitter

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

30 dicas boas para quem se está a iniciar no php.

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

Share and enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Netvibes
  • PDF
  • RSS
  • Slashdot
  • StumbleUpon
  • Twitter

ligar postgres com PHP

Arquivos de Configuração

O postgres possui basicamente 2 arquivos de configurações responsáveis pela conexão, eles são:

  1. postgresql.conf aqui você precisa definir que o seu banco de dados irá receber conexão através de TCP/IP, até a versão 7.9 do postgres esta configuraçã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 acessar o que e de qual forma: para permitir que qualquer IP possa acessar qualquer banco adicione esta linha no arquivo host    all          all         0.0.0.0 0.0.0.0       password Se quiser que apenas 1 IP específico possa acessar a máquina então host    all          all         200.200.200.200/32      password A palavra password define que para você acessar o banco tem que digitar 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 reinicie o banco. Para acessar o seu banco através do terminal use o comando: psql -h 200.200.200.200 -U postgres -d banco Fique atento aos firewall pois eles podem barrar a sua conexão com o banco, e mais uma dica para que a conexão possa ser estabelecida no CentOS é necessário desativar o SELinux, que por padrão na instalação fica ativado: vim /etc/sysconfig/selinux e configure  o SELINUX=disabled

Exemplo 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ência

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

Share and enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Netvibes
  • PDF
  • RSS
  • Slashdot
  • StumbleUpon
  • Twitter

Open cart php

OpenCart é uma platafroma de comércio online baseado em PHP. Esta plataforma suporta o sistema de “carrinho de compras” e permite a criação de uma solução de comércio eletrónico, ideal para pequenas empresas a um custo minimo.

opencart thumb OpenCart

Entre as suas caracteristicas mais interesasntes encontram-se a possibilidade de criar categorias, produtos e marcas, sem qualquer tipo de limite, o suporte a várias moedas, a possibilidade dos clientes inserirem reviews dos produtos, redimensionamento automático das imagens do produtos e o suporte a mais de 20 sistemas de pagamento.

A interface é agradavél e extremamamente intuitiva e o backoffice é bastante funcional.

Um demo deste serviço pode ser experimentado aqui, e o download está disponivel aqui.

Fonte :

Nélson Silva escreve no PL todas as quintas um artigo sobre OpenWeb. Podem encontrar mais artigos como este no seu blog pessoal.
Share and enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Netvibes
  • PDF
  • RSS
  • Slashdot
  • StumbleUpon
  • Twitter

Download PHP 5.3.0 já saiu

elephpant-elephant-php-logo

Foi lançada a versão 5.3.0 do PHP. Segundo a equipa de desenvolvimento, esta foi a maior implementação das versões série 5. Ela traz, além de várias novidades, uma porção de bugs foram corrigidos (mais de 140…).

Algumas novidades em destaque, são:

Namespaces

“Namespace” é um conceito amplamente utilizado em várias áreas da informática.
Imaginem um sistema operativo com dois arquivos com o mesmo nome. Como eles não podem estar dentro da mesma pasta, certo? Sendo assim, criamos links de pastas diferentes para cada um deles.
No PHP seria como criar variáveis dentro de namespaces.

Qualquer código PHP pode ser colocado em namespaces, mas apenas três tipos de código (Class, Funções e Constantes) são afectados por elas.

A utilidade disso é evitar problemas com nomes de variáveis do sistema ou de programas feitos por terceiros. Também evita ter que criar nomes longos para os objectos para impedir que não haja conflitos com outros objectos do mesmo nome.

Assim como outras funções do PHP (como a header() por exemplo), os namespaces devem ser definidos antes de qualquer echo ou print.

Existem dois tipos de namespaces: os namespaces comuns e os sub-namespaces. Veja um exemplo de declaração de namespaces:
Late StaticBinding

Outra novidade é a implementação do conceito de “Late Static Binding”. Usando Late Statics Bindings, a resolução de métodos não é feito na classe onde ele foi criado, mas sim de forma hierárquica, seguindo a ordem de execução. Para entender melhor, veja o exemplo comparativo entre a implementação que tínhamos, e a nova possibilidade:

Agora com Static Bindings temos:
GC (Garbage Colector)

Agora é possível armazenar o resultado de variáveis em cache. Desta forma, mesmo que o estado de sua variável mude, é possível recuperar um valor anterior. Veja o exemplo de uso:

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

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

$anteriores = gc_collect_cycles(); // apanha os valores anteriores em cache

$valor = $anteriores ['valor'] [0]; // apanha a posicao 0 da posicao de nome ‘valor’

gc_disable($anteriores); // limpa os valores apanhados e desaloca da memoria

echo $valor . ‘‘;

/*
Esse script irah retornar:

Primeiro valor
Segundo valor
Primeiro valor
*/

?>

Funções Anônimas

Funções Anônimas permitem criar funções sem um nome específico. Elas são muito úteis quando usadas como parâmetros de funções de callback (como preg_replace_callback), mas podem ter vários outras utilidades. Veja um exemplo:

Além dessas novas funções, existem alterações nos drives de ligação com o MySQL, alterações de comportamento em funções já amplamente utilizadas como a função session(), md5(), opendir().

Link para download : http://php.net/downloads.php

Fonte: http://samuelcorradi.com.br

Share and enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Netvibes
  • PDF
  • RSS
  • Slashdot
  • StumbleUpon
  • Twitter

50 Extremely Useful PHP Tools

PHP is one of the most widely used open-source server-side scripting languages that exist today. With over 20 million indexed domains using PHP, including major websites like Facebook, Digg and WordPress, there are good reasons why many Web developers prefer it to other server-side scripting languages, such as Python and Ruby.

PHP is faster (updated), and it is the most used scripting language in practice; it has detailed documentation, a huge community, numerous ready-to-use scripts and well-supported frameworks; and most importantly, it’s much easier to get started with PHP than with other scripting languages (Python, for example). That’s why it makes perfect sense to provide the huge community of PHP developers with an overview of useful tools and resources that can make their development process easier and more effective.

This post presents 50 useful PHP tools that can significantly improve your programming workflow. Among other things, you’ll find a plethora of libraries and classes that aid in debugging, testing, profiling and code-authoring in PHP.

You may also want to take a look at the following related posts:

Debugging Tools

  • Webgrind
    Webgrind is an Xdebug profiling Web front end in PHP 5. It implements a subset of the features of kcachegrind, installs in seconds and works on all platforms. For quick ‘n’ dirty optimizations, it does the job.Webgrind
  • Xdebug
    Xdebug is one of the most popular debugging PHP extensions. It provides a ton of useful data to help you quickly find bugs in your source code. Xdebug plugs right into many of the most popular PHP applications, such as PHPEclipse and phpDesigner.
  • Gubed PHP Debugger
    As the name implies, Gubed PHP Debugger is a PHP debugging tool for hunting down logic errors.
  • DBG
    DBG is a robust and popular PHP debugger for use in local and remote PHP debugging. It plugs into numerous PHP IDE’s and can easily be used with the command line.
  • PHP_Debug
    PHP_Debug is an open-source project that gives you useful information about your PHP code that can be used for debugging. It can output processing times of your PHP and SQL, check the performance of particular code blocks and get variable dumps in graphical form, which is great if you need a more visual output than the one given to you by print_r() or var_dump().
  • PHP_Dyn
    PHP_Dyn is another excellent PHP debugging tool that’s open-source. You can trace execution and get an output of the argument and return values of your functions.
  • MacGDBp
    MacGDBp is a live PHP debugger application for the Mac OS. It has all the features you’d expect from a fully featured debugger, such as the ability to step through your code and set breakpoints.

Testing and Optimization Tools

  • PHPUnit
    PHPUnit is a complete port of the popular JUnit unit testing suite to PHP 5. It’s a tool that helps you test your Web application’s stability and scalability. Writing test cases within the PHPUnit framework is easy; here’s how to do it.
  • SimpleTest
    SimpleTest is a straightforward unit-testing platform for PHP applications. To get up and running with SimpleTest quickly, read through this pragmatic tutorial that shows you how to create a new test case.Simpletest
  • Selenium
    Selenium Remote Control (RC) is a test tool that allows you to write automated Web application UI tests in any programming language against any HTTP website using any mainstream JavaScript-enabled browser. It can be used in conjunction with PHPUnit to create and run automated tests within a Web browser.
  • PHP_CodeSniffer
    PHP_CodeSniffer is a PHP 5 script for detecting conformance to a predefined PHP coding standard. It’s a helpful tool for maintaining uniform coding styles for large projects and teams.
  • dBug
    dBug is ColdFusion’s cfDump for PHP. It’s a simple tool for outputting data tables that contain information about arrays, classes and objects, database resources and XML resources, making it very useful for debugging purposes.dBug - Screenshot
  • PHP Profile Class
    PHP Profile Class is an excellent PHP profiling tool for your Web applications. Using this class will help you quickly and easily gain insight into which parts of your app could use some refactoring and optimization.

Documentation Tools

  • phpDocumentor
    phpDocumentor (also known as phpdoc and phpdocu) is a documentation tool for your PHP source code. It has an innumerable amount of features, including the ability to output in HTML, PDF, CHM and XML DocBook formats, and has both a Web-based and command-line interface as well as source-code highlighting. To learn more about phpDocumentor, check out the online manual.
  • PHP DOX
    An AJAX-powered PHP documentation search engine that enables you to search titles from all PHP documentation pages.

Security Tools

  • Securimage
    Securimage is a free, open-source PHP CAPTCHA script for generating complex images and CAPTCHA codes to protect forms from spam and abuse.
  • Scavenger
    Scavenger is an open-source, real-time vulnerability management tool. It helps system administrators respond to vulnerability findings, track vulnerability findings and review accepted and false-positive answered vulnerabilities, without “nagging” them with old vulnerabilities.
  • PHP-IDS
    PHP-IDS (PHP-Intrusion Detection System) is a simple-to-use, well-structured, fast and state-of-the-art security layer for your PHP-based Web application.
  • Pixy: PHP Security Scanner
    Pixy is a Java program that performs automatic scans of PHP 4 source code, aimed to detect XSS and SQL injection vulnerabilities. Pixy takes a PHP program as input and creates a report that lists possible vulnerable points in the program, along with additional information for understanding the vulnerability.

Image Manipulation and Graphs

  • PHP/SWF Charts
    PHP/SWF Charts is a powerful PHP tool that enables you to create attractive Web charts and graphs from dynamic data. You can use PHP scripts to generate and gather data from databases, then pass it to this tool to generate Flash (SWF) charts and graphs.
  • pChart – a chart-drawing PHP library
    pChart is a PHP class-oriented framework designed to create 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 manually provided.Chart - Screenshot
  • WideImage
    WideImage is a PHP library for dynamic image manipulation and processing for PHP 5. To be able to use the library, you should have the GD PHP extension installed on your Web server.
  • MagickWand For PHP
    MagickWand For PHP is a PHP module suite for working with the ImageMagick API, which lets you create, compose and edit bitmap images. It’s a useful tool for quickly incorporating image-editing features in your PHP applications.

PHP Code Beautifier

  • PHP_Beautifier
    PHP Beautifier is a PEAR package for automatically formatting and “beautifying” PHP 4 and PHP 5 source code.
  • PHPCodeBeautifier
    PHPCodeBeautifier is a tool that saves you from hours of reformatting code to suit your own way of presenting it. A GUI version allows you to process files visually; a command-line version can be batched or integrated with other tools (like CVS, SubVersion, IDE, etc.); and there is also an integrated tool of PHPEdit.
  • GeSHi – Generic Syntax Highlighter
    GeSHi is designed to be a simple but powerful highlighting class, with the goal of supporting a wide range of popular languages. Developers can easily add new languages for highlighting and define easily customizable output formats.

Version-Control Systems

  • Phing
    Phing is a popular project version-control system for PHP. It is a useful tool for organizing and maintaining different builds of your project.
  • xinc
    xinc is a continuous integration server version-control system written in PHP 5 (i.e. continuous builds instead of nightly builds). It works great with other systems such as Subversion and Phing.

Useful Extensions, Utilities and Classes

  • SimplePie
    SimplePie is a PHP class that helps you work with RSS feeds. Check out the online RSS and Atom feed reader, which demonstrates a simple Web application that uses SimplePie.SimplePie - Screenshot
  • HTML Purifier
    HTML Purifier is a standards-compliant HTML filter library written in PHP. HTML Purifier not only removes all malicious code (better known as XSS) with a thoroughly audited, secure yet permissive white list, it also makes sure your documents are standards-compliant. Open source and highly customizable.
  • TCPDF
    TCPDF is an open-source PHP class for generating PDF documents.
  • htmlSQL
    htmlSQL is a unique tool. It is a PHP class for querying HTML values in an SQL-like syntax. Check out the live demonstration of how htmlSQL works.
  • The Greatest PHP Snippet File Ever (Using Quicktext for Notepad++)
    “A little something for all coders: a snippets file that I use for PHP coding. This is designed to be used with Quicktext for Notepad++, but feel free to adapt it to whatever text editor you prefer.”
  • Creole
    Creole is a database abstraction layer for PHP5. It abstracts PHP’s native database-specific API to create more portable code while also providing developers with a clean, fully object-oriented interface based loosely on the API for Java’s JDBC.
  • PHPLinq
    LINQ is a component that adds native data querying capabilities to PHP using a syntax reminiscent of SQL. It defines a set of query operators that can be used to query, project and filter data in arrays, enumerable classes, XML, relational databases and third-party data sources. [via]
  • PHPMathPublisher
    With PhpMathPublisher, you can publish mathematical documents on the Web using only a PHP script (no LaTeX programs on the server and no MathML).Math - Screenshot
  • phpMyAdmin
    If you’re working with PHP, there’s a big chance you’re set up in a LAMP configuration. phpMyAdmin is Web-based tool for managing, building, importing, exporting and exploring MySQL databases.
  • PHPExcel
    PHPExcel is a set of useful PHP classes for working with Microsoft Excel files. PHPExcel allows you to read Excel files and write to them. This is useful for dynamically generating Excel spreadsheets for downloading.
  • Phormer
    Phormer is a PHP-based photo gallery management application that helps you to store, categorize and trim your photos online.
  • xajax PHP Class Library
    xajax is a PHP class for easily working with PHP AJAX applications. It gives you an easy-to-use API for quickly managing AJAX-related tasks. Check out the xajax Multiplier demo and the Graffiti Wall demo to see the xajax PHP class in action.
  • PHP User Class
    PHP User Class is an excellent script that helps you create a system for user authentication (i.e. registration, log in, account profile, etc.). It’s a useful utility to have around if you require user registration for your Web applications.
  • PHP-GTK
    PHP-GTK is a PHP extension for the GTK+ toolkit (a robust toolkit for developing GUIs). It is a suite of useful OOP functions 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 combine multiple CSS or JavaScript files, compress their content (i.e. remove unnecessary white space and comments) and serve the results with HTTP encoding (via Gzip/deflate) and headers that allow optimal client-side caching. This will help you follow several of Yahoo!’s Rules for High Performance Websites.minify - Screenshot
  • HTTP_StaticMerger: Automatic “merging” of CSS and JavaScript files
    This library automatically merges sets of static files (CSS or JavaScript) and speeds up page loading (by lowering the number of HTTP queries). It is recommended to use this together with caching reverse-proxy to minimize the response time.
  • PHP Object Generator
    PHP Object Generator is an open-source Web-based tool that helps you quickly construct PHP objects and leverage object-oriented programming (OOP) principles in your code.Php Object Generator - Screenshot
  • gotAPI/PHP
    gotAPI is a useful online tool for quickly looking up PHP functions and classes. Also check out the Quick PHP look-up widget example in case you’d like to include this awesome look-up feature on your website.gotAPI/PHP - Screenshot
  • koders
    koders is a search engine for open-source and downloadable code. It currently has over a billion lines of code indexed and isn’t limited to just PHP.
  • PECL
    PECL is a directory of all known PHP extensions and a hosting facility for downloading and developing PHP extensions.

In-Browser Tools (Firefox Add-Ons)

  • FirePHP
    FirePHP is a Firefox extension that allows you to log data in Firebug. It has a variety of useful logging features, such as the ability to change your error and exception handling on the fly and to log errors directly to the Firebug console. To learn more about what FirePHP can do, check out the FirePHP guide on how to use FirePHP. For developers using the Zend PHP framework, you might find this guide on using FirePHP with Zend useful.FirePHP - Screenshot
  • phpLangEditor
    phpLangEditor is a very handy Firefox add-on for translating language files and variables in your script.phpLangEditor - Screenshot
  • PHP Lookup
    PHP Lookup is a built-in search bar to help you quickly look up references to PHP syntax.
  • PHP Manual Search
    PHP Manual Search is a handy search bar that searches official PHP documentation from within your Web browser.

Frameworks for PHP

  • Dwoo
    Dwoo is a PHP 5 template engine positioned as an alternative to Smarty. It is (nearly) fully compatible with its templates and plug-ins, but it is being written from scratch and is aimed to go one step further with a cleaner code base.
  • CodeIgniter
    CodeIgniter is a powerful, high-performance, open-source PHP framework that helps you author PHP applications rapidly. CodeIgniter is known for having a light footprint, thereby reducing your server’s work. You can get up and running with CodeIgniter in a jiffy: it has an awesome online manual, a couple of helpful video tutorials and an active user forum.CodeIgniter - Screenshot
  • YII Framework
    Here is a high-performance component-based PHP framework that is supposed to be more efficient than CodeIgniter, CakePHP, ZF and Symfony. An optimal solution for developing large-scale Web applications. Yii supports MVC, DAO/ActiveRecord, I18N/L10N, caching, jQuery-based AJAX support, authentication and role-based access control, scaffolding, input validation, widgets, events, theming and Web services.
  • NetBeans
    A dedicated PHP coding environment and complete integration with web standards. The NetBeans PHP editor is dynamically integrated with NetBeans HTML, JavaScript and CSS editing features such as syntax highlighting and the JavaScript debugger. NetBeans IDE 6.5 fully supports iterative development, so testing PHP projects follows the classic patterns familiar to web developers.
  • Solar
    Solar is a PHP 5 development framework for Web applications derived from the Savant templating engine. Solar uses the MVC architectural pattern and has a host of classes and functions for securing your Web app against SQL injection, cross-website scripting (XSS) and other common exploits.Solar - Screenshot
  • symfony
    symfony is an open-source PHP 5 Web application framework that is well known for its modularity and useful library of classes. To get up and running as fast as possible, you should check out the pragmatic symfony online tutorial called “The symfony 1.2 advent calendar tutorial,” which takes you through a step-by-step example of building your own symfony-based Web application.
  • PEAR – PHP Extension and Application Repository
    PEAR is a popular framework and distribution system for reusable PHP components. The purpose of the framework is to provide a structured library of open-source code for PHP users, a system for code distribution and package maintenance and a standard style for PHP code.
  • Propel
    Propel is an Object-Relational Mapping (ORM) framework for PHP 5. It allows you to access your database using a set of objects, providing a simple API for storing and retrieving data.
  • {{macro}} template engine
    {{macro}} compiles initial templates into executable PHP scripts with very clean syntax (much cleaner than WACT and Smarty) and executes them very fast. The engine doesn’t use an XML-like syntax; there are only two data scopes, global and local, and no more data sources (all data is displayed with regular PHP variables); and the system supports all WACT features such as templates wrapping and including.minify - Screenshot
  • Zend Framework
    The Zend Framework by Zend Technologies (the creators of PHP’s scripting engine) is a popular PHP Web application framework that embraces the principles of PHP OOP; it’s very extensible and has built-in utilities for working with free Web service APIs, such as those of Google, Flickr and Amazon.
  • Qcodo
    Qcodo is an excellent open-source PHP Web application framework. It’s subdivided into two parts: (1) Code Generator, and (2) Qforms. Code Generator handles the creation of object code and PHP and HTML front-end code from your data model. Qforms is an intuitive system for handling and creating complex PHP-driven HTML Web forms. Check out demos of applications that use Qcodo and presentational material that covers Qcodo.Qcodo - Screenshot
  • SAJAX
    SAJAX is a JavaScript and AJAX application framework that works well with PHP (as well as several other server-side scripting languages). See SAJAX at work by going to Wall live demonstration.
  • Smarty
    Smarty is a popular PHP templating system to help you separate PHP logic and front-end code (HTML, CSS, JavaScript). It will keep your projects modular and easier to maintain.
  • CakePHP
    CakePHP is one of the leading PHP frameworks for creating robust, fully-featured Web applications. CakePHP has an extensive and well-organized online manual. If you want to learn via video tutorials, check out the CakePHP screencasts.CakePHP - Screenshot
  • Savant2
    Savant2 is another popular object-oriented PHP templating system. Instead of a special syntax unique to Savant2, you use PHP syntax to develop your project’s template.
  • PHPSpec
    PHPSpec is a simple and intuitive PHP framework. It follows the Behavior-Driven Development principle and therefore allows you to write behavior-oriented code, oftentimes in plain English.

PHP IDEs and Editors

  • PHPEclipse
    PHPEclipse is a popular PHP source-code editor that is open source and runs on all the major operating systems, such as Windows, Linux and Mac OS. It has all the features you’d expect from a PHP source-code editor, such as code-folding, syntax highlighting, hover-over tool tips and support for XDebug and DBG.PHPEclipse - Screenshot
  • PhpED
    PhpED is an excellent IDE for Windows users. It is one of the most robust and feature-packed IDEs currently out on the market and has useful features such as a built-in source-code profiler to find bottlenecks in your PHP source code and excellent integration with third-party apps and services just as front-end code validation.PhpED - Screenshot
  • phpDesigner
    phpDesigner is a lightweight PHP editor/IDE that also handles front-end code and markup remarkably well. Check out the phpDesigner online tutorials, as well as screencasts on phpDesigner to help you learn more about the IDE.phpDesigner - Screenshot
  • Zend Studio
    Zend Studio is an excellent PHP IDE for Eclipse. It’ll help you develop, deploy and manage Rich Internet Applications (RIAs) in an intuitive interface.Zend Studio - Screenshot
  • Aptana PHP
    Aptana PHP is an open-source IDE extension/plug-in to be used in conjunction with Aptana Studio. To learn more, be sure to check out the online documentation about Aptana PHP.
  • PDT
    PDT is a PHP Development Tools framework that’s part of the Eclipse project. PDT includes all the necessary tools for you to create PHP-based Web applications.
  • VS.Php
    VS.Php is a PHP IDE for MS Visual Studio, making it a great IDE for recently converted ASP developers who have used MS VS to develop Web applications. To get you up and running ASAP with VS.Php, check out Jcx.Software’s online tutorials as well as its online documentation.
  • PHPEdit
    PHPEdit is an excellent PHP editor/IDE with a ton of useful features and a very intuitive user interface. To learn more about why PHPEdit is a good IDE, read the 10 reasons to use PHPEdit and view the introductory screencast about PHPEdit.

Sources and Resources

smashingmagazine

Share and enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Netvibes
  • PDF
  • RSS
  • Slashdot
  • StumbleUpon
  • Twitter

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

PHP doesn’t come with native support for making SSH connections via the libssh2 libraries. You must use the PECL SSH2 extensions. Installing them can be tricky, but Kevin van Zonneveld does a great job explaining how to install them over here. So I won’t go there. The new version, 0.11.0, also seems to be compiling more reliably for everyone.

Unfortunately, the library is sparsely documented, and still buggy in some places. And most of the comments posted on http://www.php.net/ssh2 are just plain wrong! Kudos to Mike Sullivan for fixing some of the issues with non-blocking I/O (And let’s not forget to thank Sara Golemon for writing it to begin with!). I list the most conspicuous problems at the bottom of this blog entry for interested parties. Everyone else can use our wrappers to smooth over some of the kinks and make most common tasks trivial to perform.

Our wrapper is released under GNU license and can be used, for example, as follows:

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

All Pertinent Features:

$php_ssh2->execCommandBlockNoOutput()

allows execution of a script ignoring output. Note that without blocking execution manually, 2 ssh2_execs will execute asychronously. So it should also be used for shell scripts that have no output. Why? If you never check for data, it will never block — yes, even in blocking mode! This is subtle … until it clicks.

$php_ssh2->setLogReads($setting = true)

enables or disables read logging on the current SSH2 stream.

$php_ssh2->setLogWrites($setting = true)

enables or disables write logging on the current SSH2 stream.

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

opens a shell for the user — generally not needed and much harder to work with.

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

waits for a specified prompt $prompt_regex (expressed as a regular expression) for $timeout_secs (or 0 to block forever). Returns true or false, leaves response (whether matching or not) buffer in &$buf parameter.

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

writes the specified output to stream. Returns what it was able to write.

The rest of the functions 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 coredumps in versions < 0.11.0. So make sure you upgrade.
2. FreeBSD Ports currently reports a patched “usr/ports/security/pecl-ssh2? version 0.10.0 as 0.11.0 (Not strictly a PECL SSH2 problem, but worth noting 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 warning.
5. One must pass NULL to $pty — not false (like some comments on php.net claim), not “” — otherwise LFs (“\n”) will get changed to CRLFs (“\r\n”). Text files will mostly survive this, but binary data will be corrupted! This took us a solid hour to debug and involved a hex-editor.

As a consequence of some of the above, there is no good way to do non-blocking I/O in versions < 0.11.0. Period. No timeouts, no polling, no selecting. If you need non-blocking I/O to work reliably, you must upgrade to 0.11.0.

seoeggheadv

Share and enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Netvibes
  • PDF
  • RSS
  • Slashdot
  • StumbleUpon
  • Twitter

PHP – Controlo de erros (Debug)

Analise dos logs enquanto se desenvolve

Um dos erros muito comuns no desenvolvimento em qualquer linguagem interpretada é não usarmos a totalidade das vantagens da análise de logs. No PHP para um uso mais eficiente do relatório de erros e avisos, a propriedade error_reporting, no ficheiro php.ini, deverá ser definida como E_ALL.

error_reporting  =  E_ALL

Para um desenvolvimento mais efectivo, desligo sempre a visualização de erros no “screen”, preferindo a análise dos mesmos no ficheiro de log. Para isso defino o display_errors como desligado.

display_errors = Off

Necessitamos ainda, de indicar ao PHP para efectuar o log dos erros para um ficheiro e indicar qual o caminho para o ficheiro onde desejamos gravar as mensagens de erro.

log_errors = On ; Desejamos gravar as mensagens em ficheiro

error_log = “/var/logs/php.log” ; Caminho para o ficheiro onde desejamos gravar as mensagens

Depois basta abrir uma consola onde estou a monitorizar toda a actividade do ficheiro de log do php.

tail -f /var/logs/php.log

Xdebug

A extensão XDebug para PHP permite efectuar profilling e debugging de uma forma muito simples, com funções como xdebug_memory_usage( ), que nos permite analisar o uso da memória do script currente, que também tem correspondente na versão nativa do php, memory_get_usage(), a função xdebug_call_class(), que permite saber em que class foi o método invocado, entre muitas outras.

A extensão XDebug proporciona uma melhoria na visualização de mensagens de erro, podendo-se observar o caminho de execução do script até ao momento em que aconteceu o erro, por exemplo.

Mais informações sobre a extensão na página da mesma.

Share and enjoy:
  • Print
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • LinkedIn
  • Netvibes
  • PDF
  • RSS
  • Slashdot
  • StumbleUpon
  • Twitter

WordPress Themes