打印时使用PHP写入文件

时间:2013-06-17 17:52:25

标签: php html css

我有以下HTML:

<form method="post" id="print" action="writefile.php" onsubmit="Javascript:window.print(); return true;">
<div id="non-printable">
Enter First & Last Name:
<input id="who" name="who" type="text" /><br><br>
Enter Taken Date:
<input id="tdate" readonly name="todays_date" onfocus="showCalendarControl(this);" type="text" /><br><br>
<input id="submit" type="button" class="btn" value="Submit" />
<div  id="printout" style="text-align:center;display:none;">
    <input type=submit value="Print Certificate" />
</div>
</div>
</form>
    <div id="parent">
    <h1>THIS WILL PRINT WHEN 'PRINT CERTIFICATE' IS PRESSED</h1>
    </div>

以下CSS:

@media print {
    #non-printable { display: none; }
    #parent { display: block; }
}

我要做的是当按下PRINT CERTIFICATE时我想写入我服务器中的文件,并且还显示当前正在执行的打印窗口。我怎么能做到这一点?

我知道我可以使用以下PHP,但结合是问题:

<?php 
session_start();

// Clean up the input values 
foreach($_POST as $key => $value) {  
    $_POST[$key] = stripslashes($_POST[$key]); 

    $_POST[$key] = htmlspecialchars(strip_tags($_POST[$key])); 
}
$printfor = $_POST['who'];
$dte = $_POST['todays_date'];

$filename = "writefile.txt"; #Must CHMOD to 666, set folder to 777

if($printfor && $dte) {
$text = "\n" . str_pad($_SESSION['printlogin'], 15) . "" . str_pad($printfor, 30) . "" . str_pad($dte, 15);

$fp = fopen ($filename, "a"); # a = append to the file. w = write to the file (create new if doesn't exist)
if ($fp) {
    fwrite ($fp, $text);
    fclose ($fp);
    #echo ("File written");
    }
    else {
        #echo ("File was not written");
    }
} 
?>

附加到文件:

Image

2 个答案:

答案 0 :(得分:3)

好吧,如果您更改了html文件,可以将php合并到其中。您可以通过将html按钮作为表单的一部分来触发该php表单。表单提交时,操作可以是whateveryounamedyourphpfile.php。如果你已经在表单上放置了隐藏的输入字段(你在那里寻找'userprint'和'date'输入的php,你可以让它写入文件。

HTML:

<form id="print" method="post" action="whateveryounamedyourphpfile.php" onsubmit="Javascript:window.print(); return true;">
   <input type="hidden" name="date" value="yourvaluehere" />
   <input type="hidden" name="userprint" value="yourvaluehere" />
   <input type="submit" value="Print Certificate" />
</form>

PHP:

<?php 


$printfor = $_post['userprint'];
$date = $_post['date'];

if($printfor && $date) {
$text = "\n" . str_pad($_SESSION['printlogin'], 10) . "" . str_pad($printfor, 25) . "" . str_pad($dte, 15);

$fp = fopen ($filename, "a"); # a = append to the file. w = write to the file (create new if doesn't exist)
if ($fp) {
    fwrite ($fp, $text);
    fclose ($fp);
    #$writeSuccess = "Yes";
        #echo ("File written");
    }
    else {
        #$writeSuccess = "No";
        #echo ("File was not written");
    }
} 

//Echo your HTML here
?>

答案 1 :(得分:2)

我为你创造了这个JS小提琴,让你顺利上路。 http://jsfiddle.net/KEHtF/

它使用.ajax将信息提交到PHP脚本,同时还调用print命令。