Ir para conteúdo

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

GustavoSatheler

nome no PHP

Recommended Posts

Olá,

Eu estou literalmente apanhando com um código PHP aqui para obter o nome do usuário logado.

 

O problema é que quando eu faço o login vai para o index.php, e nesse index.php tem o header.php incluido que o nome do usuario fique no header.php.

Eu utilizo MySQL como banco de dados, sendo

 

 

 

 

 

id - int(10) - Auto_Increment

nome - varchar(100)

usuario - varchar(50)

senha - varchar(50)

rank - int(11)

 

OBS: Usuário é utilizado para o login

Nome é o que preciso

 

Segue abaixo os codigos que utilizei

 

login_valida.php

<?php include('config/db_conecta.php'); ?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $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;
}
}

mysql_select_db($database_config, $config);
$query_login = "SELECT * FROM usuarios";
$login = mysql_query($query_login, $config) or die(mysql_error());
$row_login = mysql_fetch_assoc($login);
$totalRows_login = mysql_num_rows($login);
?>

<?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['login'])) {
  $loginUsername=$_POST['login'];
  $password=$_POST['senha'];
  $MM_fldUserAuthorization = "";
  $MM_redirectLoginSuccess = "pendencias/index.php";
  $MM_redirectLoginFailed = "senha_errada.php";
  $MM_redirecttoReferrer = true;
  mysql_select_db($database_config, $config);
  
  $LoginRS__query=sprintf("SELECT usuario, senha FROM usuarios WHERE usuario=%s AND senha=%s", GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text")); 
  $Nome__query=sprintf("SELECT nome FROM usuarios WHERE nome=%s", GetSQLValueString($Nome, "text")); 
  
  
  $LoginRS = mysql_query($LoginRS__query, $config) or die(mysql_error());
  $Nome = mysql_query($Nome__query, $config) or die(mysql_error());
  $loginFoundUser = mysql_num_rows($LoginRS);
  $LoginNome = mysql_num_rows($Nome);
  if ($loginFoundUser) {
     $loginStrGroup = "";
	 
		
	if (PHP_VERSION >= 5.1) {session_regenerate_id(true);} else {session_regenerate_id();}
    //declare three session variables and assign them
    $_SESSION['MM_Username'] = $loginUsername;
    $_SESSION['MM_UserGroup'] = $loginStrGroup;
	$_SESSION['MM_Nome'] = $Nome;
	

    if (isset($_SESSION['PrevUrl']) && true) {
      $MM_redirectLoginSuccess = $_SESSION['PrevUrl'];	
    }
    header("Location: " . $MM_redirectLoginSuccess );
  }
  else {
    header("Location: ". $MM_redirectLoginFailed );
  }
}
?>
<?php
mysql_free_result($login);
?>	
index.php (onde será redirecionado após a verificação

<?php
//initialize the session
if (!isset($_SESSION)) {
  session_start();
}

// ** Logout the current user. **
$logoutAction = $_SERVER['PHP_SELF']."?doLogout=true";
if ((isset($_SERVER['QUERY_STRING'])) && ($_SERVER['QUERY_STRING'] != "")){
  $logoutAction .="&". htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_GET['doLogout'])) &&($_GET['doLogout']=="true")){
  //Para registrar totalmente fora um visitante que precisamos para limpar os varialbles sessão
  $_SESSION['MM_Username'] = NULL;
  $_SESSION['MM_Nome'] = NULL;
  $_SESSION['MM_UserGroup'] = NULL;
  $_SESSION['PrevUrl'] = NULL;
  unset($_SESSION['MM_Username']);
  unset($_SESSION['MM_Nome']);
  unset($_SESSION['MM_UserGroup']);
  unset($_SESSION['PrevUrl']);
	
  $logoutGoTo = "../area_restrita.php";
  if ($logoutGoTo) {
    header("Location: $logoutGoTo");
    exit;
  }
}
?>
<?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, $Nome, $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 = "../area_restrita.php";

if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_Nome'], $_SESSION['MM_UserGroup'])))) {   
  $MM_qsChar = "?";
  $MM_referrer = $_SERVER['PHP_SELF'];
  if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
  if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0) 
  $MM_referrer .= "?" . $_SERVER['QUERY_STRING'];
  $MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "accesscheck=" . urlencode($MM_referrer);
  header("Location: ". $MM_restrictGoTo); 
  exit;
}
?>
<?php include("../config/db_conecta.php"); ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xml:lang="en" lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Pendências ::: Principal </title>
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Cache-Control" content="no-cache" />
<link rel="shortcut icon" href="./estilo/favicon.ico" />

<script src="./js/visual.js" type="text/javascript"></script>
<script src="./js/fullcontent.js" type="text/javascript"></script>
<script src="./js/common.js" type="text/javascript"></script>
<script src="./js/hk_js.js" type="text/javascript" ></script>

<link rel="stylesheet" href="./css/hk_style.css" type="text/css" />

<body>

<?php 

include('header.php')

?>



<div class='outerdiv' id='global-outerdiv'>

<table cellpadding='0' cellspacing='8' width='100%' id='tablewrap'>
<tr> <td width='16%' valign='top' id='leftblock'>
 <div>
<?php include('menu_index.php'); ?>
 </div>
 </td>
 <td width='78%' valign='top' id='rightblock'>
header.php (onde eu quero colocar o nome do usuário)

<div class="horizontal-menu">
        <ul>
            <li class="sub-menu"><a href=""><?php echo "Olá, " . $_SESSION["MM_Nome"]; ?> 
</a>
                <ul>
			<li><a href="<?php echo $logoutAction ?>">Sair</a></li>
					</ul>
    </div>
<div class="horizontal-menu">
        <ul>
			<li><a href="./">Home</a></li>
            <li><a href="#">Notícias</a></li>
			<li><a href="../../admin/slide">Slide</a></li>
			<li><a href="../../admin/configuracao">Configuração</a></li>
			<li><a href="#">Novidades</a></li>
			<ul>
            <li class="sub-menu"><a href="../../admin/usuarios">Usuários
</a>
                <ul>
			<li><a href="../../admin/usuarios/cadastro_aluno">Cadastro Ag</a></li>
            <li><a href="../../admin/usuarios/cadastro_professores">Cadastro PF</a></li>
			<li><a href="../../admin/usuarios/cadastro_adm">Cadastro Plataforma</a></li>
					</ul>
        </ul>
	
    </div>

Compartilhar este post


Link para o post
Compartilhar em outros sites

Por que tanto SELECT?

 

Se você também quer o nome, é só selecionar o campo na mesma consulta:

 

 

SELECT nome, usuario, senha FROM usuarios WHERE usuario=%s AND senha=%s

 

 

Veja este tutorial: http://blog.ultimatephp.com.br/sistema-de-login-php/

 

 

PS: funções mysql_* estão obsoletas desde o PHP 5.5 e já foram removidas no PHP 7. Prefira usar MySQLi ou PDO. Veja mais aqui: http://rberaldo.com.br/mysql-obsoleto-php/

Compartilhar este post


Link para o post
Compartilhar em outros sites

Por que tanto SELECT?

 

Se você também quer o nome, é só selecionar o campo na mesma consulta:

SELECT nome, usuario, senha FROM usuarios WHERE usuario=%s AND senha=%s

Veja este tutorial: http://blog.ultimatephp.com.br/sistema-de-login-php/

 

 

PS: funções mysql_* estão obsoletas desde o PHP 5.5 e já foram removidas no PHP 7. Prefira usar MySQLi ou PDO. Veja mais aqui: http://rberaldo.com.br/mysql-obsoleto-php/

 

Cara vlw msm, com o tutorial que me passou, consegui adaptar e utilizar. Além do mais que entendo melhor os codigos.

 

Vlw msm!

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.