2012-02-11 2 views
0

는 현재, HTML 측에 내 코드는 다음과 같습니다DB에 정보를 게시하는 더 나은 방법?

여기
<form action="newstory.php" method="post"> 
<input type="hidden" name="author" value="<?php echo $loggedInUser->display_username; ?>" 
/> 
<input type="hidden" name="userid" value="<?php echo $loggedInUser->user_id ?>" /> 
Story Title: <input type="text" name="story_name" /><br> 
Story: <textarea rows="10" cols="30" name="story" /></textarea><br> 
<input type="submit" /> 
</form> 

는 PHP 팀 :

include("dbconnect.php"); 

mysql_select_db("scratch", $con); 

$author  = mysql_real_escape_string($_POST['author']); 
$author_id = mysql_real_escape_string($_POST['userid']); 
$story_name = mysql_real_escape_string($_POST['story_name']); 
$story  = mysql_real_escape_string($_POST['story']); 

$sql= " 
INSERT INTO stories (author, author_id, story_name, story) 
VALUES ('$author', '$author_id','$story_name', '$story') 
"; 


if (!mysql_query($sql,$con)) 
{ 
die('Error: ' . mysql_error()); 
} 
echo "Story Submitted! Redirecting to Homepage..."; 
//User is shown this for about 3 seconds 
header('Refresh: 3; URL=index.php'); 

mysql_close($con) 

나는 사람들 때문에

<input type="hidden" name="author" value="<?php echo $loggedInUser->display_username; ? 
>"/> 

을 제거 할 수 쉽게 편집하고 모든 사용자로 게시 할 수 있지만 좋은 방법은 확실하지 않습니다. userid도 마찬가지입니다.

도움주세요.

+6

사용자가 로그인 한 경우 세션을 사용하여 ID를 저장하고 데이터베이스에 삽입하십시오. –

+2

PDO를 검색하고, 여러분이있는 동안에는 mysql_ * 함수를 사용하지 마십시오. –

+0

양식에서 사용자 데이터를 전송하지 마십시오. 인증을 위해'$ _SESSION' 데이터 사용 – Richard

답변

-1

사용자가 설정되어 있는지 확인하고 사용자 개체가 유효하면 해당 양식 만 표시하십시오. mysql을 사용하여 저장하기 바로 전에 POST 데이터에서 읽는 대신 사용자 객체의 값을 사용하십시오.

<?php if (isset($_POST['story_name'])) { 
// story posted.. check if user is set 
if (isset($loggedInUser->user_id)) { 
    // save into database using $loggedInUser->user_id and $loggedInUser->author_name 
} 
?> 

<?php 
// just show the form if the user object is set 
if (isset($loggedInUser->user_id)){ 
?> 
<form> <!-- and show the form over here --> </form> 
<?php } ?> 

아, 귀하의 mysql_real_escape_string()은 좋습니다! 또 다른 가장 좋은 방법은 sprintf()를 사용하여 쿼리에 변수를 추가하는 것입니다 형태로 숨겨진 입력 필드를 통해 userid 보내기

$author  = mysql_real_escape_string($loggedInUser->author_name); 
$author_id = mysql_real_escape_string($loggedInUser->user_id); 
$story_name = mysql_real_escape_string($_POST['story_name']); 
$story  = mysql_real_escape_string($_POST['story']); 

$sql= sprintf(" 
INSERT INTO stories (author, author_id, story_name, story) 
VALUES ('%s', '%s', '%s', '%s') 
", $author, $author_id, $story_name, $story); // %s accepts the value to be a string. %d accepts a decimal for example. 
+0

사용자 데이터를 조작 할 수 있기 때문에 사용자 데이터를 요청으로 보내면 안됩니다. 누구나 브라우저에서 숨겨진 필드를 편집하여 다른 사람으로 게시 할 수 있습니다 .. – Richard

+0

당신 말이 맞습니다. 정확하게 내가 위의 4 번줄에서 rood하지만 두 번째 코드 블록에서는 편집하지 않았습니다. – user1204156

1

거대한 보안 위협이다. 누구나 해당 값을 변경할 수 있습니다. Chrome의 검사기 또는 FireBug. 누군가가 로그인하면; 적어도 그들의 user_id를 세션에 저장해야합니다. 또한 세션에 더 많은 정보를 저장할 수 있으므로 예를 들어 모든 요청에 ​​대해 데이터베이스를 쿼리 할 필요가 없습니다. 로그인 한 사용자의 사용자 이름을 페이지의 어딘가에 보여줍니다.

현재 로그인을 어떻게 처리해야할지 모르겠으며 $loggedInUser이 어떻게 채워지는지 모르겠지만 세션 변수 여야합니다. $_SESSION['user']['id']. 그렇게하면 양식을 통해 데이터를 전송하지 않고도 사용자가 누구인지 항상 알 수 있습니다. 그건 진짜없는거야.

각 페이지 상단에 session_start()이 있어야하며 이상적으로는 템플릿을 사용하고 index.php 상단에 session_start()을 추가하면됩니다.

그리고

$sql= " 
INSERT INTO stories (author, author_id, story_name, story) 
VALUES ('$author', '$author_id','$story_name', '$story') 
"; 

적어도

$sql= " 
INSERT INTO stories (author, author_id, story_name, story) 
VALUES ('". $author ."', '". $author_id ."', '". $story_name ."', '". $story ."') 
"; 

되어야하고, 나는 개인적으로 추천 할 것입니다 :

$q = " 
INSERT INTO stories 
     SET author_id = ". $_SESSION['user']['id'] ." # This is an integer (I assume) so don't use apostrophe's 
      , story_name = '". mysql_real_escape_string($_POST['story_name']) ."' 
      , story = '". mysql_real_escape_string($_POST['story']) ."' 
"; 

테이블에서 필드 author를 제거합니다. 테이블 참조에 author_id을 사용하십시오. 그렇지 않으면 중복 데이터를 저장하게되고 누군가가 저자 이름을 변경하면 스토리의 저자 이름이 오래된/잘못된/쓸모가 없습니다.

+0

내 대답 업데이트 – Richard

+0

문제가 분류 되었습니까? 추신. 나는 당신의 코드에서 mysql_close ($ con)가 줄의 끝에 세미콜론을 가지고 있지 않음을 알았다. PHP가 닫히기 전에 마지막 줄 뒤에있는 세미콜론은 선택적이지만 아래 코드를 추가하기로 결정하면 오류가 발생합니다 :-) – Richard