Escolar Documentos
Profissional Documentos
Cultura Documentos
Curso PHP 5a Parte
Curso PHP 5a Parte
APOSTILA DE PHP
- Aula 5 -
São Carlos
2007
Exemplos com banco de dados
Crie uma nova base de dados no MySql, através do PhpMyAdmin, com o nome
base5. Para acessar o phpmyadmin, basta iniciar o servidor apache e digitar o
endereço no browser: http://localhost/public/phpmyadmin/index.php
Usuario
idusuario_us int auto_increment
login_us varchar(20)
senha_us varchar(20)
Obs.: insira pelo menos um registro na tabela para testarmos o acesso à Área
Restrita.
Fotos
idfoto int auto_increment
foto blob
descricao varchar(100)
Home
idhome int auto_increment
descricao text
2
Crie uma página HTML como mostrado abaixo e salve-a com o nome index.php:
Figura 1 – index.php
3
Para adicionar o menu.php, use o código abaixo:
Ex:
<script>
function verifica()
{
if (window.document.form1.usuario.value == '')
alert("O campo usuário não foi preenchido!")
else if (window.document.form1.senha.value == '')
alert("O campo senha não foi preenchido!")
else
window.document.form1.submit();
}
</script>
index.php
<html>
<head>
<title>..:: Exemplos com PHP ::..</title>
<style type="text/css">
<!--
.style1 {
color: #FFFFFF;
font-weight: bold;
}
-->
</style>
</head>
<body>
<p>PÁGINA INICIAL</p>
<hr align="left" width="700">
<!-- inicio do menu lateral -->
<? require_once("menu.php"); ?>
<!-- fim do menu lateral -->
<p><br>
<br>
</p>
4
<p> </p>
<p> </p>
<p> </p>
<p> </p>
<hr align="left" width="700">
<table width="700" border="1" cellspacing="0" cellpadding="0">
<tr>
<td bgcolor="#99CCFF"><strong>Página Inicial </strong></td>
</tr>
<tr>
<td><p> </p>
<p>conteúdo da página inicial ! </p></td>
</tr>
</table>
<p> </p>
</body>
</html>
menu.php
<script>
function verifica()
{
if (window.document.form1.usuario.value == '')
alert("O campo usuário não foi preenchido!")
else if (window.document.form1.senha.value == '')
alert("O campo senha não foi preenchido!")
else
window.document.form1.submit();
}
</script>
5
<td>
<input name="Button" type="button" id="Submit" value="Avançar"
onclick="javascript:verifica();" />
</td>
</tr>
</table></td>
</tr>
</table>
</form>
conexao.php
<?php
mysql_connect("localhost","root","") or die("Erro de conexão");
mysql_select_db("base5") or die("Base de dados não existe");
?>
acesso.php
<?
require_once('conexao.php');
session_start();
$usuario = $_POST["usuario"];
$senha = $_POST["senha"];
arearestrita.php
<?
session_start();
if (session_is_registered("idusuario"))
{
?>
<!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>Untitled Document</title>
</head>
<body>
6
<p>ÁREA RESTRITA</p>
<hr align="left" width="700" />
<p><a href="listausuarios.php">Cadastro de usuários</a></p>
<p><a href="listafotos.php">Cadastro de fotos</a> </p>
<p><a href="listahome.php">Cadastro do conteúdo da Área Restrita</a></p>
<hr align="left" width="700" />
<p><a href="destruirsessao.php">| FECHAR | </a></p>
<p> </p>
<p> </p>
</body>
</html>
<?
}
else
header("Location: index.php");
?>
destruirsessao.php
<?
session_start(); // inicio a sessao
unset($_SESSION['idusuario']); // limpo a sessao
session_destroy(); // destruo a sessao
header("Location: index.php"); // redireciono para a página principal
?>
CADASTRO DE USUÁRIOS
listausuarios.php
<?
session_start();
if (session_is_registered("idusuario"))
{
?>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<p>Lista de Usuários</p>
<hr align="left" width="700" />
<table width="700" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="273" bgcolor="#D9ECFF"><strong>Usuário</strong></td>
<td width="219" bgcolor="#D9ECFF"><strong>Senha</strong></td>
<td colspan="2" bgcolor="#D9ECFF"><div
align="center"><strong>Opções</strong></div></td>
</tr>
<!-- inicio da 2a linha -->
<?
require_once('conexao.php');
$rset = mysql_query("Select * from Usuario Order by login_us");
while ($linha = mysql_fetch_assoc($rset))
{
?>
<tr>
7
<td><?=$linha["login_us"] ?></td>
<td><?=$linha["senha_us"] ?></td>
<td width="98"><div align="center"><a href="alterarusuario.php?id=<?= $linha["idusuario_us"] ?
>">Alterar</a></div></td>
<td width="100"><div align="center"><a href="excluirusuario.php?id=<?= $linha["idusuario_us"] ?
>">Excluir</a></div></td>
</tr>
<?
}
?>
<!-- inicio da 2a linha -->
</table>
<p align="left">|<a href="arearestrita.php"> Voltar </a>|<a href="inserirusuario.php"> Inserir </a>|</p>
<p> </p>
</body>
</html>
<?
}
else
header("Location: index.php");
?>
inserirusuario.php
<?
session_start();
if (session_is_registered("idusuario"))
{
?>
<html>
<head>
<title>Untitled Document</title>
<script>
function verifica()
{
if (window.document.forminserir.login.value == '')
alert("Campo login esta vazio!")
else if (window.document.forminserir.senha1.value == '')
alert("Campo senha esta vazio!")
else if (window.document.forminserir.senha1.value !=
window.document.forminserir.senha2.value)
alert("Senha não confere!")
else
window.document.forminserir.submit();
}
</script>
</head>
<body>
<p>Inserção de Usuários</p>
<hr align="left" width="700" />
<form name="forminserir" method="post" action="finalinserir.php" >
<table width="400" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="136"><div align="right">Login:</div></td>
<td width="258"><input name="login" type="text" id="login" /></td>
</tr>
<tr>
<td><div align="right">Senha:</div></td>
<td><input name="senha1" type="password" id="senha1" /></td>
</tr>
<tr>
8
<td><div align="right">Confirma senha: </div></td>
<td><input name="senha2" type="password" id="senha2" /></td>
</tr>
</table>
finalinserir.php
<?
session_start();
if (session_is_registered("idusuario"))
{
$login = $_REQUEST["login"];
$senha = $_REQUEST["senha1"];
?>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<?
require_once('conexao.php');
$sql = "Select * from Usuario where login_us ='".$login."'";
$rset = mysql_query($sql);
$total = mysql_num_rows($rset);
if ($total > 0)
echo $login."já existe no banco!";
else
{
$sql = "Insert into Usuario (idusuario_us, login_us, senha_us)
Values ('','".$login."','".$senha."')";
$rset = mysql_query($sql);
echo " $login inserido com sucesso! ";
}
?>
<hr align="left" width="700"/>
<p><a href="listausuarios.php">| VOLTAR | </a></p>
</body>
</html>
<?
}
else
header("Location: index.php");
?>
9
alterarusuario.php
<?
session_start();
if (session_is_registered("idusuario"))
{
$id = $_REQUEST['id'];
require_once('conexao.php');
$rset = mysql_query("Select * from Usuario Where idUsuario_us = $id");
if($linha = mysql_fetch_assoc($rset))
{
$login = $linha['login_us'];
$senha = $linha['senha_us'];
}
?>
<html>
<head>
<title>Untitled Document</title>
<script>
function verifica()
{
if (window.document.form1.login.value == '')
alert("Campo login esta vazio!")
else if (window.document.form1.senha1.value == '')
alert("Campo senha esta vazio!")
else if (window.document.form1.senha1.value != window.document.form1.senha2.value)
alert("Senha não confere!")
else
window.document.form1.submit();
}
</script>
</head>
<body>
<p>Alteração de Usuários</p>
<hr align="left" width="700" />
<form name="form1" method="post" action="finalalterar.php" >
<table width="400" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="135"><div align="right">Login:</div></td>
<td width="259"><input name="login" type="text" id="login" value="<?= $login ?>"/></td>
</tr>
<tr>
<td><div align="right">Senha:</div></td>
<td><input name="senha1" type="password" id="senha1" value="<?= $senha ?>" /></td>
</tr>
<tr>
<td><div align="right">Confirma senha: </div></td>
<td><input name="senha2" type="password" id="senha2" value="<?= $senha ?>" /></td>
</tr>
</table>
<input name="id" type="hidden" value="<?=$id?>">
<p>|<a href="listausuarios.php"> Voltar </a>|<a href="javascript:verifica();"> Alterar </a>|</p>
</form>
</body>
</html>
<?
}
else
header("Location: index.php");
?>
10
finalalterar.php
<?
session_start();
if (session_is_registered("idusuario"))
{
$id = $_REQUEST['id'];
$login = $_REQUEST["login"];
$senha = $_REQUEST["senha1"];
?>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<?
require_once('conexao.php');
$sql = "UPDATE Usuario SET login_us ='".$login."', senha_us='".$senha."'
WHERE idusuario_us = $id";
$rset = mysql_query($sql);
echo " $login alterado com sucesso! ";
?>
<hr align="left" width="700"/>
<p><a href="listausuarios.php">| VOLTAR | </a></p>
</body>
</html>
<?
}
else
header("Location: index.php");
?>
excluirusuario.php
<?
session_start();
if (session_is_registered("idusuario"))
{
$id = $_REQUEST['id'];
require_once('conexao.php');
$rset = mysql_query("Select * from Usuario Where idUsuario_us = $id");
if($linha = mysql_fetch_assoc($rset))
{
$login = $linha['login_us'];
$senha = $linha['senha_us'];
}
?>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<p>Exclusão de Usuários</p>
<hr align="left" width="700" />
<form name="form1" method="post" action="finalexcluir.php" >
<table width="400" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="133"><div align="right">Login:</div></td>
11
<td width="261"><input name="login" type="text" id="login" value="<?= $login ?>"
disabled="disabled"/></td>
</tr>
<tr>
<td><div align="right">Senha:</div></td>
<td><input name="senha1" type="password" id="senha1" value="<?= $senha ?>"
disabled="disabled"/></td>
</tr>
<tr>
<td><div align="right">Confirma senha: </div></td>
<td><input name="senha2" type="password" id="senha2" value="<?= $senha ?>" disabled="disabled"
/></td>
</tr>
</table>
<input name="id" type="hidden" value="<?=$id?>">
<p>|<a href="listausuarios.php"> Voltar </a>|
<a href="javascript:window.document.form1.submit();"> Excluir </a>|</p>
</form>
</body>
</html>
<?
}
else
header("Location: index.php");
?>
finalexcluir.php
<?
session_start();
if (session_is_registered("idusuario"))
{
$id = $_REQUEST['id'];
?>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<?
require_once('conexao.php');
$sql = "DELETE FROM Usuario WHERE idusuario_us = $id";
$rset = mysql_query($sql);
echo "Registro excluido com sucesso! ";
?>
<hr align="left" width="700"/>
<p><a href="listausuarios.php">| VOLTAR | </a></p>
</body>
</html>
<?
}
else
header("Location: index.php");
?>
12
CADASTRO DE FOTOS
listafotos.php
<?
session_start();
if (session_is_registered("idusuario"))
{
?>
<!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>Untitled Document</title>
</head>
<body>
<p>Lista de Fotos </p>
<hr align="left" width="700" />
<table width="700" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="273" bgcolor="#D9ECFF"><strong>Descrição</strong></td>
<td width="219" bgcolor="#D9ECFF"><strong>Foto</strong></td>
<td bgcolor="#D9ECFF"><div align="center"><strong>Opções</strong></div></td>
</tr>
<!-- inicio da 2a linha -->
<?
require_once('conexao.php');
$rset = mysql_query("Select * from Fotos Order by descricao");
while ($linha = mysql_fetch_assoc($rset))
{
$cont++;
?>
<tr>
<td><?=$linha["descricao"] ?> </td>
<td><?=$linha["foto"] ?> </td>
<td><div align="center"><a href="alterarfoto.php?id=<?= $linha["idfoto"] ?>">Alterar</a></div>
<div align="center"></div></td>
</tr>
<?
}
if ($cont == 0)
{
?>
<tr>
<td colspan="3">Nenhum registro encontrado!</td>
</tr>
<?
}
?>
<!-- inicio da 2a linha -->
</table>
<p>|<a href="arearestrita.php"> Voltar </a>|<a href="inserirfoto.php"> Inserir </a>|</p>
</body>
</html>
<?
}
else
header("Location: index.php");
?>
13
inserirfoto.php
<?
session_start();
if (session_is_registered("idusuario"))
{
?>
<html>
<head>
<title>Untitled Document</title>
<script>
function verifica()
{
if (window.document.form1.descricao.value == '')
alert("Campo Descrição esta vazio!")
else
window.document.form1.submit();
}
</script>
</head>
<body>
<p>Inserção de Fotos </p>
<hr align="left" width="700" />
<form name="form1" method="post" action="uploadfoto.php" >
<table width="700" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="129"><div align="right">Descrição:</div></td>
<td width="565"><input name="descricao" type="text" id="descricao" size="80" maxlength="255"
/></td>
</tr>
<tr>
<td><div align="right">Foto:</div></td>
<td><span class="Texto">
<input name="upload" type="submit" class="Texto" id="upload" value="Upload da foto...">
</span></td>
</tr>
</table>
14
uploadfoto.php
<?
session_start();
if (session_is_registered("idusuario"))
{
$descricao = $_REQUEST['descricao'];
?>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<p>Inserção de Fotos </p>
<hr align="left" width="700" />
<?php
$descricao = $_REQUEST['descricao'];
$nomefoto = $_FILES['arquivo']['name'];
if (isset($nomefoto))
{
$uploaddir = 'c:\\phpdev\www\public\aula5\\';
$arquivo = $uploaddir.$nomefoto;
if (move_uploaded_file($_FILES['arquivo']['tmp_name'], $arquivo))
print "O arquivo foi gravado com sucesso.";
else
print "Erro. O arquivo não foi enviado.";
}
?>
<form enctype="multipart/form-data" action="uploadfoto.php" method="POST">
Enviar este arquivo: <input name="arquivo" type="file">
<input type="submit" value="Envia Arquivo">
<input name="nomefoto" type="hidden" value="<?= $nomefoto ?>">
<input name="descricao" type="hidden" value="<?= $descricao ?>">
</form>
15
finalinserirfoto.php
<?
session_start();
if (session_is_registered("idusuario"))
{
$descricao = $_REQUEST["descricao"];
$nomefoto = $_REQUEST["nomefoto"];
?>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<?
require_once('conexao.php');
$sql = "Select * from Fotos where foto ='".$nomefoto."'";
$rset = mysql_query($sql);
$total = mysql_num_rows($rset);
if ($total > 0)
echo $nomefoto."já existe no banco!";
else
{
$sql = "Insert into Fotos (idfoto, foto, descricao)
Values ('','".$nomefoto."','".$descricao."')";
$rset = mysql_query($sql);
echo " Foto inserida com sucesso! ";
}
?>
<hr align="left" width="700"/>
<p><a href="listafotos.php">| VOLTAR | </a></p>
</body>
</html>
<?
}
else
header("Location: index.php");
?>
16
alterarfoto.php
<?
session_start();
if (session_is_registered("idusuario"))
{
$id = $_REQUEST['id'];
require_once('conexao.php');
$rset = mysql_query("Select * from Fotos Where idfoto = $id");
if($linha = mysql_fetch_assoc($rset))
$descricao = $linha['descricao'];
?>
<html>
<head>
<title>Untitled Document</title>
<script>
function verifica()
{
if (window.document.form1.descricao.value == '')
alert("Campo Descrição esta vazio!")
else
window.document.form1.submit();
}
</script>
</head>
<body>
<p>Alterar descrição da Foto </p>
<hr align="left" width="700" />
<form name="form1" method="post" action="finalalterarfoto.php" >
<table width="700" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="129"><div align="right">Descrição:</div></td>
<td width="565"><input name="descricao" type="text" id="descricao" size="80" maxlength="255"
value="<?= $descricao ?>" /></td>
</tr>
</table>
17
alterarfoto.php
<?
session_start();
if (session_is_registered("idusuario"))
{
$id = $_REQUEST['id'];
require_once('conexao.php');
$rset = mysql_query("Select * from Fotos Where idfoto = $id");
if($linha = mysql_fetch_assoc($rset))
$descricao = $linha['descricao'];
?>
<html>
<head>
<title>Untitled Document</title>
<script>
function verifica()
{
if (window.document.form1.descricao.value == '')
alert("Campo Descrição esta vazio!")
else
window.document.form1.submit();
}
</script>
</head>
<body>
<p>Alterar descrição da Foto </p>
<hr align="left" width="700" />
<form name="form1" method="post" action="finalalterarfoto.php" >
<table width="700" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="129"><div align="right">Descrição:</div></td>
<td width="565"><input name="descricao" type="text" id="descricao" size="80" maxlength="255"
value="<?= $descricao ?>" /></td>
</tr>
</table>
18
finalalterarfoto.php
<?
session_start();
if (session_is_registered("idusuario"))
{
$id = $_REQUEST['id'];
$descricao = $_REQUEST["descricao"];
?>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<?
require_once('conexao.php');
$sql = "UPDATE Fotos SET descricao ='".$descricao."'
WHERE idfoto = $id";
$rset = mysql_query($sql);
echo " Descricao alterada com sucesso! ";
?>
<hr align="left" width="700"/>
<p><a href="listafotos.php">| VOLTAR | </a></p>
</body>
</html>
<?
}
else
header("Location: index.php");
?>
19
Cadastro do conteúdo da Página Inicial
listahome.php
<?
session_start();
if (session_is_registered("idusuario"))
{
?>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<p>Conteúdo da página inicial </p>
<hr align="left" width="700" />
<table width="700" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="568" bgcolor="#D9ECFF"><strong>Descrição</strong></td>
<td width="126" bgcolor="#D9ECFF"><div
align="center"><strong>Opções</strong></div></td>
</tr>
<!-- inicio da 2a linha -->
<?
require_once('conexao.php');
$rset = mysql_query("Select * from Home");
while ($linha = mysql_fetch_assoc($rset))
{
?>
<tr>
<td><?=$linha["descricao"] ?></td>
<td><div align="center">
<a href="alterarhome.php?id=<?= $linha["idhome"] ?>">Alterar</a>
</div></td>
</tr>
<?
}
?>
<!-- inicio da 2a linha -->
</table>
<p align="left">|<a href="arearestrita.php"> Voltar </a>|<a href="inserirhome.php"> Inserir </a>|</p>
<p> </p>
</body>
</html>
<?
}
else
header("Location: index.php");
?>
20
inserirhome.php
<?
session_start();
if (session_is_registered("idusuario"))
{
?>
<html>
<head>
<title>Untitled Document</title>
<SCRIPT language=Javascript1.2 src="editor.js"></SCRIPT>
<SCRIPT> _editor_url = ""; </SCRIPT>
</head>
<body>
<p>Inserção de conteúdo da Página Inicial </p>
<hr align="left" width="700" />
<form name="form1" method="post" action="finalinserirhome.php" >
<table width="560" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="689"><div align="left"><strong>Descrição</strong></div></td>
</tr>
<tr>
<td>
<textarea name="descricao" cols=90 rows=15></textarea>
<SCRIPT language=javascript1.2>editor_generate('descricao');</SCRIPT>
</td>
</tr>
</table>
OBSERVAÇÃO: Para o texto de nossa página inicial, cadastraremos não somente o texto no
banco, mas todos os formatos em html.
Ex: Título com cor azul e negrito. O resto do texto em preto.
Para isso, utilizaremos dois arquivos extras: um em javascript (editor.js) e outro em html
(select_color.html).
21
editor.js
//
// htmlArea v1.04 - Copyright (c) 2002 interactivetools.com, inc.
// A free WYSIWYG editor replacement for <textarea> fields.
//
// For more information visit:
// http://www.interactivetools.com/products/htmlarea/
//
/* ---------------------------------------------------------------------- *\
Function : editor_generate
Description : replace textarea with wysiwyg editor
Usage : editor_generate("textarea_id",[height],[width]);
Arguments : objname - ID of textarea to replace
w - width of wysiwyg editor
h - height of wysiwyg editor
\* ---------------------------------------------------------------------- */
function editor_generate(objname,w,h) {
// Default Settings
var imgURL = 'images/'; // images url
22
+ ' <option value="Georgia, Times New Roman, Times, Serif">Georgia</option>\n'
+ ' <option value="Tahoma, Arial, Helvetica, sans-serif">Tahoma</option>\n'
+ ' <option value="times new roman, times, serif">Times New Roman</option>\n'
+ ' <option value="Verdana, Arial, Helvetica, sans-serif">Verdana</option>\n'
+ ' <option value="wingdings">WingDings</option>\n'
+ ' </select>'
+ ' </td>\n'
+ ' </tr>\n'
+ '</table>\n'
// -----------
// CAUTION: You may NOT remove or hide this button. If displays the "About this editor" popup
// and is required by the license agreement for the editor.
//+ '<button title="About this editor" id="_' +objname+ '_about" class="btn"
onClick="editor_action(this.id)" unselectable="on"><img src="' +imgURL+ 'ed_about.gif"
unselectable="on"></button>'
// -----------
+ '</td></tr></table>\n'
+ '</td></tr></table>\n'
+ '<textarea ID="_' +objname + '_editor" style="width:' +width+ '; height:' +height+ '; margin-top: -1px;
margin-bottom: -1px;"></textarea>'
// create editor
var contents = document.all[objname].value; // get original contents
24
document.all[objname].outerHTML = editor; // create editor frame
document.all['_'+objname+'_editor'].value = contents; // set contents
/* ---------------------------------------------------------------------- *\
Function : editor_action
Description : perform an editor command on selected editor content
Usage :
Arguments : button_id - button id string with editor and action name
\* ---------------------------------------------------------------------- */
function editor_action(button_id) {
25
// insert link
if (cmdID.toLowerCase() == 'createlink'){
editdoc.execCommand(cmdID,1);
}
// insert image
else if (cmdID.toLowerCase() == 'insertimage'){
showModalDialog("insert_image.html", editdoc, "resizable: no; help: no; status: no; scroll: no; ");
}
// insert image
else if (cmdID.toLowerCase() == 'about'){
var html = '<HTML><HEAD><TITLE>About</TITLE>\n'
+ '<style>\n'
+ ' html,body,textarea { font-family: verdana,arial; font-size: 9pt; };\n'
+ '</style></HEAD>\n'
+ '<BODY style="background: threedface; color: #000000" topmargin=5 leftmargin=12>\n\n'
+ '<span style="font-family: arial black, arial; font-size: 28px; letter-spacing:
-2px;">htmlArea</span> by interactivetools.com<br>\n'
+ 'A free WYSIWYG editor replacement for <textarea> fields.<br>\n\n'
+ '<p><textarea style="width:100%; height:120px" readonly>\n'
+ 'Copyright (c) 2002 interactivetools.com, inc.\n\n'
+ 'Permission is hereby granted, free of charge, to any person obtaining a copy of this software
and associated documentation files (the "Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so, subject to the
following conditions:\n\n'
+ 'a) The above copyright notice, this permission notice, and the "About this editor" button that
appears as a question mark in the editor interface, shall be included in all copies or substantial portions
of the Software.\n\n'
+ 'b) The "About this editor" button that appears as a question mark ("?") in the editor interface
must always be visible in the editor interface and bring up the original "About" dialog window when
clicked.\n\n'
+ 'c) The "About" dialog window and its contents, including the link to interactivetools.com can
not be amended.\n\n'
+ 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO
EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.\n'
+ '</textarea>\n\n'
+ '<p>For more information visit:<br>\n'
+ '<a href="http://www.interactivetools.com/products/htmlarea/"
target="_blank">http://www.interactivetools.com/products/htmlarea/</a><br><br>\n'
+ '</body></html>\n\n';
editor_updateUI(objname);
}
26
/* ---------------------------------------------------------------------- *\
Function : editor_updateUI
Description : update button status, selected fonts, and hidden output field.
Usage :
Arguments : objname - ID of textarea to replace
runDelay: -1 = run now, no matter what
0 = run now, if allowed
1000 = run in 1 sec, if allowed at that point
\* ---------------------------------------------------------------------- */
function editor_updateUI(objname,runDelay) {
var editor_obj = document.all["_" +objname+ "_editor"]; // html editor object
if (runDelay == null) { runDelay = 0; }
var editdoc, editEvent;
// setup timer for delayed updates (some events take time to complete)
if (runDelay > 0) { return setTimeout(function(){ editor_updateUI(objname); }, runDelay); }
// don't execute more than 3 times a second (eg: too soon after last execution)
if (this.tooSoon == 1 && runDelay >= 0) { this.queue = 1; return; } // queue all but urgent events
this.tooSoon = 1;
setTimeout(function(){
this.tooSoon = 0;
if (this.queue) { editor_updateUI(objname,-1); };
this.queue = 0;
}, 333); // 1/3 second
if (!cmdActive) { // option is OK
if (button_obj.className != 'btn') { button_obj.className = 'btn'; }
if (button_obj.disabled != false) { button_obj.disabled = false; }
} else if (cmdActive) { // option already applied or mixed content
if (button_obj.className != 'btnDN') { button_obj.className = 'btnDN'; }
if (button_obj.disabled != false) { button_obj.disabled = false; }
}
/* ---------------------------------------------------------------------- *\
Function : editor_setmode
Description : change mode between WYSIWYG and HTML editor
Usage : editor_setmode(object_id, mode);
Arguments : button_id - button id string with editor and action name
mode - init, textedit, or wysiwyg
\* ---------------------------------------------------------------------- */
//
// Switch to TEXTEDIT mode
//
// disable buttons
var IDList =
Array('Bold','Italic','Underline','StrikeThrough','SubScript','SuperScript','JustifyLeft','JustifyCenter','JustifyR
ight','InsertOrderedList','InsertUnorderedList','Outdent','Indent','ForeColor','BackColor','InsertHorizontalR
ule','CreateLink','InsertImage');
for (i=0; i<IDList.length; i++) { // for each button
var button_obj = document.all["_" +objname+ "_" +IDList[i]]; // get button object
if (button_obj == null) { continue; } // if no btn obj???
button_obj.className = 'btnNA';
button_obj.disabled = true;
}
_editor_focus(editor_obj);
}
//
// Switch to WYSIWYG mode
//
else {
var contents = editor_obj.value;
// create editor
editor_obj.outerHTML = RichEdit;
editor_obj = document.all["_" +objname + "_editor"];
// enable buttons
var IDList =
Array('Bold','Italic','Underline','StrikeThrough','SubScript','SuperScript','JustifyLeft','JustifyCenter','JustifyR
ight','InsertOrderedList','InsertUnorderedList','Outdent','Indent','ForeColor','BackColor','InsertHorizontalR
ule','CreateLink','InsertImage');
for (i=0; i<IDList.length; i++) {
var button_obj = document.all["_" +objname+ "_" +IDList[i]];
if (button_obj == null) { continue; }
button_obj.className = 'btn';
button_obj.disabled = false;
}
// Call update UI
if (mode != 'init') { // don't update UI on page load, only on mode switch
editor_updateUI(objname);
}
/* ---------------------------------------------------------------------- *\
Function : _editor_focus
Description : bring focus to the editor
Usage : editor_focus(editor_obj);
Arguments : editor_obj - editor object
\* ---------------------------------------------------------------------- */
function _editor_focus(editor_obj) {
else { // wysiwyg
var editdoc = editor_obj.contentWindow.document; // get iframe editor document object
var editorRange = editdoc.body.createTextRange(); // editor range
var curRange = editdoc.selection.createRange(); // selection range
/* ---------------------------------------------------------------------- *\
Function : _dec_to_rgb
Description : convert dec color value to rgb hex
Usage : var hex = _dec_to_rgb('65535'); // returns FFFF00
Arguments : value - dec value
\* ---------------------------------------------------------------------- */
function _dec_to_rgb(value) {
var hex_string = "";
for (var hexpair = 0; hexpair < 3; hexpair++) {
var byte = value & 0xFF; // get low byte
value >>= 8; // drop low byte
var nybble2 = byte & 0x0F; // get low nybble (4 bits)
var nybble1 = (byte >> 4) & 0x0F; // get high nybble
hex_string += nybble1.toString(16); // convert nybble to hex
hex_string += nybble2.toString(16); // convert nybble to hex
}
return hex_string.toUpperCase();
}
/* ---------------------------------------------------------------------- *\
Function : _fix_placeholder_urls
Description : editor make relative urls absolute, this change them back
if the url contains a placeholder ("***")
Usage : _fix_placeholder_urls(editdoc)
Arguments : editdoc - reference to editor document
\* ---------------------------------------------------------------------- */
function _fix_placeholder_urls(editdoc) {
var i;
// for links
for (i=0; i < editdoc.links.length; i++) {
editdoc.links[i].href = editdoc.links[i].href.replace(/^[^*]*(\*\*\*)/, "$1");
}
// for images
for (i=0; i < editdoc.images.length; i++) {
editdoc.images[i].src = editdoc.images[i].src.replace(/^[^*]*(\*\*\*)/, "$1");
}
/* ---------------------------------------------------------------------- *\
Function : editor_insertHTML
31
Description : insert string at current cursor position in editor. If
two strings are specifed, surround selected text with them.
Usage : editor_insertHTML(objname, str1, [str2], reqSelection)
Arguments : objname - ID of textarea
str1 - HTML or text to insert
str2 - HTML or text to insert (optional argument)
reqSelection - (1 or 0) give error if no text selected
\* ---------------------------------------------------------------------- */
// error checking
if (editor_obj == null) { return alert("Unable to insert HTML. Invalid object name '" +objname+ "'."); }
_editor_focus(editor_obj);
// insert HTML
var oldHandler = window.onerror;
window.onerror = function() { alert("Unable to insert HTML for current selection."); return true; } //
partial table selections cause errors
if (sHtml.length) { // if content selected
if (str2) { sRange.pasteHTML(str1 +sHtml+ str2) } // surround
else { sRange.pasteHTML(str1); } // overwrite
} else { // if insertion point only
if (reqSel) { return alert("Unable to insert HTML. You must select something first."); }
sRange.pasteHTML(str1 + str2); // insert strings
}
window.onerror = oldHandler;
}
// insert HTML
if (sText.length) { // if content selected
if (str2) { sRange.text = str1 +sText+ str2; } // surround
else { sRange.text = str1; } // overwrite
32
} else { // if insertion point only
if (reqSel) { return alert("Unable to insert HTML. You must select something first."); }
sRange.text = str1 + str2; // insert strings
}
}
else { alert("Unable to insert HTML. Unknown object tag type '" +tagname+ "'."); }
/* ---------------------------------------------------------------------- */
select_color.html
function _CloseOnEsc() {
if (event.keyCode == 27) { window.close(); return; }
}
color = window.dialogArguments;
color = ValidateColor(color) || '000000';
View(color); // set default color
}
33
schar = string.charAt(i);
if (chars.indexOf(schar) != -1) { out += schar; }
}
</SCRIPT>
42
finalinserirhome.php
<?
session_start();
if (session_is_registered("idusuario"))
{
$descricao = $_REQUEST["descricao"];
?>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<?
require_once('conexao.php');
$sql = "Insert into Home (idhome, descricao)
Values ('','".$descricao."')";
//echo $sql;
$rset = mysql_query($sql);
echo " O conteúdo da página inicial foi inserido com sucesso! ";
?>
<hr align="left" width="700"/>
<p><a href="listahome.php">| VOLTAR | </a></p>
</body>
</html>
<?
}
else
header("Location: index.php");
?>
43
alterarhome.php
<?
session_start();
if (session_is_registered("idusuario"))
{
$id = $_REQUEST['id'];
require_once('conexao.php');
$rset = mysql_query("Select * from Home Where idhome = $id");
if($linha = mysql_fetch_assoc($rset))
$descricao = $linha['descricao'];
?>
<html>
<head>
<title>Untitled Document</title>
<SCRIPT language=Javascript1.2 src="editor.js"></SCRIPT>
<SCRIPT> _editor_url = ""; </SCRIPT>
</head>
<body>
<p>Alteração de conteúdo da Página Inicial </p>
<hr align="left" width="700" />
<form name="form1" method="post" action="finalalterarhome.php" >
<table width="560" border="1" cellspacing="0" cellpadding="0">
<tr>
<td width="689"><div align="left"><strong>Descrição</strong></div></td>
</tr>
<tr>
<td>
<textarea name="descricao" cols=90 rows=15><?=$descricao?></textarea>
<SCRIPT language=javascript1.2>editor_generate('descricao');</SCRIPT>
</td>
</tr>
</table>
44
finalalterarhome.php
<?
session_start();
if (session_is_registered("idusuario"))
{
$id = $_REQUEST['id'];
$descricao = $_REQUEST["descricao"];
?>
<html>
<head>
<title>Untitled Document</title>
</head>
<body>
<?
require_once('conexao.php');
$sql = "UPDATE Home SET descricao ='".$descricao."'
WHERE idhome = $id";
$rset = mysql_query($sql);
echo " Descricao alterada com sucesso! ";
?>
<hr align="left" width="700"/>
<p><a href="listahome.php">| VOLTAR | </a></p>
</body>
</html>
<?
}
else
header("Location: index.php");
?>
45