2013-02-21 3 views
11

나는이 사이트에서 답변을 검색했지만 couldnt를 찾았습니다.PHP가 입력에서 txt로 파일 쓰기

나는 형식이 있으며 입력 내용을 txt 파일에 기록하고 싶습니다. 간단하게하기 위해 간단한 양식과 스크립트를 작성했지만 빈 페이지를 계속 가져옵니다. 여기에 내가

<html> 
<head> 
    <title></title> 
</head> 
<body> 
    <form> 
     <form action="myprocessingscript.php" method="post"> 
     <input name="field1" type="text" /> 
     <input name="field2" type="text" /> 
     <input type="submit" name="submit" value="Save Data"> 
    </form> 
    <a href='data.txt'>Text file</a> 
</body> 

있어 무엇이며, 여기에 데이터가 GET 방법에가는 것을, 내 PHP 파일

<?php 
$txt = "data.txt"; 
$fh = fopen($txt, 'w+'); 
if (isset($_POST['field1']) && isset($_POST['field2'])) { // check if both fields are set 
    $txt=$_POST['field1'].' - '.$_POST['field2']; 
    file_put_contents('data.txt',$txt."\n",FILE_APPEND); // log to data.txt 
    exit(); 
} 
    fwrite($fh,$txt); // Write information to the file 
    fclose($fh); // Close the file 
    ?> 
+1

합니까는'더 출력을 생성 myprocessingscript.php'? 두 번째 스 니펫이 전체 PHP 스크립트 인 경우 빈 페이지는 출력을 생성하지 않을 때 얻을 수있는 페이지입니다. – acme

+0

또한 공백 페이지를 얻는 것은 정상적인 현상이며, 클라이언트에게는 아무 것도'echo() '하지 않습니다. – Floby

답변

33

과 같아야 양식 :

<form action="myprocessingscript.php" method="POST"> 
    <input name="field1" type="text" /> 
    <input name="field2" type="text" /> 
    <input type="submit" name="submit" value="Save Data"> 
</form> 

내가 /tmp/mydata.txt에 쓴

<?php 
if(isset($_POST['field1']) && isset($_POST['field2'])) { 
    $data = $_POST['field1'] . '-' . $_POST['field2'] . "\n"; 
    $ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX); 
    if($ret === false) { 
     die('There was an error writing this file'); 
    } 
    else { 
     echo "$ret bytes written to file"; 
    } 
} 
else { 
    die('no post data to process'); 
} 

는 PHP를하기 때문에이 방법으로 지금 바로 I 곳은. data.txt을 사용하면 현재 작업 디렉토리의 해당 파일에 씁니다.이 파일은 내가 알지 못하는 예제입니다.

file_put_contents 파일을 열고 쓰고 닫습니다. 그것을 망쳐 놓지 마십시오.

추가 읽기 : file_put_contents

+0

다시 'data.txt'로 바꿨지 만 나머지는 완벽합니다. – user2094841

+0

공유 호스트에서 액세스 권한이없는 곳에서/tmp, mydata.txt는 어디에 두겠습니까?내 디렉토리 구조는 ~/www-root/ – cryptic0

+0

입니다. 여기에 머문 시간을 정말 감사드립니다, 플로비. 이것은 정말 우아한 솔루션이며 워드 프레스 플러그인과 같은 타사 양식 프로세서에서 필요로하는 많은 스크립트를 버릴 수있었습니다. :) – Nathan

5

당신이 가지고 있기 때문에 당신이 가지고있는 여분의 <form>의있는 문제이며, POST을 사용하여 PHP의 데이터에 액세스하고 있습니다.

<body> 
<!--<form>--> 
    <form action="myprocessingscript.php" method="POST"> 
+1

독수리 눈에 +1 : D – acme

+0

@acme 환영합니다. :) –

0

가능한 솔루션 :

<?php 
$txt = "data.txt"; 
if (isset($_POST['field1']) && isset($_POST['field2'])) { // check if both fields are set 
    $fh = fopen($txt, 'a'); 
    $txt=$_POST['field1'].' - '.$_POST['field2']; 
    fwrite($fh,$txt); // Write information to the file 
    fclose($fh); // Close the file 
} 
?> 

당신은 가까운 데 파일 전에 스크립트를 폐쇄했다.

0

file_put_contents를 사용하는 경우 fopen -> fwrite -> fclose를 수행 할 필요가 없으면 file_put_contents가 모든 작업을 수행합니다. 또한 웹 서버에 "data.txt"파일을 쓰려고하는 디렉토리에 쓰기 권한이 있는지 확인해야합니다.

PHP 버전 (이전 버전 인 경우)에 따라 file_get/put_contents 기능이 없을 수 있습니다. 스크립트를 실행할 때 오류가 발생했는지 웹 서버 로그를 확인하십시오. fwrite() 대신에 file_put_contents를의

+0

관리자가 서버에서 실행하면 작동하는 것으로 나타났습니다. 어떻게 권한을 변경할 수 있습니까? – user2094841

+0

웹 서버가 아파치 인 경우 :'chown -R apache : apache dir_where_you_create_the_file' – Naryl

0

사용()