2014-02-11 164 views
1

我有一些簡單的系統來上傳文件並使用數據庫爲每個特定用戶跟蹤它們。PHP變量聲明

我的問題是,我連接到checklogin.php文件中的數據庫,該文件負責處理來自main_login.php$_POST

在文件 'checklogin.php':

$current_user_name = NULL; 

這是所有文件的全局變量。現在,在文件signup.php,我嘗試包括checklogin.php定義變量:

require_once '/checklogin.php'; 
... 
mysql_query("INSERT INTO " . tbl_name . " (username, userpassword, userisadmin) 
     VALUES (''" . $_POST['myusername'] . "'," 
     . "'" . md5($_POST['mypassword']). "'," 
     . "0)"); 
$current_user_name = $_POST['myusername']; 
header("location:login_success.php"); 

正如你所看到的,我嘗試設置變量$current_user_name = $_POST['myusername'];的價值,但是當header轉到文件login_success.php,它也有require_once '/checklogin.php';,變量再次設置爲null

我該如何解決這個問題?即我如何存儲當前用戶以使其可以被所有文件訪問?

+0

爲什麼不把'$ current_user_name'作爲'SESSION'變量呢? –

+0

@ShankarDamodaran我仍然是php中的一個開始...... – user1234524521

+3

在創建查詢之前,請始終從$ _POST或$ _GET中對輸入進行清理。 http://stackoverflow.com/questions/129677/whats-the-best-method-for-sanitizing-user-input-with-php – EdCapetti

回答

2

你不能存儲這樣的變量。每個請求都將重新執行。在這種情況下,我們必須使用會話請this

並與你的代碼中的另一個問題是SQL注入,請仔細閱讀this

1

您不能訪問在checklogin.php

收到的參數是什麼你可以做你可以檢查登錄狀態並設置當前用戶在會話中。

從會話變量中,您可以訪問和設置當前用戶。

1

你可以設置一個會話變量它和每一個你可以使用它像這樣

session_start(); 
    if(isset($_SESSION['current_user_name'])) 
    { 
     $current_user_name = $_SESSION['current_user_name']; 
    } 
    else 
    { 
     $current_user_name = NULL; 
    } 

並設置會話變量如下

session_start(); 
require_once '/checklogin.php'; 
////... 
mysql_query("INSERT INTO " . tbl_name . " (username, userpassword, userisadmin) 
     VALUES (''" . $_POST['myusername'] . "'," 
     . "'" . md5($_POST['mypassword']). "'," 
     . "0)"); 
$current_user_name = $_POST['myusername']; 
$_SESSION['current_user_name'] = $current_user_name; // set your session here 
header("location:login_success.php"); 
+0

謝謝,不幸的是我不能選擇多個最佳答案! – user1234524521