2017-07-31 57 views
-2

我使用下面的HTML代碼和php代碼來寫入新文件。如何使用PHP編寫html文件?

<html> 
<body> 

<form action="write.php" method="get"> 
ID : <input type="text" name="ID"><br> 
<input type="submit"> 
</form> 

</body> 
</html> 

<?php 
    $myfile = fopen($_GET["ID"] , "w") or die("Unable to open file!"); 
    $txt = "Your user ID ="; 
    fwrite($myfile, $txt); 
    $txt = $_GET["ID"]; 
    fwrite($myfile, $txt); 
    fclose($myfile); 
?> 

如果我提交TEST到html表單,php代碼寫入一個名爲「test」的文件。它沒有文件擴展名。 如何用上面的代碼編寫「TEST.html」。?

+1

'$ _GET [「ID」]。「html」'。但在這裏我認爲'.html'是毫無價值的。你需要添加'.txt'extension。 –

+1

爲什麼你會試圖爲每個用戶ID創建一個html頁面?這似乎是一個非常糟糕的主意。 – Difster

+0

我正在爲少數發佈者創建一個簡單的聯盟系統。我爲每個用戶創建單獨的html文件。 – Thunga

回答

-1

你需要用!empty()檢查添加.html那裏,象下面這樣: -

<?php 
if(!empty($_GET['ID'])){ // check first that ID is coming or not 
    $myfile = fopen($_GET["ID"]."html" , "w") or die("Unable to open file!"); 
    $txt = "Your user ID ="; 
    fwrite($myfile, $txt); 
    $txt = $_GET["ID"]; 
    fwrite($myfile, $txt); 
    fclose($myfile); 
} 
?> 

要打開和讀取該文件: -

<?php 
    if(!empty($_GET['ID'])){ // check first that ID is coming or not 
    $myfile = fopen($_GET["ID"]."html", "r") or die("Unable to open file!"); 
    echo fread($myfile,filesize($_GET["ID"])); 
    fclose($myfile); 
    } 
?> 

OR: -

<?php 
if(!empty($_GET['ID'])){ // check first that ID is coming or not 
    $file = fopen($_GET["ID"]."html","r") or die("Unable to open file!"); ; 

    while(! feof($file)){ 
    echo fgets($file). "<br />"; 
    } 

    fclose($file); 
} 
?> 

注: -

在我看來,你需要用文字.txt而不是.html .An HTML文件中像test實在沒有意思,或服務器任何有用的目的順便說一下,它是你想要的擴展。我剛剛發表了我的看法。

2

打開文件之前添加擴展名: -

$filename = $_GET["ID"] . '.html'; 

$myfile = fopen($filename, "w") or die("Unable to open file!"); 

注意您正在開拓自己各種這裏的安全問題。

+0

如何使用此代碼打開以上html文件<?php $ myfile = fopen($ _ GET [「ID」],「r」)或死(「無法打開文件!」); echo fread($ myfile,filesize($ _ GET [「ID」])); fclose($ myfile); ?> – Thunga

+1

只需將上面創建的'$ filename'傳遞給函數而不是'$ _GET [「ID」]''。 – localheinz

1

只需使用此代碼: -

fopen($_GET["ID"].'.html' , "w")