2014-01-13 27 views
0

我搞砸了一些PHP和不熟悉如何更新數組正常工作。以下是我目前所面對的:更新PHP陣列,並更新服務器端

的index.php

<form action="register.php" method="get"> 
register > 
    <input name="reg_username" type="text" /> 
    <input name="reg_password" type="password" /> 
    <input id="submit" type="submit" /> 
</form> 

register.php

<?php 
    $username = $_GET["reg_username"]; 
    $password = $_GET["reg_password"]; 
     include('data/user_data.php'); 
     if(isset($users[$username])): 
      echo "this username is already taken!"; 
     else: 
      array_push($users, $username, $username, $password);    
     endif; 
?> 

user_data.php

<?php $users = array(
dextermb => array("dextermb", "password"), 
tonymb => array("tonymb", "password2") 
) 
?> 

我想,以確保當更新數組時,它保持與已經在其中的格式相同的格式。

"username" => array("username","password")

+0

只是一個建議,如果您正在使用的密碼工作,你應該使用post方法而不是get,post方法更安全,因爲它不會通過url。 – frosty11x

+0

是的,我聽說過不同之處:P只是使用它來確保一切正常工作(如沒有錯別字,這可能會讓我覺得代碼中有錯誤):) – Night

回答

1

只需添加一個新的元素添加到陣列的用戶名作爲鍵,包含用戶名和密碼的數組:

if(isset($users[$username])): 
    echo "this username is already taken!"; 
else: 
    $users[$username] = array($username, $password); 
endif; 
+0

這不會更新服務器端? – Night

+0

「不更新服務器端」是什麼意思? –

+0

將新陣列輸入從服務器或實例保存到user_data.php - 如果我要返回到index.php並嘗試用新的'用戶'登錄,它將以'不在陣列中'復原 – Night

0

你試過這樣嗎?

$users[$username] = array($username, $password); 

,使其在使用簡單的,你可以試試下面的代碼也

$users[$username] = $password; // If you have no other data in array 
+0

這不是一個好的解決方案,如果在某些情況下$ username是一個負數。最好的做法是始終使用數組中的鍵的常量,並防止使用變量。 –

+0

大聲笑。用戶名爲?這很陌生。 –

+0

這是一個普遍的考慮。當您測試您的代碼時,確保$ username可能永遠不會是負數,但在生產方式中,它應該被視爲風險。 –

0

array_push()只適用於非關聯數組。您明確設置陣列鍵和它的關聯值:

$array[$key] = array(); 

其結果是,你的代碼應該是這樣的:

if(isset($users[$username])): 
    echo "this username is already taken!"; 
else: 
    $users[$username] = array($username, $password);