A complete library, that grew from WordPress, which offers the most common tasks for creating web applications like user management, HTTP transactions, logging, formatting and more.
The class aims to ease the handling of user management tasks like registration, login, logout, etc. for PHP-MySQL applications.
Do you want to automate the process of generating keywords or meta tags from the content? This is what phpSEO does.
It can create any desired number of keywords from a given string or URL, generate a description and does all with not using any banned words you define.
A PHP class for improving web typography with features like hyphenation, spacing control, wrapping of long text, character replacement for items like ordinal suffixes, trademark or math symbols and more.
The class creates tag clouds from a given array of items where each tag can have its own color, URL and style.
A set of PHP classes for writing to and reading from different file formats, like Excel, PDF and HTML.
It supports many MS Excel features like adding worksheets to a spreadsheet, inserting data and formulas to cells, calculating formulas and much more.
Set of classes for reading and writing to Powerpoint documents and supports adding slides, rotating images and more.
A complete PHP PDF class with features like custom page formats or margins, support for images and automatic page header/footer management.
It can also handle document encryption, PDF annotations, bookmarks and table of content.
A PDF generator class with flexible page format and margins support. It can automatically arrange page breaks and can insert images into documents.
Compared to many PHP zipping libraries, this class does not require “writable temp directory” and can generate + start the download after the client timeouts (good for huge files).
A clean and simple PHP file upload class which can also delete the file uploaded and get the size + filename of it
A PHP class for manipulating and uploading image files on-the-fly.
It can convert, resize and work on uploaded images in many ways: add labels, watermarks and reflections.
A PHP class which can open, resize (smart resizing with no distortion) and save a number of images in multiple formats.
It is explained very well with a detailed tutorial.
A feature-rich PHP library for image manipulations by providing a simple way to loading and saving images from/to files, strings, database, uploads and URL addresses.
You can apply filters, get channels, merge, resize, crop or rotate images using the library.
A powerful PHP image processor with features like resize, rotate, watermak, frame, convert, rotate, crop and much more.
An impressive class to make various calculations on colors like converting between formats (HEX,RGB,HSL/HSV), getting the end color when a color is added to or removed from a pallette and more.
One of the most popular PHP e-mail classes around with features like multiple receivers, embedded images, HTML or plain text, SMTP authentication and much more.
There are also other projects by the same author for form-to-emails, mailing list and bounce management.
The library can send emails using SMTP, sendmail, postfix or a custom method.
It supports SMTP authentication, handling attachments and much more. A great thing is, it is extendable with plugins (there are already ones for antiflood, throttling and logging).
A set of rules for instantly adding server-side validation to our forms.
The rules include “required, length, e-mail, date, numeric, string and much more. Also, you can add custom regular expressions.
It can check user input by comparing to the rules defined and, if necessary, display errors.
The library has methods like required, e-mail, zip codes, IP address, date, time, integer, string and much more.
This PHP captcha class can create complex images or captcha codes and can be easily added into existing forms.
The codes generated can be in custom length, font and use backgrounds. Also, a Flash button can play the mp3 of the image.
This PHP database wrapper offers a human-readable SQL and makes CRUD operations so easy.
It also handles data validation and database manipulation (creating databases, tables, etc.)
A database abstraction library for PHP which supports almost any database (MySQL, PostgreSQL, Interbase, Firebird, Informix, Oracle, MSSQL, Access, SQLite, etc.).
It is fast, supports advanced features like SQL code generation, database-backed sessions and more.
It offers a powerful database abstraction layer with many features for database schema introspection, schema management and PDO abstraction.
Also an object relational mapper (ORM) that sits on top of a powerful database abstraction layer (DBAL) which can write database queries in a proprietary object oriented SQL dialect called Doctrine Query Language (DQL) providing developers a powerful alternative to SQL that maintains flexibility without requiring unnecessary code duplication.
This PHP database class makes using popular databases a breeze.ezSQL with detailed debug functions to find outwhat’s going on in your SQL code.
A free PHP class that is developed by the NY Times development team.
It can convert various input types to many other types like Oracle to MySQL or from a database to a flat file.
The class enables users to backup and restore databases (MySQL, PostgreSQL, MSSQL, etc.) from a web-based interface.
Taking backups of large MySQL databases via scripting (like from phpMyAdmin) is usually an issue as backups may not be completed because of the PHP timeout value.
This class backups databases with small portions every time and continues from where it had stopped.
It extracts data from a database and generates a .CSV file with it.
The class can be set to prompt you to download the generated file or save it in a folder (or both).
A PHP charts class for displaying the data beautifully.
It supports line- bar and pie charts in both 2D and 3D.
An impressive graphing library with support for lots of chart types. It generates web-friendly, small images, can draw 200+ flags with a built-in function and has an internal caching.
Sometimes charts are not what we need and displaying the data within a paragraph, just like a word, works better.
This library exactly does that. Using it, you can create tiny graphics to present your data.
It is the ultimate PHP class for fetching, caching, parsing feeds with lots of integrated methods from social bookmarking integration to one-click subscriptions for popular feed services.
A simple yet powerful RSS parser with features like caching, limiting items and date formatting.
A modular and bandwidth-friendly (transparent GZIP-encoding) RSS parser with an integrated caching system.
There are many sort URL services and it is possible that you may not want to stick to only one.
This class can shorten URLs with TinyURL, Is.gd, Hex.io, Tr.im & Bit.ly API.
Google Translate has a limit of translating 5000 words at once. This smart PHP class can translate unlimited numbe of words by splitting the input, sending the queries one-by-one and merging the results at the end.
An easy to use PHP class for getting Google Analytics data.
To view a working demo, check out the tutorial I had published using the class: FeedCount-Like Google Analytics Counter.
If you want to use these providers at the same time in a project, the library offers an API which enables you to handle all providers in the same way.
It is a PHP wrapper for the Flickr API which returns a friendly array of data to make development easier.
The class has support for uploading photos, getting albums + images inside them and caching.
It makes communicating with the Twitter API (using OAuth) easier and supports almost every feature of the API.
A lightweight weather conditions library that pulls the weather data from the NOAA’s public XML weather feeds.
It can get the temperature (in multiple formats), wind, humidity and an icon for the weather situation.
A complete PHP HTML filter library that can remove malicious code (with a whitelist) and also makes sure the documents are standards-compliant.
A set of PHP classes that provides a direct domain name service API.
It offers direct to-server queries, the ability to process the response in detail but still with a simple interface for the developer.
A simple class for extracting common microformats from a page (currently supports hCard).
It enables you to connect to any XMPP 1.0 server (like Google Talk), send messages and supports SSL/TLS connections.
Quem precisa desenvolver com PHP no Windows sempre enfrenta um pequeno probleminha: como fica o envio de emails? Nos Unix existem configurações adicionais do Sendmail, que facilitam muito a vida, mas no Windows isso não existe.
Uma solução paleativa é instalar um servidor de email (como o hMailServer), e testar na rede interna, usando um domínio falso para sua rede, e criando uma conta de email nele.
Mas a melhor solução eu achei nos comentários do PHP.net: usar o Fake Sendmail (licença BSD). Desenvolvindo originalmente para o Bugzilla pra Windows, com ele é possível usar suas contas e servidores reais de email, através de autenticação SMTP (se necessário). O Fake Sendmail também é usado pelos pacotes “tudo em um” como o XAMPP (Apache + MySQL + PHP).
Por exemplo, eu poderia configurar o PHP em minha máquina para usar um email pessoal do meu provedor para envio de emails pelo PHP.
Iniciando
Os passos foram tirados e adaptados do comentário original em PHP.net:
1 – Baixe o arquivo sendmail.zip de http://glob.com.au/sendmail/. Se você usa XAMPP, ele já vem incluído (pule então o passo 2).
2 – Descompacte para alguma pasta do Windows, mas de preferência com nomes curtos (como por exemplo C:\sendmail).
3 – Edite seu PHP.ini (no WAMP/XAMPP, acesse pelo menu próprio), e configure como abaixo (repare que vamos usar configurações do Sendmail nos Unix):
[mail function]
; For Win32 only.
;SMTP =
; For Win32 only.
;sendmail_from =
; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = "C:\sendmail\sendmail.exe -t"
; Force the addition of the specified parameters to be passed as extra parameters
; to the sendmail binary. These parameters will always replace the value of
; the 5th parameter to mail(), even in safe mode.
;mail.force_extra_paramaters =
4 – Salve suas alterações do PHP.ini.
5 – Agora abra o arquivo SENDMAIL.ini e edite os seguintes campos:
Pegue estas informações com seu provedor de email. No caso do Gmail, pegue as informações da seguinte página de ajuda: Gmail: Configurando o Outlook Express.
[sendmail]
; you must change mail.mydomain.com to your smtp server,
; or to IIS's "pickup" directory. (generally C:\Inetpub\mailroot\Pickup)
; emails delivered via IIS's pickup directory cause sendmail to
; run quicker, but you won't get error messages back to the calling
; application.
smtp_server=smtp.yourdomain.com
; smtp port (normally 25)
; ATENÇÃO: PARA SSL É 465
; ATENÇÃO: PARA GMAIL É 587 (E APENAS COM SSL)!
smtp_port=25
; the default domain for this server will be read from the registry
; this will be appended to email addresses when one isn't provided
; if you want to override the value in the registry, uncomment and modify
default_domain=yourdomain.com
; log smtp errors to error.log (defaults to same directory as sendmail.exe)
; uncomment to enable logging
; error_logfile=sendmail_error.log
; create debug log as debug.log (defaults to same directory as sendmail.exe)
; uncomment to enable debugging
; debug_logfile=sendmail_debug.log
; if your smtp server requires authentication, modify the following two lines
;auth_username=
;auth_password=
; if your smtp server uses pop3 before smtp authentication, modify the
; following three lines
pop3_server=pop.yourdomain.com
pop3_username=you@yourdomain.com
pop3_password=mysecretpassword
; to force the sender to always be the following email address, uncomment and
; populate with a valid email address. this will only affect the "MAIL FROM"
; command, it won't modify the "From: " header of the message content
force_sender=you@yourdomain.com
; sendmail will use your hostname and your default_domain in the ehlo/helo
; smtp greeting. you can manually set the ehlo/helo name if required
hostname=
6 – Reinicie o Apache
7 – Alguns serviços de email precisam de configuração para permitir o acesso POP3. No Gmail, por exemplo, execute os passos descritos em “Enabling POP”.
Conclusão
Vimos como usar o Fake Sendmail para usarmos servidores externos de email no PHP rodando no Windows, simulando facilidades que existem no mundo Unix.
Opcionalmente, você pode habilitar os logs normais e de erro para tentar solucionar algum possível problema. Tente isso antes de me mandar um email, pois apenas com estas informações dos logs eu poderei te ajudar (mas geralmente as informações do log são suficientes para que você consiga resolver sozinho).
Atenção: Algumas pessoas tem tido dificuldade no envio de emails simplesmente porque alguns servidores requerem autenticação segura (SSL). Para isso, você precisa baixar a versão do sendmail com suporte a SSL (a página é a mesma da versão normal), e configurar as portas corretamente no SENDMAIL.ini.
“Ao som de Saliva – Faultline”
Se não houver um motivo muito claro pra usar opendir, readdir e closedir (não consigo pensar em nenhum), a forma mais prática de listar o conteúdo de um diretório é com DirectoryIterator:
Se for necessário listar os arquivos recursivamente, percorrendo todos os subdiretórios, é só usar o RecursiveDirectoryIterator junto com o RecursiveIteratorIterator:
Com um pouco de criatividade, é possível estender essas classes com qualquer lógica facilmente, como por exemplo, para montar uma árvore com a estrutura dos diretórios.
Mesmo que menos comum (e menos útil), colocar uma query string numa URL é um trabalho trivial demais pra ser feito com implode, concatenando tudo ou qualquer outro método engenhoso. Desde o lançamento do PHP 5 é possível contar com a http_build_query:
E o inverso também é possível com as funções parse_url e parse_str:
echo $query['q'];
// anneke van giersbergen
Só fique atento que, por motivos alheios ao bom senso, parse_str por padrão extrai as variáveis no escopo onde foi chamada. É necessário passar um segundo argumento para ter um array gerado por referência, como no exemplo acima com a variável $query.
Dentre todas as implementações, a mais desnecessária costuma ser fsockopen, fwrite, feof, fgets e fclose para ler arquivos remotos por HTTP.
Uma função já resolve:
Isso é possível graças aos protocol wrappers que encapsulam a lógica de acesso aos respectivos protocolos, tal como HTTP. Esta forma de acesso, no entanto, depende da configuração allow_url_fopen estar habilitada no php.ini (que é o padrão).
Para ler os response headers da requisição, utilize fopen com stream_get_meta_data.
E se um dia você quiser impressionar a mulherada, veja a função stream_wrapper_register para criar o seu próprio protocol wrapper.
A coisa fica mais complicada quando o desenvolvedor pensa em usar cURL pra submeter dados por POST para outro servidor. A extensão até tem seu mérito, mas usá-la apenas pra este propósito é um grande equívoco.
As funções que fazem uso dos protocol wrappers aceitam um objeto de stream context, criado pela função stream_context_create, para configurar alguns aspectos do protocolo. As opções de contexto do protocolo HTTP permitem definir, entre outras coisas, o método de acesso (GET, POST, etc) e o conteúdo a ser postado:
$contents = file_get_contents(‘http://exemplo/teste.php’, null, $context);
Quando não for necessário ler o retorno da requisição, basta chamar a url com fopen passando o contexto como quarto argumento.
Vale lembrar que a maioria das funções de stream e filesystem aceitam URLs completas e fazem uso da abstração do protocolo. O que eu vejo muita gente esquecer é que isso inclui a função copy:
O trecho acima vai baixar a imagem remota e salvar no arquivo local /tmp/Terri Clark.jpg. E caso não seja óbvio, “local” se refere a quem está executando o script PHP, que no caso será o seu servidor caso seja um script web, e não o cliente que está acessando pelo browser.
Se o objetivo for realmente repassar o conteúdo remoto para o cliente que estiver acessando pelo browser, o script é igualmente simples:
$meta_data = stream_get_meta_data($handle);
// Repassa todos os headers do servidor remoto para o nosso cliente
foreach ( $meta_data['wrapper_data'] as $header ) {
header($header);
}
// Repassa o conteúdo para o nosso cliente
fpassthru($handle);
Considerando que estamos apenas testando a funcionalidade. Ter um script de proxy totalmente funcional é bem mais complexo, e certamente já tem algo pronto por aí.
Dentre todas as simplificações possíveis, a que mais costuma comover é a função strtotime. Pra quem já está acostumado, parece que não faz mais do que sua obrigação. Mas pra quem ainda faz cálculos com data multiplicando por 86400, chega a parecer mágico:
echo ’Vencimento: ‘, strftime(‘%d/%m/%Y’, strtotime(‘+3 months’));
// Vencimento: 30/08/2009
Mais exemplos você mesmo pode ver no manual do PHP ou na página de Date Input Formats do projeto GNU. Para o nome dos meses e dias da semana ficarem em português, utilize setlocale(LC_TIME, ‘pt_BR’); antes de chamar a função strftime.
Felizmente nunca mais vi nenhum script com aberrações anti-sql-injection, mas há algum tempo era possível encontrar pessoas removendo palavras-chave de SQL de todas as strings que íam para o banco de dados. Se o usuário digitasse palavras como select, delete ou drop, elas eram simplesmente removidas da frase. Isso quando o programador não interrompia o script e acusava o usuário de estar tentando explorar alguma falha de segurança. Eu juro, isso existia.
Ao trabalhar com PDO, a melhor opção (pra não dizer a única!) é utilizar prepare e execute pra separar a query em si dos seus parâmetros:
$sth = $conexao->prepare(‘SELECT nome FROM pessoa WHERE uf = ? AND idade > ?’);
$sth->execute(array($uf, $idade));
while ( $row = $sth->fetch() ) {
echo $row['nome'];
}
Se estiver utilizando drivers nativos, veja as funções mysql_real_escape_string ou mysqli_prepare e mysqli_stmt_bind_param, dependendo da extensão. Certamente outros bancos de dados têm a mesma funcionalidade.
A única preocupação é garantir que os parâmetros não se misturem com a query; não precisa inventar moda e remover o que o usuário digitou.
Outra confusão comum é ao escapar HTML. O objetivo é evitar que o texto digitado por um usuário seja interpretado pelo browser de todos os usuários do site.
Conceitualmente, esta é uma responsabilidade da camada de exibição. O template é que deve utilizar htmlspecialchars antes de gerar a saída na tela, e não antes de salvar no banco. Isso garante que o conteúdo que está no banco é fiel ao que foi digitado pelo usuário e pode ser reaproveitado em outras mídias além do HTML.
O que pode e deve ser feito é filtrar conteúdo realmente indevido, como caracteres inválidos ou espaços extras, dependendo da aplicação.
O PHP não requer (ou suporta) a definição de tipo explicita na declaração de variáveis: o tipo de uma variável é determinado pelo contexto em que a variável é utilizada. Isto significa que, se você assimila um valor string para a variável $var, $var se torna uma string. Se você então assimila um valor inteiro para $var, ela se torna um inteiro.
Um exemplo da conversão automática do PHP é o operador de adição ‘+’. Se qualquer um dos operadores for float, então todos os operadores são avaliados como floats, e o resultado será um float. De outra forma, se os operadores forem interpretados como inteiros então o resultado será um inteiro. Note que isso NÃO muda os tipos dos operadores: apenas muda em como esses operadores são avaliados.
<?php |
Se os últimos dois exemplos lhe parecerem estranhos, veja Conversão de strings para números.
Se você deseja forçar uma variável para ser avaliada como um certo tipo, veja a seção Moldando o tipo (casting). Se você deseja mudar o tipo de uma variável, veja settype().
Se quiser testar qualquer um dos exemplo desta seção, você pode usar a função var_dump().
Nota: O comportamento de uma conversão automática para array é atualmente indefinida.
<?php
$a = "1"; // $a é uma string
$a[0] = "f"; // E com relação aos índices da string? O que acontece?
?>
Desde que o PHP (por razões históricas) suporta indexação de strings através de offsets utilizando a mesma sintaxe da indexação de arrays, o exemplo acima nos deixa um problema: $a se tornou um array sendo o primeiro elemento “f”, ou será que “f” se tornou o primeiro caracter da string $a ?
As versões atuais do PHP interpretam a segunda assimilacao como identificação de deslocamento na string, então $a se torna “f”, o resultado desta conversão automática entretanto pode ser considerada indefinida. O PHP 4 introduziu a nova sintaxe de chaves para acessar caracteres na string. Utilize esta sintaxe em vez do exemplo apresentado acima:
Veja a seção entitulada Acessando caracteres da string para mais informações.
A moldagem de tipos no PHP funciona como no C: o nome de um tipo desejado é escrito entre parênteses antes da variável em que se deseja a moldagem.
As moldagens permitidas são:
Note que tabulações e espaços são permitidos dentro dos parênteses, então o seguinte são funcionalmente equivalentes:
Nota: Em vez de moldar uma variável para string, você também pode englobar a variável entre aspas duplas.
Using Model-View-Controller (MVC) frameworks are the way to go for developing websites today. Nearly all websites need basic functionalities like accessing databases, controlling user logins, templating, and more. WordPress deployments are great, but when needing to quickly build custom web applications, MVC frameworks like CakePHP and CodeIgniter are the way to go. Though these two frameworks have a lot in common, there are some key differences that we will explore.
Commonalities
Both CakePHP and CodeIgniter have some basic things in common:
As Advertised
As advertised, one begins to see some differences between CakePHP and CodeIgniter. CakePHP is characterized by a few statements:
And CodeIgniter is characterized by the phrases:
We will look at some of these differences next, but it should be noted that even just these advertising phrases show a lot. It’s almost as though CodeIgniter promotes itself by being the solution to the things that most developers dislike about CakePHP.
Models
First, let’s look at models. Databases are not only a central component to most any website but they are also frequently accessed. Thus, any framework should be harshly judged according to how good its methodology is for handling database requests. CodeIgniter has an excellent method for grabbing data from the database which eliminates the need for even having a model with most projects since most projects have simple and straightforward database layouts. An example query using method chaining would look like the following,
$publishedAuthors = $this->CI->db->distinct()->select(‘user_id’)->from(‘articles’)->where(‘status !=’,’pending’)->get();
As you can see, even complex queries could be written using method chaining in the CodeIgniter framework. CakePHP on the other hand automatically loads the model for every controller and will throw an error if one isn’t found, tough one can set the controller to not use a model. The query methods are not as intuitive and are more rigid,
$publishedAuthors = $this->Article->find(‘all’, array(
‘fields’ => ‘DISTINCT Article.user_id’,
‘conditions’ => array(‘Article.status !=’ => ‘pending’)
));
As you can see, the methodology isn’t nearly as similar to MySQL as CodeIgniter’s and therefore less intuitive. However, it does have some fancy automation features. It automatically makes associations between framework methods and the database. For example, one could grab all the values in the users table where the status field is zero by,
$users = $this->User->findAllByStatus(0);
CakePHP automatically associates the characters after the ‘findBy’ or ‘findByAll’ methods with fields in the database. Though CakePHP’s models are much more powerful in that they are thoroughly automated, the amount of forced automation is more often than not a hindrance, and overkill at that.
Automation
CakePHP is automated to the max. Every controller requires a model, and every controller’s method requires a view. All these are automatically loaded using the default layout/scaffolding template and the naming schemes are tight. If the controller is named ‘Pages’, it must have a folder ‘views/pages/‘, a model ‘Page’, and a database table named ‘Page’. When it comes to user authentication it is even more so. It uses the ‘Users’ controller by default which requires a table named ‘users’ with an id field named ‘id’. And this is just the beginning of all the tasks that CakePHP automates.
CodeIgniter has a very different approach. It only automates what you want. If you want to load a model or a view and/or use scaffolding then you specify it. And, don’t be deceived, it is not more work than CakePHP because with CakePHP you are forced to create the various files with the right naming schemes, whether you use them or not. In CodeIgniter you only use what you specify and the logic flow is much more apparent when looking at what is going on in the controller.
Speed
Because of how automagic CakePHP is, it is also much more slow. How slow? Well, one benchmarking test run just a few months ago using the Apache Benchmark (ab) tool put CodeIgniter at 9.4 times faster. The test used 10 users hitting CakePHP and CodeIgniter with requests over 60 seconds. CakePHP completed 3,450 requests and CodeIgniter a whopping 32,544. CakePHP processed 57.50 requests per second and CodeIgniter processed 542.37! Other benchmarking tests show the same, one shows CakePHP at 6.10 requests per second and CodeIgniter at 90.88 requests per second–15 times faster!
Documentation
I would have to agree with Mr. Jonathan Snook on this point who notes that CodeIgniter’s documentation is much more organized and thorough than CakePHP’s. I know that I have always found what I needed on their site, though that hasn’t been true for CakePHP in my experience. Yet, perhaps that is because CodeIgniter is much a much more simple and straightforward framework. Even so, both frameworks have solid community support which is where a lot of great code examples and plugins are found.
Conclusion
The claims that CakePHP is simple as cake are ill-founded. It is more advanced than CodeIgniter because it is more automated, but that automation is not easy to understand. CodeIgniter balances simplicity with complexity, that is, it is simple to understand how it achieves complex tasks, and that is exactly what makes it a better framework. As Mr. Snook stated, “[e]verything is in plain sight and you can really see how things work.” Though he wrote in 2007, I find his analysis still accurate.
One article compares CakePHP and CodeIgniter to boxers, the first being a “heavyweight fighter with guns to show” and the second a “lightweight fighter, quick on the feet.” In Round One, “CodeIgniter is already throwing punches left and right while CakePHP is just warming up.” Developers want to be able to start throwing punches in round one with their websites, and CodeIgniter allows them to do it. For new developers and those who haven’t used MVCs it will take a larger amount of time to understand the CakePHP framework to even be able to get in the ring before “throwing punches” and making websites.
Every developer and every website each have their own characteristics that make them who they are. CakePHP forces the developer and the code into very tight boxes. On the other hand, CodeIgniter gives the developer creative freedom and allows websites to be easily shaped into their own character while still fitting the code into a logical and organized framework. Most of all, keep in mind that the essential goal for using any framework is to develop code in a logical and organized manner. If even CodeIgniter is too cramped for you, create your own MVC framework or try out Dave Hensley’s PunyMVC, the “lighter-than-air, no-nonsense, zero-learning-curve, lightning-fast MVC framework in less than 4/5 of a kilobyte (uncompressed)!”
Enquanto desenvolvedores e designers podem debater sobre a importância de diferentes estratégias para a otimização dos mecanismos de busca, uma métrica que simplesmente não pode ser discutida é o PageRank de uma página, ou sua importância em gerar tráfego para o site. Atingir um PageRank melhor foi uma das considerações ao refazermos o design do nosso blog. Podemos discutir como alcançar um PageRank melhor em outra ocasião, mas este artigo irá focar em como você pode recuperar o PageRank de uma página usando uma pequena classe PHP que criei.
As funções básicas dentro dessa classe foram criadas por Jamie Scott – todo o crédito das funções básicas vão para ele. Eu simplesmente coloquei a funcionalidade dentro do formato da classe PHP para facilitar o uso e para atualizar o código para que ele fosse um pouco mais transparente. No que diz respeito às classes PHP, esta é bem pequena:
// Declare the class
class GooglePageRankChecker {
// Track the instance
private static $instance;
// Constructor
function getRank($page) {
// Create the instance, if one isn't created yet
if(!isset(self::$instance)) {
self::$instance = new self();
}
// Return the result
return self::$instance->check($page);
}
// Convert string to a number
function stringToNumber($string,$check,$magic) {
$int32 = 4294967296; // 2^32
$length = strlen($string);
for ($i = 0; $i < $length; $i++) {
$check *= $magic;
//If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31),
// the result of converting to integer is undefined
// refer to http://www.php.net/manual/en/language.types.integer.php
if($check >= $int32) {
$check = ($check - $int32 * (int) ($check / $int32));
//if the check less than -2^31
$check = ($check < -($int32 / 2)) ? ($check + $int32) : $check;
}
$check += ord($string{$i});
}
return $check;
}
// Create a url hash
function createHash($string) {
$check1 = $this->stringToNumber($string, 0x1505, 0x21);
$check2 = $this->stringToNumber($string, 0, 0x1003F);
$factor = 4;
$halfFactor = $factor/2;
$check1 >>= $halfFactor;
$check1 = (($check1 >> $factor) & 0x3FFFFC0 ) | ($check1 & 0x3F);
$check1 = (($check1 >> $factor) & 0x3FFC00 ) | ($check1 & 0x3FF);
$check1 = (($check1 >> $factor) & 0x3C000 ) | ($check1 & 0x3FFF);
$calc1 = (((($check1 & 0x3C0) << $factor) | ($check1 & 0x3C)) << $halfFactor ) | ($check2 & 0xF0F );
$calc2 = (((($check1 & 0xFFFFC000) << $factor) | ($check1 & 0x3C00)) << 0xA) | ($check2 & 0xF0F0000 );
return ($calc1 | $calc2);
}
// Create checksum for hash
function checkHash($hashNumber)
{
$check = 0;
$flag = 0;
$hashString = sprintf('%u', $hashNumber) ;
$length = strlen($hashString);
for ($i = $length - 1; $i >= 0; $i --) {
$r = $hashString{$i};
if(1 === ($flag % 2)) {
$r += $r;
$r = (int)($r / 10) + ($r % 10);
}
$check += $r;
$flag ++;
}
$check %= 10;
if(0 !== $check) {
$check = 10 - $check;
if(1 === ($flag % 2) ) {
if(1 === ($check % 2)) {
$check += 9;
}
$check >>= 1;
}
}
return '7'.$check.$hashString;
}
function check($page) {
// Open a socket to the toolbarqueries address, used by Google Toolbar
$socket = fsockopen("toolbarqueries.google.com", 80, $errno, $errstr, 30);
// If a connection can be established
if($socket) {
// Prep socket headers
$out = "GET /search?client=navclient-auto&ch=".$this->checkHash($this->createHash($page))."&features=Rank&q=info:".$page."&num=100&filter=0 HTTP/1.1rn";
$out .= "Host: toolbarqueries.google.comrn";
$out .= "User-Agent: Mozilla/4.0 (compatible; GoogleToolbar 2.0.114-big; Windows XP 5.1)rn";
$out .= "Connection: Closernrn";
// Write settings to the socket
fwrite($socket, $out);
// When a response is received...
$result = "";
while(!feof($socket)) {
$data = fgets($socket, 128);
$pos = strpos($data, "Rank_");
if($pos !== false){
$pagerank = substr($data, $pos + 9);
$result += $pagerank;
}
}
// Close the connection
fclose($socket);
// Return the rank!
return $result;
}
}
}
Os métodos createHash e checkHash geram as operações matemáticas profundas. Uma vez que elas estiverem fora do caminho, o método check se conecta ao servidor da barra de ferramentas do Google, disfarçando-se como uma barra de ferramenta através do cabeçalho User-Agent, para chegar ao PageRank da página. Um padrão único é usado, uma vez que criar instâncias individuais não é importante:
$rank = GooglePageRankChecker::getRank("davidwalsh.name"); // returns "5"
O número fornecido representa o PageRank para a URL fornecida! Essa classe PHP pode ser usada sozinha, mas eu criei um script comandado pelo MooTools para recuperar o endereço do PageRank através de um simples AJAX.
Este script quick inline do MooTools responde ao clique de um botão, gerando um chamado AJAX para um script PHP que executa a classe fornecida acima:
// When the DOM is ready
window.addEvent("domready",function() {
// When the form is submitted...
var form = document.id("rankForm"), request, display, domain;
form.addEvent("submit",function(e) {
// Stop the event
if(e) e.stop();
// Create request, if not already created
if(!request) {
domain = document.id("domain");
display = document.id("rankerDisplay");
request = new Request({
url: "pagerank-checker.php",
method: "post",
onComplete: function(response) {
display.setStyle("display","block").set("text","Page rank for " + domainValue + " is: " + response);
}
});
}
// Get the value fo the URL
domainValue = domain.get("value");
// Send the request
request.send({ data: { domain: domainValue } });
});
});
Utilizando este pedaço de Javascript como no exemplo, você pode facilmente adicionar um verificador javascript para o Google PageRank com o framework que você escolher.
⁂
Texto original em disponível em http://davidwalsh.name/google-pagerank