Jump to content

$_SESSION['Name'] is this global?


Ansego
Go to solution Solved by Ansego,

Recommended Posts

Just wanted to know if $_Session was a global thing or does php require cookies setup?

 

I assumed that I could do something like this:

PAGE: A.php
session_start();
$_Session['Cat'] = 'Meow';

// -----------------------

PAGE: B.php
if (isset($_Session['Cat']) && !empty($_Session['Cat'])){
echo $_Session['Cat'];
}
OUTPUT: Meow

// -----------------------
PAGE: C.php
if (isset($_Session['Cat']) && !empty($_Session['Cat'])){
echo $_Session['Cat'];
}

OUTPUT: Meow


I can't seem to get this to work.

 

Page: Handler.inc

	// ========================================================= Session Log in / out
	public function logon($username, $password){
		if ($username == "admin" && $password == "coffee"){
			
				session_start();
				$_SESSION['USER_STATUS'] = '1';
				
				echo 'IN SESSION LOGIN HANDLER';
				echo $_SESSION['UserLogged'];
			}
		}
		
	public function logout(){
				$_SESSION['USER_STATUS'] = '0';
				
				echo 'IN SESSION LOGOUT HANDLER';
				
				session_destroy();
				//session_unset();
		}

Page: index.php

if (!isset($_SESSION['USER_STATUS']) && empty($_SESSION['USER_STATUS']) || $_SESSION['USER_STATUS'] == 0){
		if (isset($_POST['username']) && !empty($_POST['username']) && isset($_POST['password']) && !empty($_POST['password'])){
			
			$username = $_POST['username'];
			$password = $_POST['password'];
			
			echo $handler->logon($username, $password); 
		
			}

<LOGIN FORM CODE>

}else{

		if (isset($_SESSION['USER_STATUS']) && !empty($_SESSION['USER_STATUS']) || $_SESSION['USER_STATUS'] == 1){
			echo 'Session name: '. $_SESSION['USER_STATUS'];
		}

	if (isset($_POST['btn_logout']) && !empty($_POST['btn_logout'])){

		$handler->logout();
		echo '<br />Logged out<br />';
		
		}

<LOGOUT FORM BUTTON CODE>

}


Could someone point me in the right direction please. It does not seem to hold its session.

 

 

 

 

Link to comment
Share on other sites

I am lost what the heck am i doing!

 

PAGE: index.php

<?php 	
		session_start();
		//session_unset();
		//session_destroy();
?>

<!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>Server Status Login</title>
</head>

<body>

<?php
spl_autoload_register(function ($class) {
    include 'lib/' . $class . '.inc';
});

$handler = new handler;

?>
    <a style="text-decoration:none;" href='index.php'>Home</a> | 
    <a style="text-decoration:none;" href='test.php'>Test</a> | 
    <a style="text-decoration:none;" href='index.php'>A</a><br /><br />
<?php

	// # CHECKING SESSION READ OUT
	if (isset($_SESSION['USER_STATUS']) && $_SESSION['USER_STATUS'] == 1){
					echo '<br />Session SET: '.$_SESSION['USER_STATUS'].'<br />';
				}else{
					echo '<br />Nothing<br />';
					}
	
	// # ACCEPTS LOGIN DETAILS
	if (isset($_POST['username']) && !empty($_POST['username']) && isset($_POST['password']) && !empty($_POST['password'])){
			
			$username = $_POST['username'];
			$password = $_POST['password'];
			
			echo $handler->logon($username, $password); 
		
			}
			
	// # HANDLES LOGOUT
			if (isset($_POST['btn_logout']) && !empty($_POST['btn_logout'])){
	
			$handler->logout();
			echo '<br />Logged out<br />';
			
			}

	// # SESSION CHECK AND SHOW LOGIN FORM
    	if (isset($_SESSION['USER_STATUS']) && $_SESSION['USER_STATUS'] == 0){


?>
        <form action="index.php" method="post" enctype="application/x-www-form-urlencoded" name="Login">
          <table width="200" border="0" align="center" cellpadding="5" cellspacing="5">
            <tr>
              <td> </td>
              <td> </td>
              <td> </td>
            </tr>
            <tr>
              <td> </td>
              <td><input type="text" name="username" id="username" placeholder="Username" /></td>
              <td> </td>
            </tr>
            <tr>
              <td> </td>
              <td><input type="password" name="password" id="password" placeholder="Password" /></td>
              <td> </td>
            </tr>
            <tr>
              <td> </td>
              <td align="right"><input type="submit" name="btn_login" id="btn_login" value="Login" /></td>
              <td> </td>
            </tr>
            <tr>
              <td> </td>
              <td align="right"></td>
              <td> </td>
            </tr>
          </table>
        </form>
<?php
			
	// # IF SESSION IS SET TOO 1 SHOW LOGOUT BUTTON FORM	
		if (isset($_SESSION['USER_STATUS']) && $_SESSION['USER_STATUS'] == 1){
			echo '<br />Session name: '. $_SESSION['USER_STATUS'] ."<br />";
			

?>
        <form action="index.php" method="post" enctype="application/x-www-form-urlencoded" name="Login">
          <table width="200" border="0" align="center" cellpadding="5" cellspacing="5">
            <tr>
              <td> </td>
              <td></td>
              <td> </td>
            </tr>
            <tr>
              <td> </td>
              <td align="right"><input type="submit" name="btn_logout" id="btn_logout" value="Logout" /></td>
              <td> </td>
            </tr>
            <tr>
              <td> </td>
              <td align="right"></td>
              <td> </td>
            </tr>
          </table>
         </form>
<?php
			echo $handler->listServers();
			}
		}
?>
  <br />
  <br />
  <em style="font-size:9px;">copyright © 2014 ansego.com </em>

</body>
</html>

PAGE: handler.inc

<?php

	include_once '../../../Global-Includes/ServerStatus/db-connect.php';
	
//namespace xStatus;

class handler {
 
	private $username = '';
	private $password = '';
	
	private $db_Hostname	= HOSTNAME;
	private $db_Username	= USERNAME;
	private $db_Password	= PASSWORD;
	private $db_Database	= DATABASE;
	
	private $dbSQL			= '';
	
	//    function __construct($url, $port = '2302') {
    function __construct() {
		
	} // End Construct
	
	// ========================================================= Session Log in / out
	public function logon($username, $password){
		if ($username == "admin" && $password == "coffee"){
				//session_start();
				$_SESSION['USER_STATUS'] = 1;
			}else{
				echo '<br />Login Details failed!<br />';
				}
			
		}
		
	public function logout(){
				$_SESSION['USER_STATUS'] = 0;
				session_destroy();
				//session_unset();
		}
	
	// ========================================================= List Servers
	public function listServers(){
		
		$db = new mysqli($this->db_Hostname,$this->db_Username,$this->db_Password,$this->db_Database); // use your credentials
	
		$message = '';
		
		
			// list current servers from database
			$sql = "SELECT * FROM tbl_servers";
			$res = $db->query($sql);
			
			if ($res->num_rows > 0) {
				
				$message = '<h3>Current Servers</h3>';
				
				while ($row = $res->fetch_assoc()) {
					
					$message .= $row['HostGame'] . '<br />';
					$message .= $row['HostIP'] . '<br />';
					$message .= $row['HostPort'] . '<br />';
					$message .= $this->get_status($row['HostIP'],$row['HostPort']) . '<br /><br />';
					
				}
			}
			
			$message .= "<br />End of the \"Server List\" ";
			$message .= "<br />";
			
		$db->close();
		return $message;
		
		}
		
	// ========================================================= SEARCH SERVERS
	public function listSearchServers($field,$keyword){}

	// ========================================================= INSERT SERVERS
	public function insertServers($HostGame,$HostIP,$HostPort,$Datastamp,$Order){

		$sql = "INSERT INTO `serverstatus`.`tbl_servers`
		(`HostGame`,
			`HostIP`,
			`HostPort`,
			`Datastamp`,
			`Order`)
		VALUES
		($HostGame,
			$HostIP,
			$HostPort,
			$Datastamp,
			$Order)";

			//$sql = "INSERT INTO person (name) VALUES ('$name')";
			$result = sqlExecute($sql);

		return $result;
		
		}

	// ========================================================= UPDATE SERVERS	
	public function updateServers($ID, $HostGame,$HostIP,$HostPort,$Datastamp,$Order){

			$sql = "UPDATE `serverstatus`.`tbl_servers`
								SET
								`HostGame` = $HostGame,
								`HostIP` = $HostIP,
								`HostPort` = $HostPort,
								`Datastamp` = $Datastamp,
								`Order` = $Order
								WHERE `ID` = $ID";

			//$sql = "INSERT INTO person (name) VALUES ('$name')";
			$result = sqlExecute($sql);

		return $result;
		
		}

	// ========================================================= DELETE SERVERS
	public function deleteServers($id){

			$sql = "DELETE FROM `serverstatus`.`tbl_servers`
			WHERE ID = $id";

			//$sql = "INSERT INTO person (name) VALUES ('$name')";
			$result = sqlExecute($sql);

		return $result;
		
		}
	
	// ========================================================= Execute Helpers
	public function sqlExecute($sqlStatement){
		
		$db = new mysqli($this->db_Hostname,$this->db_Username,$this->db_Password,$this->db_Database); 
		$db->real_escape_string($sqlStatement);
		
		if ($db->query($sqlStatement)) {
			printf("%d Row inserted.\n", $db->affected_rows);
		}

		//$db->query($sql);
		
		$db->close();
		
		return true;
		
		}

	// ========================================================= GET STATUS
		public function get_status($ServerIP,&$ServerPort){
			
			// NOTICE THE @
			//if(@stream_socket_client("tcp://".$this.$ServerIP.":".$this.$ServerPort."", $errno, $errstr, 1) !== false) {
			//FIX: if(stream_socket_client("tcp://$ServerIP:$ServerPort", $errno, $errstr, 1) !== false) {
				
			if(@stream_socket_client("tcp://$ServerIP:$ServerPort", $errno, $errstr, 5) !== false) {
				return "<strong style='color:#33CC00'>Online</strong>";
			} else {
				return "<strong style='color:#CC0000'>Offline</strong>";
			}
			//return "Offline";
			}


	
/*

SELECT `tbl_servers`.`ID`,
    `tbl_servers`.`HostGame`,
    `tbl_servers`.`HostIP`,
    `tbl_servers`.`HostPort`,
    `tbl_servers`.`Datastamp`,
    `tbl_servers`.`Order`
FROM `serverstatus`.`tbl_servers`;

INSERT INTO `serverstatus`.`tbl_servers`
(`ID`,
`HostGame`,
`HostIP`,
`HostPort`,
`Datastamp`,
`Order`)
VALUES
(<{ID: }>,
<{HostGame: }>,
<{HostIP: }>,
<{HostPort: }>,
<{Datastamp: }>,
<{Order: }>);


UPDATE `serverstatus`.`tbl_servers`
SET
`ID` = <{ID: }>,
`HostGame` = <{HostGame: }>,
`HostIP` = <{HostIP: }>,
`HostPort` = <{HostPort: }>,
`Datastamp` = <{Datastamp: }>,
`Order` = <{Order: }>
WHERE `ID` = <{expr}>;

DELETE FROM `serverstatus`.`tbl_servers`
WHERE <{where_expression}>;



*/
	
	
	
	
    // property declaration
    public $var = 'a default value<br />';

    // method declaration
    public function displayVar() {
        echo $this->var .'<br />';
    }
	
	
	
	
	
	
	
} // End class






/* ======================================================== MESS

		//$this->myFunc = 'myFunc Value';

		echo 'Hello from construct...<br />';

        $this->server = array(
            "url" => $url, 
			"port" => $port
        );
		print_r($this->server);
	
*/


?>
Link to comment
Share on other sites

There are several other issues:

  • Do you actually store the admin credentials as plaintext in your script? Never store plaintext passwords, always hash them with bcrypt.
  • Your sessions are vulnerable to sessions fixation, because you keep reusing the same ID. If an attacker manages to set a custom session cookie in the victim's browser, they just need to wait for the victim to log-in. Now they know the ID of a fully authenticated session. To prevent this, the ID must be regenerated in the log-in procedure.
  • Your queries are vulnerable to SQL injection attacks. You've randomly added mysqli_real_escape_string() to one method, but you don't seem to understand what that does and how to use it. Manual escaping is obsolete, anyway. Learn to use prepared statements.
  • You establish a new database connection for every query. This is a performance killer and simply bad design. Establish one connection, store it in an attribute and then use it for all queries.
  • The mixture of PHP and HTML makes the code very hard to read and leads to many problems like the infamous “headers already sent” error. In modern code, you separate the application logic from the presentation. Put all the PHP stuff on top of the script and all the HTML to the bottom. Many people also use a dedicated template engine like Twig.
  • Your class is becoming a god object. Use separate objects for separate functionalities. For example, user authentication has absolutely nothing to do with listing servers, so there's no reason to put both into the same class. Proper names would also help (a “handler” could be pretty much anything).
  • Table layouts were OK in the 90s, but nowadays, we use CSS.
  • You declare the document as XHTML, but then you use plain HTML, making the markup invalid in either flavor. Is there any reason why you want XHTML? This is a rather exotic XML-based implementation of HTML and requires special treatment. For example, you cannot use the usual text/html content type. You need application/xhtml+xml, which in turn cannot be handled by older browsers. I'd just use plain HTML.
Link to comment
Share on other sites

@Jacques1 - 

 

These suggestions are amazing and sooo much appreciated mate, I've copied them down and are on my desktop for reference. 

 

Seriously thank you for the feed back, great bunch of guys on this forum, thank you,

 

ps. Hope you don't mind I will send you a pm to pick your brains some.

 

Re

 

Ansego.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.