Login Automatico

1. Login Automatico

Roberto Costa
asparion

(usa Ubuntu)

Enviado em 26/04/2015 - 18:33h

Boa noite....

to usando um script php para ordem de serviços, que usa login e senha parar acessar:
ex: www.dominio.com.br --> index.php --> se o login tiver correto --> menu.php

$MM_redirectLoginSuccess = "menu.php";


certo, dentro do menu tenho a opção adicionar clientes
ex: www.dominio.com.br/add_clientes.php

como que faço para que se eu passar esse link para o cliente, ele nao peça pra logar
obs: no inico do arquivo .php tem essa opção eu tirei mais nao funcionou, segue:

vim add_cliente.php

<?php require_once('Connections/data.php'); ?>


seguei links:

http://www.asparion.com.br/os/index.php # Aqui quero deixar como ta pedindo login e senha
http://www.asparion.com.br/os/add_clientes.php # Aqui quero que entre automatico sem pedir login e senha


Alguem pode me ajudar...

Obrigado.....








  


2. Re: Login Automatico

CASSIO FERRAZ
cassio88

(usa Ubuntu)

Enviado em 26/04/2015 - 19:32h


Asparion,
desculpe-me se eu não tiver entendido corretamente seu problema, mas não é o caso de você usar variável de sessão?
algo do tipo...
login.php: o cara digita login e senha
sessao.php: se estiver correto, então
$_SESSION[login]=1;
e aí você redireciona para index.php, senão volta para login.php
para adicionar cliente, você cria um formulário, o cliente entra com login e senha, você insere no banco de dados e neste momento, também define
$_SESSION[login]=1;
assim o cliente não volta para a página de login



3. Re: Login Automatico

Roberto Costa
asparion

(usa Ubuntu)

Enviado em 27/04/2015 - 01:29h

opa boa noite..

então, na verdade não porque dai teria que criar um usuário para cada cliente quer for fazer cadastro o que não é viável,

o que preciso é o seguinte. vou por um link no meu site apontando para add_cliente.php. quando o cliente clicar la ele faz o cadastro. mais antes precisa logar, e preciso que entrasse sem pedir o login e senha.

se der pra fazer da seguinte forma seria bom tipo. no topo do arquivo add_cliente.php inserir um login padrão

ex:
vim add_cliente.php

<?php require_once('Connections/data.php'); ?>
user=cliente
senha=cliente
......restante do codigo.....


ai eu criaria o usuario cliente com a senha cliente. e ao clicar no link ja entraria logado.

ou tambem se der pra fazer uma index.html ou php que redirecione

ex:
vim index.html ou index.php

# uma linha apontando o caminho
vai para = http://www.dominio.com.br/os/index.php

# inserindo usuario e senha
user=usuario
password=senha

# Redirecionado para a pagina de cadastro do cliente
redireciona para = http://www.domino.com.br/os/add_clientes.php


basicamente é isso, so preciso que para o cliente nao tenha de digitar login e senha ao acesar add_clientes.php, o demais continua como esta...

abraço




4. Re: Login Automatico

CASSIO FERRAZ
cassio88

(usa Ubuntu)

Enviado em 27/04/2015 - 11:00h


Asparion,
Sem conhecer seu código a fundo e o padrão de projeto (programação) que você utiliza, a chance de eu contribuir positivamente cai bastante, em todo o caso vou arriscar.
No padrão de projeto que eu uso, o "cliente" entra sempre em login.php, digita usuário e senha e é remetido para sessao.php
sessao.php valida usuário e senha. Se passar, crio uma session ($_SESSION[login]), e o cliente é remetido para index.php, senão volta para login.php e uma mensagem de senha incorreta é mostrada.
Note que, a nível de código, as outras páginas só precisam testar se $_SESSION[login] existe. E se você atribuir à $_SESSION[login] o código do cliente, você pode usar esta informação durante toda a navegação dele pelo site.
com relação à add_cliente.php, não é preciso testar $_SESSION[login]: a pessoa insere login e senha (2 vezes), você insere a informação no banco, cria a sessão e contiua normalmente
Finalmente, se quiser que ele navegue sem digitar login, senha, basta criar $_SESSION[login] em add_cliente.php
bom, é isso.



5. Re: Login Automatico

Roberto Costa
asparion

(usa Ubuntu)

Enviado em 27/04/2015 - 23:28h

Boa noite...

nao entendi rsrsrs

mais segue minha conf

vim index.php

<?php require_once('Connections/data.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}
?><?php
// *** Validate request to login to this site.
if (!isset($_SESSION)) {
session_start();
}

$loginFormAction = $_SERVER['PHP_SELF'];
if (isset($_GET['accesscheck'])) {
$_SESSION['PrevUrl'] = $_GET['accesscheck'];
}

if (isset($_POST['textfield'])) {
$loginUsername=$_POST['textfield'];
$password=$_POST['textfield2'];
$MM_fldUserAuthorization = "nivel";
$MM_redirectLoginSuccess = "menu.php";
$MM_redirectLoginFailed = "menux.php";
$MM_redirecttoReferrer = false;
mysql_select_db($database_data, $data);

$LoginRS__query=sprintf("SELECT login, senha, nivel FROM funcionario WHERE login=%s AND senha=%s",
GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text"));

$LoginRS = mysql_query($LoginRS__query, $data) or die(mysql_error());
$loginFoundUser = mysql_num_rows($LoginRS);
if ($loginFoundUser) {

$loginStrGroup = mysql_result($LoginRS,0,'nivel');

//declare two session variables and assign them
$_SESSION['MM_Username'] = $loginUsername;
$_SESSION['MM_UserGroup'] = $loginStrGroup;

if (isset($_SESSION['PrevUrl']) && false) {
$MM_redirectLoginSuccess = $_SESSION['PrevUrl'];
}
header("Location: " . $MM_redirectLoginSuccess );
}
else {
header("Location: ". $MM_redirectLoginFailed );
}
}
?><!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=utf-8" />
<title>Asparion Informatica</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>

<body>
<form ACTION="<?php echo $loginFormAction; ?>" method="POST" name="form1" id="form1">
<table width="100%" border="0" cellspacing=" 0" cellpadding="0">
<tr>
<td><table width="100%" border="0" cellspacing=" 0" cellpadding="0">
<tr>
<td width="15"> </td>

<div align="center"><img src="Imagens/logo.png"></div><br>

<td><strong><div align="center">ÁSPARION INFORMÁTICA</a></strong></td>
</tr>
</table></td>
</tr>
<tr>
<td valign="top"><div align="center">Área
restrita para funcionários da sua empresa, digite nos
campos abaixo o seu login e senha e clique no botão
acessar:<br><br>

<table border="0" cellspacing="2" cellpadding="2" class="texto" align="center">
<tr>
<td align="right"><b>Login:</b></td>
<td>  <input type="text" name="textfield" /> </td>
</tr>
<tr>
<td align="right"><b>Senha:</b></td>
<td>  <input type="password" name="textfield2" /> </td>
</tr>
<tr align="center">
<td colspan="2"><div align="right">
<input type="submit" name="Submit" value="Acessar" />
<br />
</div></td>
</tr>
</table>
</div></td>
</tr>
</table>
</form>
</body>
</html>


vim data.php

<?php
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_data = "localhost";
$database_data = "os";
$username_data = "root";
$password_data = "123456";
$data = mysql_pconnect($hostname_data, $username_data, $password_data) or trigger_error(mysql_error(),E_USER_ERROR);
?>


e por ultima o que quero que nao precise de senha ou ja entre logado

vim add_cliente.php

<?php require_once('Connections/data.php'); ?> <?php
if (!isset($_SESSION)) {
session_start();
}
$MM_authorizedUsers = "";
$MM_donotCheckaccess = "true";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) {
// For security, start by assuming the visitor is NOT authorized.
$isValid = False;

// When a visitor has logged into this site, the Session variable MM_Username set equal to their username.
// Therefore, we know that a user is NOT logged in if that Session variable is blank.
if (!empty($UserName)) {
// Besides being logged in, you may restrict access to only certain users based on an ID established when they login.
// Parse the strings into arrays.
$arrUsers = Explode(",", $strUsers);
$arrGroups = Explode(",", $strGroups);
if (in_array($UserName, $arrUsers)) {
$isValid = true;
}
// Or, you may restrict access to only certain users based on their username.
if (in_array($UserGroup, $arrGroups)) {
$isValid = true;
}
if (($strUsers == "") && true) {
$isValid = true;
}
}
return $isValid;
}

$MM_restrictGoTo = "index.php";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) {
$MM_qsChar = "?";
$MM_referrer = $_SERVER['PHP_SELF'];
if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
if (isset($QUERY_STRING) && strlen($QUERY_STRING) > 0)
$MM_referrer .= "?" . $QUERY_STRING;
$MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
header("Location: ". $MM_restrictGoTo);
exit;
}
?><?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;

$theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}

$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
$colname_rsVerificador = "-1";
if (isset($_POST['nome'])) {
$colname_rsVerificador = $_POST['nome'];
}
mysql_select_db($database_data, $data);
$query_rsVerificador = sprintf("SELECT * FROM cliente WHERE nome = %s", GetSQLValueString($colname_rsVerificador, "text"));
$rsVerificador = mysql_query($query_rsVerificador, $data) or die(mysql_error());
$row_rsVerificador = mysql_fetch_assoc($rsVerificador);
$totalRows_rsVerificador = mysql_num_rows($rsVerificador);
mysql_free_result($rsVerificador);

if ($totalRows_rsVerificador == 0) { // Show if recordset empty
$insertSQL = sprintf("INSERT INTO cliente (codigo, nome, cpf, email, celular, endereco, bairro, cidade, estado, cep) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)",
GetSQLValueString($_POST['codigo'], "int"),
GetSQLValueString($_POST['nome'], "text"),
GetSQLValueString($_POST['cpf'], "text"),
GetSQLValueString($_POST['email'], "text"),
GetSQLValueString($_POST['celular'], "text"),
GetSQLValueString($_POST['endereco'], "text"),
GetSQLValueString($_POST['bairro'], "text"),
GetSQLValueString($_POST['cidade'], "text"),
GetSQLValueString($_POST['estado'], "text"),
GetSQLValueString($_POST['cep'], "text"));

mysql_select_db($database_data, $data);
$Result1 = mysql_query($insertSQL, $data) or die(mysql_error());

$insertGoTo = "fechar.php";
if (isset($_SERVER['QUERY_STRING'])) {
$insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
$insertGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $insertGoTo));
} // Show if recordset empty

?>
<?php } // Show if recordset empty ?>
<!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=utf-8" />
<title>Asparion Informatica</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<script>
function formatar(src, mask)
{
var i = src.value.length;
var saida = mask.substring(0,1);
var texto = mask.substring(i)
if (texto.substring(0,1) != saida)
{
src.value += texto.substring(0,1);
}
}
function MM_validateForm() { //v4.0
if (document.getElementById){
var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=document.getElementById(args[i]);
if (val) { nm=val.name; if ((val=val.value)!="") {
if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
if (p<1 || p==(val.length-1)) errors+='- '+nm+' deve conter um endereço valido.\n';
} else if (test!='R') { num = parseFloat(val);
if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
min=test.substring(8,p); max=test.substring(p+1);
if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
} } } else if (test.charAt(0) == 'R') errors += '- '+nm+' é um campo obrigatório.\n'; }
} if (errors) alert('Os Seguintes erros foram encontrados:\n'+errors);
document.MM_returnValue = (errors == '');
} }
</script>
<script language="JavaScript">
<!--
function muda(qual)
{
uCase = qual.value.toUpperCase();
qual.value = uCase;
}
-->
</script>
<style type="text/css">
<!--
.style1 {color: #FF0000}
-->
</style>
</head>

<body>
<form action="<?php echo $editFormAction; ?>" method="POST" name="form1" id="form1" onsubmit="MM_validateForm('nome','','R','email','','NisEmail');return document.MM_returnValue">
<table width="100%" border="0" cellpadding="0" cellspacing=" 0">
<tr>
<td width="15"><div align="center"><img src="Imagens/cadeado.gif" alt="" width="30" height="30" /></div></td>
<td><font color="#666666"><b><span class="style1">

Intranet

</span> -<font color="#666666"><b><b><a href="fechar.php"> Fechar Janela</a></b></b></font></b></font></td>
</tr>
</table>
<table border="0" cellspacing="2" cellpadding="2" class="verdana" >
<input type="hidden" name="codigo" />
<tr>
<td width="263"><font color="#666666"><b>Nome:</b><br />
<input name="nome" type="text" class="select" id="nome" size="50" maxlength="80" onKeyUp="muda(this)"/>
</font></td>
<td width="30">&nbsp;</td>
<td width="220"><b><font color="#666666"><b>CPF
/ CNPJ:</b><br />
<b>
<input type="text" name="cpf" class="select" maxlength="15" size="18" />
</b></font></b></td>
</tr>
<tr>
<td width="263"><font color="#666666"><b>Endere&ccedil;o:</b><br />
<b>
<input name="endereco" type="text" class="select" id="endereco" size="50" maxlength="100" onKeyUp="muda(this)"/>
</b></font></td>
<td width="30">&nbsp;</td>
<td width="220"><font color="#666666"><b>Bairro:</b><br />
<b>
<input type="text" name="bairro" class="select" maxlength="30" size="35" onKeyUp="muda(this)"/>
</b></font></td>
</tr>
<tr>
<td width="263"><font color="#666666"><b>Cidade:</b><br />
<b>
<input name="cidade" type="text" class="select" onKeyUp="muda(this)" value="Maringá" size="35" maxlength="30"/>
</b> </font></td>
<td width="30">&nbsp;</td>
<td width="220"><table width="100%" border="0" cellspacing="0" cellpadding="0" class="verdana">
<tr>
<td><font color="#666666"><b>Estado:</b><br />
<select name="estado" size="1" class="select">
<option value="PR">Paran&aacute;</option>
<option value="AC">Acre</option>
<option value="AL">Alagoas</option>
<option value="AP">Amap&aacute;</option>
<option value="AM">Amazonas</option>
<option value="BA">Bahia</option>
<option value="CE">Cear&aacute;</option>
<option value="DF">Distrito Federal</option>
<option value="ES">Esp&iacute;rito Santo</option>
<option value="GO">Goi&aacute;s</option>
<option value="MA">Maranh&atilde;o</option>
<option value="MT">Mato Grosso</option>
<option value="MS">Mato Grosso do Sul</option>
<option value="MG">Minas Gerais</option>
<option value="PA">Par&aacute;</option>
<option value="PB">Para&iacute;ba</option>
<option value="PE">Pernambuco</option>
<option value="PI">Piau&iacute;</option>
<option value="RJ">Rio de Janeiro</option>
<option value="RN">Rio Grande do Norte</option>
<option value="RS">Rio Grande do Sul</option>
<option value="RO">Rond&ocirc;nia</option>
<option value="RR">Roraima</option>
<option value="SC">Santa Catarina</option>
<option value="SP">S&atilde;o Paulo</option>
<option value="SE">Sergipe</option>
<option value="TO">Tocantins</option>
</select>
</font></td>
<td><font color="#666666"><b>Cep.:</b><br />
<b>
<input type="text" name="cep" class="select" maxlength="9" size="15" OnKeyPress="formatar(this, '#####-###')"/>
</b></font></td>
</tr>
</table></td>
</tr>
<tr>
<td width="263"><table width="100%" border="0" cellspacing="0" cellpadding="0" class="verdana">
<tr>
<td><font color="#666666"><b>Fone
Comercial:</b><br />
<b>
<input type="text" name="foneC" class="select" maxlength="13" size="15" />
</b></font></td>
<td><font color="#666666"><b>Fone
Residencial:</b><br />
<b>
<input type="text" name="foneR" class="select" maxlength="13" size="15" />
</b></font></td>
</tr>
</table></td>
<td width="30">&nbsp;</td>
<td width="220"><font color="#666666"><b>Celular:</b><br />
<b>
<input type="text" name="celular" class="select" maxlength="13" size="15" />
</b></font></td>
</tr>
<tr>
<td valign="top" width="263"><font color="#666666"><b>E-Mail:</b><br />
<b>
<input name="email" type="text" class="select" id="email" size="40" maxlength="50" />
</b> </font></td>
<td width="30">&nbsp;</td>
<td width="220">&nbsp;</td>
</tr>
<tr>
<td colspan="3" height="35" align="center"><div align="right">
<input type="submit" name="Submit" id="button" value="Efetuar Cadastro" />
<input type="reset" name="button2" id="button2" value="Limpar Campos" />
</div></td>
</tr>
</table>
<input type="hidden" name="MM_insert" value="form1" />
</form>
<p>
<?php if ($totalRows_rsVerificador > 0) { // Show if recordset not empty ?>
<span class="style1">
Este cadastro não pôde ser realizado, pois o mesmo já se encontra cadastrado em nosso sistema!
<?php } // Show if recordset not empty ?>
<br />
</p>
</body>
</html>



uma vez logado o index.php direciona para menu.php



6. Re: Login Automatico

Perfil removido
removido

(usa Nenhuma)

Enviado em 27/04/2015 - 23:42h

Se você tentar liberar essa página que é privada para pública poderá ter problemas com segurança. Qualquer um terá acesso a página e poderá adicionar clientes.



7. Re: Login Automatico

Roberto Costa
asparion

(usa Ubuntu)

Enviado em 28/04/2015 - 01:48h


Boa noite...

mais essa é justamente a intenção rsrsrs


8. Re: Login Automatico

CASSIO FERRAZ
cassio88

(usa Ubuntu)

Enviado em 28/04/2015 - 14:06h

Hum, peço desculpas, estava tão focado no código que não percebi que o problema estava mais na regra do negócio...

Bom, no post 1 você perguntou:
como que faço para que se eu passar esse link para o cliente, ele nao peça pra logar

eu faço assim:
o cara entra em login.php, digitando login e senha
se tiver sucesso, você atribui o login a $_SESSION['login']

nas demais páginas:
<?php
session_start();
if (! $_SESSION['login']) {
header("Location:login.php");
die;
}

e na página de add_cliente:
a) você define de saída $_SESSION['login'] = 'convidado' e aí o cara pode navegar com privilégios restritos
b) privilégio restrito até você aceitar o novo cliente e aí $_SESSION['login'] = login

Tem ainda a questão que o colega apontou acima, mas aí é outra história...


9. Re: Login Automatico

Roberto Costa
asparion

(usa Ubuntu)

Enviado em 28/04/2015 - 17:27h

Meu script nao tem o arquivo login.php

Segue Arquivos para analize.
http://www.asparion.com.br/testes/Ordem_Servico.rar

agradeço a ajuda...


10. Re: Login Automatico

CASSIO FERRAZ
cassio88

(usa Ubuntu)

Enviado em 29/04/2015 - 05:39h


Asparion,
baixei a pasta ordem de serviço, vou dar uma olhada.
Por favor, confirme o seguinte:
você precisa link no seu site apontando para add_cliente.php. quando o cliente clicar la ele faz o cadastro. sem ter de pedir o login e senha. O cara digita os dados e aí você faz um insert. (Sendo assim, há o risco de um engraçadinho ficar colocando registros do tipo Bin Laden, Madre Teresa de Calcutá, Pedro Alvares Cabral, mas este é um risco que todos correm.)



11. Re: Login Automatico

Roberto Costa
asparion

(usa Ubuntu)

Enviado em 30/04/2015 - 04:49h

a quanto isso nao tem problema nao. depois eu apago se tiver algum Osama Bin Laden da vida rsrsrs
so preciso que nao peça senha no arquivo add_clientes.php e quando o cliente clicar em Efetuar cadastro vai aparecer a msg CADASTRO EFETUADO COM SUCESSO clique ok para sair, ai volta na minha pagina



12. Re: Login Automatico

CASSIO FERRAZ
cassio88

(usa Ubuntu)

Enviado em 01/05/2015 - 06:44h

Asparion, seu código é muito grande e seu estilo de programação é diferente do meu, de modo que posso estar dando um fora.

Em todo o caso, você já pensou em criar o link que aponta para add_clientes.HTML? Este é um um formulário simples (<HTML><HEAD>...</HEAD><BODY><FORM> ...</FORM></BODY></HTML>)e, como tal, nunca será barrado por causa de $_SESSION. O HTML aponta para, digamos, add_clientes.php (que não terá teste de session, então sempre executará) e este faz o insert no banco.



01 02



Patrocínio

Site hospedado pelo provedor RedeHost.
Linux banner

Destaques

Artigos

Dicas

Tópicos

Top 10 do mês

Scripts