2014-11-18 1 views
0

html로 양식을 작성 중입니다. 사람이 제출을 클릭하면 특정 필드가 올바르게 채워지는지 확인하기 때문에 지금까지는 매우 간단한 형식이었습니다.PHP로 양식 값 저장 및 SESSION을 사용하여 쿠키 호출하기

그러나 사람이 페이지를 새로 고치면 입력란에 입력 한 텍스트를 저장하고 싶습니다. 따라서 페이지가 새로 고쳐지면 텍스트는 필드에 계속 표시됩니다.

나는 이것을 PHP와 쿠키를 사용하여 시도하고있다.

// Cookie 

    $saved_info = array(); 
    $saved_infos = isset($_COOKIE['offer_saved_info']) ? explode('][', 
    $_COOKIE['offer_saved_info']) : array(); 

    foreach($saved_infos as $info) 
    { 
     $info_ = trim($info, '[]'); 
     $parts = explode('|', $info_); 

     $saved_info[$parts[0]] = $parts[1]; 
    } 

    if(isset($_SESSION['webhipster_ask']['headline'])) 
     $saved_info['headline'] = $_SESSION['webhipster_ask']['headline']; 

    // End Cookie 

이제 폼 입력 필드 :

<div id="headlineinput"><input type="text" id="headline" 

value="<?php echo isset($_SESSION['webhipster_ask']['headline']) ? 
$_SESSION['webhipster_ask'] ['headline'] : ''; ?>" 

tabindex="1" size="20" name="headline" /></div> 

내가 그렇게 내 후 질문은, PHP에서 세션을 사용하여에 새로운 오전 :

는 사용하지 않고이를 달성하는 간단한 방법이 있나요 위와 같은 쿠키? 또는 위의 코드에서 내가 잘못 했습니까? 정말 생각하지만 당신이 묻는 유일한 질문이 아니다

echo (isset($_SESSION['webhipster_ask']['headline']) ? value : value) 

을 :

+0

$ _SESSION의 모든 저장. 여기에서 모든 것을 액세스 할 수 있습니다. 또는 jquery 쿠키 플러그인을 시도하고 쿠키에있는 모든 것을 저장하고 js – brandelizer

+0

을 통해 쿠키의 데이터를 읽습니다. 쿠키에 이러한 것들을 저장하는 가장 좋은 방법은 json 문자열 (Json으로 배열)을 사용하는 것입니다. – brandelizer

+1

@brandelizer 세션에 저장하는 경우 JSON을 사용할 필요가 없습니다. '$ _SESSION'에 배열을 직접 넣을 수 있습니다. PHP는 제대로 배열을 처리합니다. – Barmar

답변

1

우선 내가 그것을 좋아 주위에 당신이 괄호가 있어야 에코있어 확신합니다.

양식을 통해 데이터를 제출하는 경우 양식 값을 사용하여 유효성을 검사하지 말고 html 입력 값에 양식 값을 사용하십시오. 일단 데이터를 확인하고 이동하면 세션을 저장합니다. 예를 들어

:

<?php 
session_start(); 
$errors=array(); 

if($_POST['doSubmit']=='yes') 
{ 
    //validate all $_POST values 
    if(!empty($_POST['headline'])) 
    { 
     $errors[]="Your headline is empty"; 
    } 
    if(!empty($_POST['something_else'])) 
    { 
     $errors[]="Your other field is empty"; 
    } 

    if(empty($errors)) 
    { 
     //everything is validated 
     $_SESSION['form_values']=$_POST; //put your entire validated post array into a session, you could do this another way, just for simplicity sake here 
     header("Location: wherever.php"); 
    } 
} 
if(!empty($errors)) 
{ 
    foreach($errors as $val) 
    { 
     echo "<div style='color: red;'>".$val."</div>"; 
    } 
} 
?> 
<!-- This form submits to its own page //--> 
<form name="whatever" id="whatever" method="post"> 
<input type="hidden" name="doSubmit" id="doSubmit" value="yes" /> 
<div id="headlineinput"> 
<input type="text" id="headline" value="<?php echo $_POST['headline'];?>" tabindex="1" size="20" name="headline" /> 
<!-- the line above does not need an isset, because if it is not set, it will simply not have anything in it //--> 
</div> 
<input type="submit" value="submit" /> 
</form>