terça-feira, 29 de maio de 2012

Utilização do CURL do PHP

Veja bem,

Este é um exemplo de utilização do CURL.


        $ch = curl_init();
        $url = "http://" .  $_SERVER['SERVER_NAME'] . "/cliente/utilitario/lerrg.php?rg=" . $rg;                      
        $timeout = 20;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false); 
        curl_setopt($ch, CURLOPT_NOBODY, false); // remove body 
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $data = curl_exec($ch);              
        curl_close($ch);
        return $data;
Coloquei em vermelho dois parâmetros "traiçoeiros". Apesar de estar escrito Header e Body, eles não se referem ao Header ou Body da página que você está chamando.
Utilize esta configuração para acessar o conteúdo da página sem problemas.

That's it!

Criar um índice no MySQL

Veja bem,

Exemplo de criação de índice:

CREATE INDEX indx_cliente ON Cliente (descricao);

indx_cliene = nome do índice.
Cliente = nome da tabela.
descricao = nome da coluna.

That's it.

Alien Planet - Documentário

segunda-feira, 28 de maio de 2012

API Google

Veja bem,
Você também está querendo usar as API's do Google? Em especial o GoogleMaps com Geocoding? Faça o seguinte
Acesse
https://code.google.com/apis/console 
Nesse endereço você consegue a Key, sem a qual você não consegue fazer nada.


Referência:

Obtaining an API Key

All Maps API applications* should load the Maps API using an API key. Using an API key enables you to monitor your application's Maps API usage, and ensures that Google can contact you about your application if necessary. If your application's Maps API usage by exceeds the Usage Limits, you must load the Maps API using an API key in order to purchase additional quota.
* Google Maps API for Business developers must not include a key in their requests. Please refer to Loading the Google Maps JavaScript API for Business-specific instructions.
To create your API key:
  1. Visit the APIs Console at https://code.google.com/apis/console and log in with your Google Account.
  2. Click the Services link from the left-hand menu.
  3. Activate the Google Maps API v3 service.
  4. Click the API Access link from the left-hand menu. Your API key is available from the API Access page, in the Simple API Access section. Maps API applications use the Key for browser apps.

Mudar o domínio localhost - Windows

Às vezes você precisa mudar o domínio da sua máquina, ou acrescentar outro além do localhost que você já tem.

Know-how:
C:\Windows\System32\drivers\etc\host

Abaixo acrescentei o domínio netdaniels.com.

Depois disso é só reiniciar a máquina e testar.


# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

# localhost name resolution is handled within DNS itself.
# 127.0.0.1       localhost
# ::1             localhost

127.0.0.1 localhost
127.0.0.1 netdaniels.com


Vocabulário de Francês - 01

Estou lendo um livro em francês chamado Le Monde de Sophie. Eu vou lendo e anotando as palavras que não conheço para depois procurar no dicionário. Eis mais uma lista:


le potage  a sopa
couette  edredão
sommeil  dormir
placard  armário
l'étagère  a prateleira
mi-bas  Elevações de Joelho
la haie  o hedge
remonta  subiu
demeures  casas
atteignirent  alcançado
lovée  coiled
canapé  sofá
plumes d'oie  ganso
tapissé  forrado
songe  sonho
facteur  fator
lézarda  lézarda
déterrer  desenterrar
arpenter  vistoria
fusil  rifle
incunable  incunábulo
berceau  berço
la poudre  pó
à tour de bras  um braço de cada vez


Algumas traduções me parecem esquisitas, se você perceber alguma coisa errada, comente. Obrigado.

domingo, 27 de maio de 2012

Classe de validação : CValidator

Veja bem,

Se você está que nem eu, desenvolvendo com yii já deve ter chegado a questão das classes de validação. Se não chegou, vai chegar.

No meu caso construí uma classe de validação para CEP.

Primeiro passo:

Na classe Model


    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('code',
                    'required'),
            array(
                'code','cep'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array(
                'id, code, noise, accessibility, neighborhood, afforestation, violence',
                'safe',
                'on' => 'search'),
            );
    }

//Segundo passo criar a classe de validação..........


class cep extends CValidator
{ //início da Classe

    public function validateAttribute($object, $attribute)
    {
        $message = utf8_encode("não é válido ou não existe.");
        if (!$this->validaCEP($object->$attribute)) {
            $message = $this->message !== null ? $this->message : Yii::t('cep',
                '{attribute} ' . $message);
            $this->addError($object, $attribute, $message);
        }

    }


    public function clientValidateAttribute($object, $attribute)
    {
        return "";

    }

    private function validaCEP($cep)
    {
        $cep = trim($cep);
        if (!is_numeric($cep)) {
            return false;
        }
        if (strlen($cep) != 8) {
            return false;
        }
       
        $content = $this->get_data("utilitario/lercep.php?cep=$cep");
        $content = trim($content);
       
        if (strlen($content) == 0)
        {
            return false;
        }
               
        return true;

    }

    function get_data($url)
    {
        $ch = curl_init();
        $timeout = 5;
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }

} //fim da Classe


Para mais detalhes acesse este link
http://abelcorreadias.blogspot.com.br/2012/01/criando-um-validator-para-o-campo-cpf.html

PS: utilitario/lercep.php não é um php mágico que acesse o cep de algum site como república virtual ou mesmo o site do correio. Estou acessando minha própria base de CEP. Atenção: a base de CEP do correio é gigantesca.