Category Archives: Dicas e Códigos
Como criar programas para Windows (desktop)
Para começar a desenvolver programas, é necessário antes de tudo decidir qual linguagem se deve trabalhar. Uma das mais recomendadas no mercado hoje em dia e a linguagem JAVA. Entretanto iremos apresentar um pequeno exemplo de uma calculadora simples construída através do programa DEV-C++, que pode ser baixado gratuitamente.
#include <windows.h>
#include <stdlib.h>
LRESULT CALLBACK WindowProcedure (HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain (HINSTANCE hThisInstance,
HINSTANCE hPrevInstance,
LPSTR lpszArgument,
int nFunsterStil)
{
HWND hwnd;
MSG messages;
WNDCLASSEX wincl;
wincl.hInstance = hThisInstance;
wincl.lpszClassName = "WindowsApp";
wincl.lpfnWndProc = WindowProcedure;
wincl.style = CS_DBLCLKS;
wincl.cbSize = sizeof (WNDCLASSEX);
wincl.hIcon = LoadIcon (NULL, IDI_APPLICATION);
wincl.hIconSm = LoadIcon (NULL, IDI_APPLICATION);
wincl.hCursor = LoadCursor (NULL, IDC_ARROW);
wincl.lpszMenuName = NULL;
wincl.cbClsExtra = 0;
wincl.cbWndExtra = 0;
wincl.hbrBackground = (HBRUSH) COLOR_BACKGROUND;
if (!RegisterClassEx (&wincl))
return 0;
hwnd = CreateWindowEx (
0,
"WindowsApp",
"Calculadora © Por Toca Digital",
WS_OVERLAPPEDWINDOW,
350,
250,
550,
100,
HWND_DESKTOP,
NULL,
hThisInstance,
NULL
);
ShowWindow (hwnd, nFunsterStil);
while (GetMessage (&messages, NULL, 0, 0))
{
TranslateMessage(&messages);
DispatchMessage(&messages);
}
return messages.wParam;
}
#define ID_BUTTONmais 1001
#define ID_BUTTONmenos 1002
#define ID_BUTTONvezes 1003
#define ID_BUTTONdividir 1004
#define ID_BUTTONurl 1005
HINSTANCE g_inst;
HWND EditNum1,EditNum2,EditTotal,ButtonMais,ButtonMenos,ButtonVezes,ButtonDividir,ButtonURL;
void DesenharObjectos(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
EditNum1 = CreateWindowEx (
WS_EX_CLIENTEDGE,
//valor inicial (esquerda): 0
"EDIT",
"0",
WS_VISIBLE|WS_CHILD|WS_BORDER|ES_RIGHT ,
30, 30, 50, 20,
hwnd,
NULL,
g_inst,
NULL
);
EditNum2 = CreateWindowEx (
//valor inicial (direita): 0
WS_EX_CLIENTEDGE,"EDIT", "0",
WS_VISIBLE|WS_CHILD|WS_BORDER,
160, 30, 50, 20,
hwnd, NULL, g_inst, NULL );
EditTotal = CreateWindowEx (
WS_EX_CLIENTEDGE,"EDIT", "",
WS_VISIBLE|WS_CHILD|WS_BORDER,
220, 30, 50, 20,
hwnd, NULL, g_inst, NULL );
ButtonMais = CreateWindowEx (
0,
"BUTTON",
"+",
WS_VISIBLE|WS_CHILD,
80, 30, 20, 20,
hwnd,
(HMENU)ID_BUTTONmais,
g_inst,
NULL
);
ButtonMenos = CreateWindowEx (
0, "BUTTON", "-",
WS_VISIBLE|WS_CHILD,
100, 30, 20, 20,
hwnd, (HMENU)ID_BUTTONmenos, g_inst, NULL);
ButtonVezes = CreateWindowEx (
0, "BUTTON", "*",
WS_VISIBLE|WS_CHILD,
120, 30, 20, 20,
hwnd, (HMENU)ID_BUTTONvezes, g_inst, NULL);
ButtonDividir = CreateWindowEx (
0, "BUTTON", "/",
WS_VISIBLE|WS_CHILD,
140, 30, 20, 20,
hwnd, (HMENU)ID_BUTTONdividir, g_inst, NULL);
CreateWindowEx (
0,
"STATIC",
"=",
WS_VISIBLE|WS_CHILD,
212, 31, 5, 20,
hwnd,
NULL,
g_inst,
NULL
);
ButtonURL = CreateWindowEx (
0,
"BUTTON",
"www.tocadigital.com.br",
WS_VISIBLE|WS_CHILD,
272, 30, 230, 20,
hwnd,
(HMENU)ID_BUTTONurl,
g_inst,
NULL
);
SendMessage((HWND) EditNum1,
(UINT) WM_SETFONT,
(WPARAM) GetStockObject(DEFAULT_GUI_FONT),
(LPARAM) lParam
);
SendMessage((HWND) EditNum2,(UINT) WM_SETFONT, (WPARAM) GetStockObject(DEFAULT_GUI_FONT),(LPARAM) lParam);
SendMessage((HWND) EditTotal,(UINT) WM_SETFONT, (WPARAM) GetStockObject(DEFAULT_GUI_FONT),(LPARAM) lParam);
SendMessage(
(HWND) ButtonMais,
(UINT) WM_SETFONT,
(WPARAM) GetStockObject(DEFAULT_GUI_FONT),
(LPARAM) lParam
);
SendMessage((HWND) ButtonMenos,(UINT) WM_SETFONT, (WPARAM) GetStockObject(DEFAULT_GUI_FONT),(LPARAM) lParam);
SendMessage((HWND) ButtonVezes,(UINT) WM_SETFONT, (WPARAM) GetStockObject(DEFAULT_GUI_FONT),(LPARAM) lParam);
SendMessage((HWND) ButtonDividir,(UINT) WM_SETFONT, (WPARAM) GetStockObject(DEFAULT_GUI_FONT),(LPARAM) lParam);
}
void abreURL(){
char szPath[] = "http://www.tocadigital.com.br";
HINSTANCE hRet = ShellExecute(
HWND_DESKTOP, //Parent window
"open", //Operation to perform
szPath, //Path to program
NULL, //Parameters
NULL, //Default directory
SW_SHOW); //How to open
}
char s_valor1[20] = "0", s_valor2[20] = "0", s_total[20] = "0";
int valor1, valor2, total;
LRESULT CALLBACK WindowProcedure (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_CREATE:
DesenharObjectos(hwnd,message,wParam,lParam);
break;
case WM_COMMAND:
if ((HIWORD(wParam) == BN_CLICKED))
{
SendMessage(
(HWND) EditNum1,
(UINT) EM_GETLINE,
(WPARAM) 1,
(LPARAM) &s_valor1
);
SendMessage((HWND)EditNum2,(UINT)EM_GETLINE,(WPARAM)1,(LPARAM) &s_valor2);
valor1 = atoi(s_valor1);
valor2 = atoi(s_valor2);
switch (LOWORD(wParam))
{
case ID_BUTTONmais:
total = valor1+valor2;
break;
case ID_BUTTONmenos:
total = valor1-valor2;
break;
case ID_BUTTONvezes:
total = valor1*valor2;
break;
case ID_BUTTONdividir:
total = valor1 / valor2;
break;
case ID_BUTTONurl:
abreURL();
break;
}
itoa (total,s_total,10);
SendMessage(
(HWND) EditTotal,
(UINT) WM_SETTEXT,
(WPARAM) 0,
(LPARAM) &s_total
);
}
break;
case WM_DESTROY:
PostQuitMessage (0);
break;
default:
return DefWindowProc (hwnd, message, wParam, lParam);
}
return 0;
}
Como criar popup em div box
Hoje em dia os navegadores já vêm com a funcionalidade de bloqueio de pop-ups, ou janelas sobressalentes, porém existe uma forma de evitar que o navegador bloqueie uma informação ou algum conteúdo que seja importante ser aberto com uma mensagem atual, ou uma propaganda… ou o que quer que seja. Esta forma é através das DIVs, você pode fixar uma div sobre seu site, para isso, basta criar uma div fixa na tela, com um botão flutuante à esquerda para que seja fechada.
Uma forma de fazer isso, é justamente através de uma simples função em Javascript, que você pode definir a abertura e o fechamento da mesma.
Então, para fazer a sua div, vc deve definir as regras para que ela esteja visível ou invisível (defina em seu CSS o parâmetro: display:block; ou display:none, também pode ser usado visibility:hidden, ou visibility:visible), isso vai depender do comportamento que você deseja para sua div.
Então sua html ficaria mais ou menos assim:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Teste de Popup</title>
<script type="text/javascript">
// abre a DIV
function abreJanela(id){
var obj = document.getElementById(id);
$(obj).style.display='block';
}
// fecha a DIV
function fechaJanela(id){
var obj = document.getElementById(id);
obj.style.display='none';
}
</script>
<style type="text/css">
body {
background: #000000;
}
#popup {
font-family:Arial, Helvetica, sans-serif;
display:block;
position:absolute;
width:300px;
height:450px;
left:50%;
top:30px;
border:1px solid #000000;
padding:6px;
color:#000000;
background: #fff;
z-index:300;
}
#popup p{ line-height:18px}
#popup a.fechar {
color:#000033;
text-align:right;
float:right;
text-decoration:none;
font-family:Arial, Helvetica, sans-serif;
width:20px;
}
#popup a:hover.fechar { color:#003399
}
</style>
</head>
<body>
<a href="javascript:;" onclick="abreJanela('popup')">Abrir Popup</a>
<div id="popup">
<a href="javascript:;" onclick="fechaJanela('popup')" class="fechar">X</a>
<!--//aqui entra seu conteúdo-->
<p>teste de mensagem</p>
</div>
</body>
</html>
Porém você pode implementar ainda mais seu código javascript, usando recursos do jQuery:
conforme abaixo:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
// abre a DIV
function abreJanela(id){
var obj = document.getElementById(id);
$(obj).fadeIn("slow");
}
// fecha a DIV
function fechaJanela(id){
var obj = document.getElementById(id);
$(obj).fadeOut("slow");
}
</script>
Como fazer URLs Amigáveis com módulo de reescrita para o seu site
Fazer URL amigável não tem segredo nenhum, parece complicado para quem não conhece, mas é bem mais fácil do que parece.
Entretanto, antes de começarmos a sair escrevendo as regras é importante entender um pouco do conceito:
A url amigável é basicamente uma forma mais inteligente de indexar seus sites, facilitando a busca através do contexto dentro do seu site, ou seja, se de repente o usuário escrever no google a frase “hoje vai ter sol” e sua url estiver com hoje-vai-ter-sol, significa que a possibilidade do seu site vir a ser o primeiro é muito grande, pois ele é indexado automaticamente pelo buscador, caso o site esteja cadastrado…
Você pode se aprofundar muito mais sobre isso, procurando pelo termo SEO (Search Engine Optimization) no google, tem muitos sites que abordam bem esse assunto,no nosso caso nos iremos somente partir deste princípio, e começar a trabalhar com a ferramenta de URL amigável.
A URL amigável no “mod_rewrite” nada mais são do que regras estabelecidas em um arquivo de texto sem extensão, chamado “.htaccess” que correspondem à regras que interagem no comportamento de resposta às páginas enviadas pelo PHP ao servidor.
Antes de definir as regras deste arquivo, primeiramente, você precisará ter que habilitar o módulo rewrite do servidor, no caso do localhost, você deverá editar seu arquivo http.conf, para localizá-lo, basta você digitar na busca dentro da pasta onde está seu programa servidor, xampp, wamp, phpeasy…sei lá… localize com a busca do windows dentro da pasta, digite sem aspas… “httpd.conf”, quando encontrá-lo, abra ele com o bloco de notas e procure o termo rewrite, retire o símbolo de quadrado “# ” na frente do “LoadModule rewrite_module modules/mod_rewrite.so”, assim ela deixa de ser um comentário…e passa a ser um módulo ativo, agora basta reiniciar o apache para que tudo esteja funcionando de forma adequada…
Agora que está tudo funcionando, tudo fica muito mais fácil…
1º – Crie uma pasta no seu diretório root htpdocs, www, sei lá… com o nome: teste_rewrite
sua URL deverá ficar assim: http://localhost/teste_rewrite/
Maravilha, agora vamos entender e criar este arquivo de regras, o tal do .htaccess
Para começar abra o bloco de notas e digite os procedimentos a seguir…
1º - Definimos o cabeçalho das regras, então iremos informar que o modo de releitura deverá estar ativo:
Options +FollowSymLinks RewriteEngine On
2º – Agora definimos que arquivos e diretórios deverão ignorar as regras de URL amigável:
RewriteCond %{REQUEST_FILENAME}!-f
RewriteCond %{REQUEST_FILENAME}!-d
3º – Muito bem, se você chegou até aqui com sucesso, significa que o resto é mais fácil ainda…
Então vamos supor que a URL do seu site hoje faz o seguinte caminho:
http://localhost/teste_rewrite/index.php
bom, nossa 1ª regra para o index deverá ser (observe que a regra começa com ^ e termina com $):
RewriteRule ^home$ index.php
Isso significa que sua URL vai passar a ser: http://localhost/teste_rewrite/home
Agora vamos criar uma 2ª regra, suponhamos que sua URL seja assim:
http://localhost/teste_rewrite/produtos.php?id=123&titulo=computador+azul+e+branco
e vc quer que sua URL fique assim:
http://localhost/teste_rewrite/produto-123_computador-azul-e-branco
Então faremos a regra assim:
RewriteRule ^produto-(.*)_(.*)$ index.php?id=$1&titulo=$2
Ou seja, $1 e $2 são as variável sequenciais, onde isso: (.*) será substituído por “qualquer valor” desta posição, que no caso é logo depois da palavra “produto-”, exemplo: produto-(123)_(computador-azul-e-branco)…
Sendo assim, vc pode criar suas regras como quiser a partir deste princípio:
Outro exemplo de regra…
http://localhost/teste_rewrite/index.php?id=20&cat=martelo&data=21-10-2010
RewriteRule ^categoria-(.*)-(.*)-data_(.*)$ index.php?id=$1&cat=$2&data=$3
Ficaria assim:
http://localhost/teste_rewrite/categoria-20-martelo-data_21-10-2010
Ok, esta parte parece fácil não é mesmo, mas para que suas URL fiquem com o título bonitinho, tipo: “minha-mae-mandou-eu-escolher-este-daqui”, eu recomendo que vc utilize o código abaixo, que é uma função gratuita com licença GPL, que pode ser usada para o seu bom proveito, do sistema do wordpress…
eu adaptei para: slug(“aqui vem seu texto”);
echo slug(“aqui vem seu texto”);
irá retornar:
aqui-vem-seu-texto
pegue o código abaixo:
<?php
//primeira parte
/**
* Converts all accent characters to ASCII characters.
*
* If there are no accent characters, then the string given is just returned.
*
* @since 1.2.1
*
* @param string $string Text that might have accent characters
* @return string Filtered string with replaced "nice" characters.
*/
function remove_accents($string) {
if ( !preg_match('/[\x80-\xff]/', $string) )
return $string;
if (seems_utf8($string)) {
$chars = array(
// Decompositions for Latin-1 Supplement
chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
chr(195).chr(135) => 'C', chr(195).chr(136) => 'E',
chr(195).chr(137) => 'E', chr(195).chr(138) => 'E',
chr(195).chr(139) => 'E', chr(195).chr(140) => 'I',
chr(195).chr(141) => 'I', chr(195).chr(142) => 'I',
chr(195).chr(143) => 'I', chr(195).chr(145) => 'N',
chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
chr(195).chr(159) => 's', chr(195).chr(160) => 'a',
chr(195).chr(161) => 'a', chr(195).chr(162) => 'a',
chr(195).chr(163) => 'a', chr(195).chr(164) => 'a',
chr(195).chr(165) => 'a', chr(195).chr(167) => 'c',
chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
chr(195).chr(177) => 'n', chr(195).chr(178) => 'o',
chr(195).chr(179) => 'o', chr(195).chr(180) => 'o',
chr(195).chr(181) => 'o', chr(195).chr(182) => 'o',
chr(195).chr(182) => 'o', chr(195).chr(185) => 'u',
chr(195).chr(186) => 'u', chr(195).chr(187) => 'u',
chr(195).chr(188) => 'u', chr(195).chr(189) => 'y',
chr(195).chr(191) => 'y',
// Decompositions for Latin Extended-A
chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
// Euro Sign
chr(226).chr(130).chr(172) => 'E',
// GBP (Pound) Sign
chr(194).chr(163) => '');
$string = strtr($string, $chars);
} else {
// Assume ISO-8859-1 if not UTF-8
$chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
.chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
.chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
.chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
.chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
.chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
.chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
.chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
.chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
.chr(252).chr(253).chr(255);
$chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
$string = strtr($string, $chars['in'], $chars['out']);
$double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
$double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
$string = str_replace($double_chars['in'], $double_chars['out'], $string);
}
return $string;
}
//segunda parte
/**
* Checks to see if a string is utf8 encoded.
*
* NOTE: This function checks for 5-Byte sequences, UTF8
* has Bytes Sequences with a maximum length of 4.
*
* @author bmorel at ssi dot fr (modified)
* @since 1.2.1
*
* @param string $str The string to be checked
* @return bool True if $str fits a UTF-8 model, false otherwise.
*/
function seems_utf8($str) {
$length = strlen($str);
for ($i=0; $i < $length; $i++) {
$c = ord($str[$i]);
if ($c < 0x80) $n = 0; # 0bbbbbbb
elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
else return false; # Does not match any model
for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
return false;
}
}
return true;
}
//terceira parte
/**
* Encode the Unicode values to be used in the URI.
*
* @since 1.5.0
*
* @param string $utf8_string
* @param int $length Max length of the string
* @return string String with Unicode encoded for URI.
*/
function utf8_uri_encode( $utf8_string, $length = 0 ) {
$unicode = '';
$values = array();
$num_octets = 1;
$unicode_length = 0;
$string_length = strlen( $utf8_string );
for ($i = 0; $i < $string_length; $i++ ) {
$value = ord( $utf8_string[ $i ] );
if ( $value < 128 ) {
if ( $length && ( $unicode_length >= $length ) )
break;
$unicode .= chr($value);
$unicode_length++;
} else {
if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;
$values[] = $value;
if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
break;
if ( count( $values ) == $num_octets ) {
if ($num_octets == 3) {
$unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
$unicode_length += 9;
} else {
$unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
$unicode_length += 6;
}
$values = array();
$num_octets = 1;
}
}
}
return $unicode;
}
//quarta parte
/**
* Sanitizes title, replacing whitespace with dashes.
*
* Limits the output to alphanumeric characters, underscore (_) and dash (-).
* Whitespace becomes a dash.
*
* @since 1.2.0
*
* @param string $title The title to be sanitized.
* @return string The sanitized title.
*/
function slug($title) {
$title = strip_tags($title);
// Preserve escaped octets.
$title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
// Remove percent signs that are not part of an octet.
$title = str_replace('%', '', $title);
// Restore octets.
$title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
$title = remove_accents($title);
if (seems_utf8($title)) {
if (function_exists('mb_strtolower')) {
$title = mb_strtolower($title, 'UTF-8');
}
$title = utf8_uri_encode($title, 200);
}
$title = strtolower($title);
$title = preg_replace('/&.+?;/', '', $title); // kill entities
$title = str_replace('.', '-', $title);
$title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
$title = preg_replace('/\s+/', '-', $title);
$title = preg_replace('|-+|', '-', $title);
$title = trim($title, '-');
return $title;
}
//use slug("sua frase para url");
?>
Link no botão do arquivo flash
Para inserir um arquivo flash em sua html sem que no código fonte venha escrita a extensão “swf” é muito simples, basta passar a extensão para dentro de um arquivo externo de JavaScript, com a extensão .js , observe o exemplo abaixo:
1º – passo: crie o arquivo flash.js com o seguinte código:
function carregaFlash(url,arquivo,largura,altura)
{
var caminho=arquivo+'.swf?endereco='+url;
document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0" width="'+largura+'" height="'+altura+'">');
//if (navigator.appName.indexOf('Microsoft') != -1 && msieversion() < 7)
//{ largura=largura+4;
//}
document.write('<param name="movie" value="'+caminho+'">');
document.write('<param name="quality" value="high">');
document.write('<param name="wmode" value="transparent">');
document.write('<param name="AllowScriptAccess" value="sameDomain">');
document.write('<param name="menu" value="false">');
document.write('<embed src="'+caminho+'" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" width="'+largura+'" height="'+altura+'" wmode="transparent"></embed>');
document.write('</object>');
}
2º passo: inclua seu arquivo js na html, entre as tags <head></head> da sua página com o caminho abaixo:
<script type="text/javascript" src="flash.js"></script>
3º passo: coloque no seu <body></body> a chamada do seu arquivo swf:
<script>
carregaFlash('http://www.tocadigital.com.br','nome_do_seu_arquivo_sem_ponto_swf',300,300);
</script>
Veja o exemplo o código funcionando:
http://www.tocadigital.com.br/biblioteca/flash.html
Baixe o exemplo do botão:
http://www.tocadigital.com.br/biblioteca/flash.fla
Baixe o código js:
http://www.tocadigital.com.br/biblioteca/flash.txt
Função simples e prática para carregar páginas em AJAX
Tanto o Mozilla Firefox como o Internet Explorer às vezes fazem com que uma página enviada via AJAX não seja carregada adequadamente.
Aqui temos um exemplo simples que corrige estas falhas, e faz com que arquivos como flash, e scripts sejam carregados sem erros, para isso iremos utilizar a tecnologia do jQuery, e usar o API do Google, para que seja carregado mais rapidamente:
1º – colocamos nas tags HEAD da nossa index os APIs para JQuery, Ajax, etc…
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"> </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.js" type="text/javascript"> </script>
2º criamos o seguinte script:
<script type="text/javascript" >
function abreURL(url,metodo,onde){
if(metodo=='POST'){
// metodo post
$.post(url, function(data) {
// página do carregador (loading)
$("#carregador").show();
$( "#"+onde).load(url);
});
}
else if(metodo=='GET'){
// metodo get
$.get(url, function(data) {
// página do carregador (loading)
$("#carregador").show();
$( "#"+onde).load(url);
});
}
}
</script>
3º Agora criamos na HTML o link que irá passar a função do AJAX e enviar a página e suas e se tiver também, as requisições junto:
<a onclick="abreURL('pagina_nova.php?id=10','GET','conteudo')" href="#">
Abrir na div conteúdo
</a>
4º depois criamos na nossa index a div que irá receber a página e os parâmetros:
<div id="conteudo"> <div id="carregador">Carregando...</div> Aqui irá carregar a pagina nova e os dados do banco de id=10.</div>
Pronto.
Após colocar estas construções, seu site já estará navegando via Ajax.
Baixe este exemplo:
Modelo AJAX com jQuery
Dica para animação em flash
Se você for criar uma animação em flash, provavelmente vai precisar incluir sons no seu site, aqui vai a dica de alguna sites que oferecem arquivos de sons e outras coisas para arquivos em flash:
http://www.grsites.com/archive/sounds/
Tratamento de Webserver de Notícias
Como formatar um serviço de notícias que vem do webservice, este código foi feito para tratar as notícias que eram fornecidas pela http://www.enfoque.com.br/, você pode utilizar isso em diversos webservices que dispõe desta mesma estrutura de XML, pode ser tanto em SOAP, como ASMX, isso varia de acordo com o servidor que disponibiliza o serviço. Você mesmo pode habilitar este tipe de serviço em algum servidor, basta saber como montar um webservice, confira no site: http://devedge-temp.mozilla.org/viewsource/2002/soap-overview/index_pt_br.html como montar um webservice.
formato XML:
<?xml version="1.0" encoding="utf-8"?> <DataSet xmlns="http://tempuri.org/"> <xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"> <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:Locale="pt-BR"> <xs:complexType> <xs:choice maxOccurs="unbounded"> <xs:element name="Table"> <xs:complexType> <xs:sequence> <xs:element name="idpagina" type="xs:int" minOccurs="0" /> <xs:element name="data" type="xs:string" minOccurs="0" /> <xs:element name="titulo" type="xs:string" minOccurs="0" /> <xs:element name="URL" type="xs:string" minOccurs="0" /> </xs:sequence> </xs:complexType> </xs:element> </xs:choice> </xs:complexType> </xs:element> </xs:schema> <diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1"> <NewDataSet xmlns=""> <Table diffgr:id="Table1" msdata:rowOrder="0"> <idpagina>2733487</idpagina> <data>2011-04-18 07:48:13.000</data> <titulo>Bolsas da Ásia e da Europa fecham em reação à medidas da economia chinesa</titulo> <URL>http://www.enfoque.com.br/headlines/ENEWS/042011/25458.asp</URL> </Table> <Table diffgr:id="Table2" msdata:rowOrder="1"> <idpagina>2733489</idpagina> <data>2011-04-18 07:57:49.000</data> <titulo>Dilma: pincipais objetivos de viagem à China foram alcançados</titulo> <URL>http://www.enfoque.com.br/headlines/ENEWS/042011/25459.asp</URL> </Table> <Table diffgr:id="Table3" msdata:rowOrder="2"> <idpagina>2733511</idpagina> <data>2011-04-18 08:30:03.000</data> <titulo>Agenda Econômica Semanal</titulo> <URL>http://www.enfoque.com.br/headlines/enews/agendaSemanal.asp</URL> </Table> <Table diffgr:id="Table4" msdata:rowOrder="3"> <idpagina>2733512</idpagina> <data>2011-04-18 08:30:03.000</data> <titulo>Agenda Econômica Semanal</titulo> <URL>http://www.enfoque.com.br/headlines/enews/agendaSemanal.asp</URL> </Table> </diffgr:diffgram> </DataSet>
página de tratamento do XML do webserver:
<?php
function DataBr($data = "0000-00-00 00:00:00") {
if ($data == "0000-00-00 00:00:00" or $data == NULL) {
return NULL;
exit();
}
$temp = explode(" ", $data);
$temp2 = explode("-", $temp[0]);
$temp3 = explode(".",$temp[1]);
$temp4 = explode(":",$temp3[0]);
//$this->debug($data);
if (count($temp) > 1) {
return trim($temp2[2].'/'.$temp2[1].' '.$temp4[0].":".$temp4[1]);
} else {
return trim($temp2[2].'/'.$temp2[1].$temp2[0]);
}
}
function my_xml2array($__url)
{
$xml_values = array();
$contents = $__url; //file_get_contents($__url);
$parser = xml_parser_create('');
if(!$parser)
return false;
xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, 'UTF-8');
xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
xml_parse_into_struct($parser, trim($contents), $xml_values);
xml_parser_free($parser);
if (!$xml_values)
return array();
$xml_array = array();
$last_tag_ar =& $xml_array;
$parents = array();
$last_counter_in_tag = array(1=>0);
foreach ($xml_values as $data)
{
switch($data['type'])
{
case 'open':
$last_counter_in_tag[$data['level']+1] = 0;
$new_tag = array('name' => $data['tag']);
if(isset($data['attributes']))
$new_tag['attributes'] = $data['attributes'];
if(isset($data['value']) && trim($data['value']))
$new_tag['value'] = trim($data['value']);
$last_tag_ar[$last_counter_in_tag[$data['level']]] = $new_tag;
$parents[$data['level']] =& $last_tag_ar;
$last_tag_ar =& $last_tag_ar[$last_counter_in_tag[$data['level']]++];
break;
case 'complete':
$new_tag = array('name' => $data['tag']);
if(isset($data['attributes']))
$new_tag['attributes'] = $data['attributes'];
if(isset($data['value']) && trim($data['value']))
$new_tag['value'] = trim($data['value']);
$last_count = count($last_tag_ar)-1;
$last_tag_ar[$last_counter_in_tag[$data['level']]++] = $new_tag;
break;
case 'close':
$last_tag_ar =& $parents[$data['level']];
break;
default:
break;
};
}
return $xml_array;
}
//
// use this to get node of tree by path with '/' terminator
//
function get_value_by_path($__xml_tree, $__tag_path)
{
$tmp_arr =& $__xml_tree;
$tag_path = explode('/', $__tag_path);
foreach($tag_path as $tag_name)
{
$res = false;
foreach($tmp_arr as $key => $node)
{
//echo is_int($key)?$node['name']."<br>":'';
if(is_int($key) && $node['name'] == $tag_name)
{
$tmp_arr = $node;
$res = true;
break;
}
}
if(!$res)
return false;
}
return $tmp_arr;
}
header('Content-Type: text/html; charset=utf-8');
$conteudo= file_get_contents("http://endereco_webserver/pagina_webserver.asmx/variavel?login=usuario&senha=1234");
$arr = my_xml2array($conteudo);
$c=0;
foreach(array_reverse($arr[0][1][0]) as $item) {
if (isset($item['name']) && $item['name']=="Table") {
?>
<div id="<? echo ($c%2==0)?'branco':'cinza';?>"><a href="carrega.php?p=<?=$item[3]['value'];?>" title="<?=$item[2]['value'];?>" target='_parent' class=><strong><?=DataBr($item[1]['value']);?></strong> <?=$item[2]['value'];?></a></div>
<?
$c++;}
}
?>
Como obter a lista de todos os caracteres (char) em php?
Hoje vou postar a minha primeira dica de código, como é primeira vez, pelo fato do site ter recebido uma cara nova, que espero que esteja agradando, mais do que o antigo inexpressivo, aí vai:
<?php
//simples assim
for ($x=0; $x<256; $x++){
echo "Char $x - " . chr($x) . "<br>";
}
?>
Você pode obter mais dicas interessantes neste link:
http://www.php.net/manual/pt_BR/function.chr.php


