info:myphp:sessions

PHP Sessions

Tutoriels

voir toutes les variables de session de son site

<?php
foreach($_SESSION as $key => $value)
echo $key." = ".$value."<br />";
 
//ou en utilisant ce code
 
print("<pre>");
print_r($_SESSION);
print("</pre>");
?> 

Utilisation de sessions avec PHP

il faut une db mysql et des scripts php

CREATE TABLE `users_session` (
  `sid` varchar(255) NOT NULL,
  `userid` varchar(255) NOT NULL,
  `last_modified` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
  `ip` varchar(15) NOT NULL,
  PRIMARY KEY  (`sid`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

CREATE TABLE `users` (
  `user_name` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `role` varchar(255) NOT NULL,
  PRIMARY KEY  (`user_name`),
  UNIQUE KEY `user_name` (`user_name`),
  KEY `password` (`password`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
<?php
#here we set the path relative to server name
$serveur= $_SERVER["HTTP_HOST"];
$role=$_SESSION['role'];
#echo $serveur;
if($serveur=="localhost") { //serveur de développement
$CHEMIN="/websites//";
$REPERTOIRE="/";

} elseif ($serveur==""){ //serveur de prod
$CHEMIN="/";
$REPERTOIRE="/";

} elseif ($serveur==""){ //serveur de backups
$CHEMIN="//";
$REPERTOIRE="/";
}
require_once($REPERTOIRE."common/sessions.inc.php");



#special stuff to give different mySQL login for different authentification
#admin: all rights
if($role=="Administrateur") {
	if($serveur=="localhost") {  
      $dbUsername = "";
      $dbPassword = "";	
	$dbName="";
	} elseif ($serveur==""){ //serveur de prod
      $dbUsername = "";
      $dbPassword = "";	
		$dbName="";

	} elseif ($serveur==""){ //serveur de backups
      $dbName     = "";          
	$dbUsername = "";
      $dbPassword = "";	
	}
#surfer: SELECT only
} elseif ($role=="Surfeur"){
	if ($serveur==""){ //serveur de backups
	$dbUsername = "";
      $dbPassword = "";	
      $dbName     = "";          

	} else { //serveur de développement && //serveur de prod
	$dbUsername = "";
	$dbPassword = "";
	$dbName="";

	}
} else {
#on renvoie la personne non authentifiée au login et on exclut la suite
echo "Probl&egrave;me d'identification! Vous n'&ecirc;tes pas autoris&eacute;-e &agrave; utiliser le syst&egrave;me";
exit;
}
      $dbHostname = "localhost";


#echo $dbName;
      //  Make connection to database 
      //  If no connection made, display error Message          
      $dblink = MYSQL_CONNECT($dbHostname, $dbUsername, $dbPassword) OR DIE("Error dBc1 !! Unable to connect to database");       

      // Select the database name to be used or else print error message if unsuccessful*/
      @mysql_select_db($dbName) or die( "Unable to select database ".$dbName); 

?>
<?php
error_reporting(0);
	#initialisation temps pour calcul chargement page, fin sur footer.php
$time_start = microtime(true);
/*
Software for the administration of teachers formation
Fred Radeff, radeff.red mercredi 23 mai 2007, 15:24:32 (UTC+0200)
License: GNU General Public License (GPL) 
SPECIAL THANKS To http://sourceforge.net/projects/phpcodegenie/
*/

#GENERAL SETTING FOR THE WHOLE SITE
$APPLICATION_NAME="nom du site";
#here we set the path relative to server name
$serveur= $_SERVER["HTTP_HOST"];
#echo $serveur;
if($serveur=="localhost") { //serveur de développement
  $CHEMIN="/websites/"; // chemin sur le serveur
  $REPERTOIRE="/home/radeff/"; //chemin local
} elseif ($serveur=="test.ch"){ //serveur de prod
$CHEMIN="";
$REPERTOIRE="";
} elseif ($serveur=="www.other.ch"){ //serveur de backups
$CHEMIN="";
$REPERTOIRE="";
}
require_once($REPERTOIRE."common/sessions.inc.php");
include("tools.inc.php");


?>
<HTML>
<HEAD>
<TITLE><? 
if ($serveur==""){ // message d'avertissement serveur de secours
echo "*** ATTENTION: SERVEUR DE SECOURS! ***";
}
#echo $APPLICATION_NAME;
if(isset($page_name)&&$page_name!="") {
echo $page_name;
}
?></TITLE>
<link rel="stylesheet" href="<? echo $CHEMIN ?>common/style.css" type="text/css">
<script language="javascript" src="<? echo $CHEMIN ?>common/javascripttools.js"></script>
<LINK REL="SHORTCUT ICON" href="<? echo $CHEMIN ?>favicon.ico">
</HEAD>
<!-- Here is the main title of the site-->
<BODY>
<?
#cas particulier du serveur de secours
if ($serveur=="www.productionserver.ch"){ // affichage serveur de secours et interdiction opérations SQL INSERT UPDATE DELETE
echo "<h1 style=\"text-decoration: blink\">*** ATTENTION: SERVEUR DE SECOURS! ***</h1>";
	if(ereg("/edit",$PHP_SELF)||ereg("/confirmDelete",$PHP_SELF)||ereg("/delete",$PHP_SELF)||ereg("/enterNew",$PHP_SELF)||ereg("/update",$PHP_SELF)||ereg("/insert",$PHP_SELF)) {
	echo "Sur le serveur de secours vous n'avez pas accès à cette page";
	exit; // on sort
	};
}
?>
<NOSCRIPT><h1>Merci d'activer JavaScript! Le syst&ecirc;eme ne marche pas sans!!!</h1></NOSCRIPT>
<A href="<? echo $CHEMIN ?>"><IMG src="<? echo $CHEMIN ?>common/logo.jpg" alt="logo + homepage" title="logo + homepage" width="100" height="100" align="left" border="0"></A>
<div id="main-title"><? 
echo $APPLICATION_NAME; 
if(isset($page_name)&&$page_name!="") {
echo " - " .$page_name;
}
echo " <div class=\"petitGros\">user: " .$PHP_AUTH_USER ." / role: " .$_SESSION['role'] 
." | <a href=\"" .$CHEMIN ."logout.php\" style=\"font-size: x-small\">Logout</a></div>";
?></div>
<div id="main-text">
<?php

      session_start( );

$PHP_AUTH_USER=$_SERVER['PHP_AUTH_USER'];
$PHP_AUTH_PW=$_SERVER['PHP_AUTH_PW'];

function showerror( )
   {
      die("Error " . mysql_errno( ) . ": " . mysql_error( ));
}
function authenticateUser($username, 
                          $password) {
$serveur= $_SERVER["HTTP_HOST"];
if($serveur=="localhost") { //serveur de développement
      $dbUsername = "";
      $dbPassword = "";
      $dbHostname = "localhost";
      $dbName     = "";      

} elseif ($serveur=="truc.ch"){ //serveur de prod
      $dbUsername = "";
      $dbPassword = "";
      $dbHostname = "";
      $dbName     = "";      

} elseif ($serveur==""){ //serveur de backups
      $dbUsername = "";
      $dbPassword = "";
      $dbHostname = "localhost";
      $dbName     = "";      

}

      $dblink = MYSQL_CONNECT($dbHostname, $dbUsername, $dbPassword) OR DIE("Error dbc1 !! Unable to connect to database");       
      @mysql_select_db($dbName) or die( "Unable to select database ".$dbName); 

  // Test the username and password parameters
  if (!isset($username) || !isset($password))
    return false;

  // Get the two character salt from the 
  // username collected from the challenge
  $salt = substr($username, 0, 2); 

  // Encrypt the password collected from 
  // the challenge

  // Formulate the SQL find the user
  $query = "SELECT * FROM users
               WHERE user_name = '$username'
               AND password = md5('$password')";
#echo $query;
  // Execute the query
  $result = mysql_query($query);


  // exactly one row? then we have found the user
  if (mysql_num_rows($result) != 1) 
    return false;
  else
    return true;
}

if (!authenticateUser($PHP_AUTH_USER,
                     $PHP_AUTH_PW)||!isset($PHP_AUTH_USER,
                     $PHP_AUTH_PW))
{
  // No credentials found - send an unauthorized
  // challenge response ...
    header("WWW-Authenticate: Basic realm='Restricted Area'");
  header("HTTP/1.0 401 Unauthorized");
    print("<H1>Authorization Required</H1>This server could not verify that you are authorized to access the document requested. Either you supplied the wrong credentials (e.g., bad password), or your browser doesn't understand how to supply the credentials required.<hr>");
    exit;      
  // ...

  exit;
} else {

// The HTML response to authorized users ...
if($printable!="oui"){
include_once("../common/header.php");
}
  $query = "SELECT * FROM users
               WHERE user_name = '$PHP_AUTH_USER'";
  $result = mysql_query($query);

$sid=session_id();
$now= date("Y-m-d H:m:s");
$chercheSession="SELECT * FROM `users_session` WHERE `sid`='$sid'";
$chercheSession=mysql_query($chercheSession);
$chercheSession=mysql_num_rows($chercheSession);
#echo $chercheSession;
if($chercheSession<1) {
$insert="INSERT INTO `users_session` ( `sid` , `userid` , `last_modified` , `ip` )
VALUES (
'$sid', '$PHP_AUTH_USER', '$now' , '$remote_addr'
)";

$insertSQL=mysql_query($insert);
}
$role=mysql_result($result,0,'role');
// Register the variable named "role"
session_register("role");
$foo = $role;
}

?>
  • info/myphp/sessions.txt
  • Dernière modification : 2026/03/05 08:57
  • de radeff