0

我对 PHP 比较陌生,我正在尝试运行一个小脚本。我有一个使用以下函数发布数据的 VB .net 程序。

Public Sub PHPPost(ByVal User As String, ByVal Score As String)
    Dim postData As String = "user=" & User & "&" & "score=" & Score
    Dim encoding As New UTF8Encoding
    Dim byteData As Byte() = encoding.GetBytes(postData)
    Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("http://myphpscript"), HttpWebRequest)
    postReq.Method = "POST"
    postReq.KeepAlive = True
    postReq.ContentType = "application/x-www-form-urlencoded"
    postReq.ContentLength = byteData.Length
    Dim postReqStream As Stream = postReq.GetRequestStream()
    postReqStream.Write(byteData, 0, byteData.Length)
    postReqStream.Close()
End Sub

其中“myphpscript”实际上是 PHP 脚本的完整 URL。基本上我正在尝试将“用户”变量和“分数”变量发布到 PHP 脚本。我试过的脚本如下:

<?php
    $File = "scores.rtf";
    $f = fopen($File,'a');
    $name = $_POST["name"];
    $score = $_POST["score"];
    fwrite($f,"\n$name $score");
    fclose($f);
?>

“scores.rtf”没有改变。任何帮助,将不胜感激。提前感谢,我是 PHP 新手。

4

2 回答 2

0

确保您的脚本正在接收 POST 变量。

http://php.net/manual/en/function.file-put-contents.php

你可以试试file_put_contents,它结合了fopen、fwrite和fclose的使用。

使用 isset/empty 之类的东西在写之前检查是否有东西要写可能是明智的。

<?php
$file = 'scores.rtf';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= print_r($_POST);

//Once confirmed remove the above line and use below
$current .= $_POST['name'] . ' ' . $_POST['score'] . "\n";

// Write the contents back to the file
file_put_contents($file, $current);
?>

此外,完全忽略了 RTF 部分,一定要看看 Mahan 提到的内容。如果您不需要该特定文件类型,我会建议上述内容。

于 2013-05-29T03:31:57.740 回答
0

“scores.rtf”没有改变。

RTF 文件的处理方式不同,因为它不是真正的纯文本文件,它包含控制文本在 rtf 文件上显示方式的元数据和标签。请有时间阅读以下来源

http://www.webdev-tuts.com/generate-rtf-file-using-php.html

http://blw.de/phprtf_en.php

http://paggard.com/projects/doc.generator/doc_generator_help.html

如果在任何情况下你想要一个普通的文本文件,你可以使用下面的代码,不要使用fwrite(),请使用file_put_contents()

file_put_contents("scores.txt", "\n$name $score");
于 2013-05-29T03:30:50.377 回答