2016-11-21 57 views
-2

传递变量到PHP脚本[POST]我使用此代码:如何使用C#

public void sendPostData(string url, string data) 
    { 
     WebRequest req = WebRequest.Create(url); 

     req.Method = "POST"; 
     req.ContentType = "application/x-www-form-urlencoded"; 

     byte[] bytes = Encoding.UTF8.GetBytes(data); 
     req.ContentLength = bytes.Length; 

     Stream dataStream = req.GetRequestStream(); 
     dataStream.Write(bytes, 0, bytes.Length); 
     dataStream.Close(); 
    } 

PHP进行后处理:

<?php 

if(@$_POST['filename']) 
{ 
    $data = filter_var($_POST['filename'], FILTER_SANITIZE_STRING); 
    $f = fopen($data.".txt", "w"); 
    fclose($f); 
} 
?> 

我打电话这个:

sendPostData("http://127.0.0.1/csharptest/index.php", "filename=myvariablehere"); 

所以,它所做的只是在服务器上创建一个文件名“myvariablehere”,而不是在myvariablehere中存储保存数据的值。

我希望在服务器上存储“myvariablehere”值。

请帮助这里!

感谢

+1

什么是你所得到的网址,尝试检查元素 –

+0

这听起来像代码的做法刚好它写的是什么。 –

+0

我没有得到任何网址。我只是想在服务器上保存变量值。它所做的只是保存我的变量名称而不是其中的数据。 –

回答

0

试试这个代码

public static class Upload 
    { 
     public static byte[] Post(string uri, NameValueCollection pairs) 
     { 
      byte[] response = null; 
      using (WebClient client = new WebClient()) 
      { 
       response = client.UploadValues(uri, pairs); 
      } 
      return response; 
     } 
    } 

,然后简单地调用这个

var response = Upload.Post("URL", new NameValueCollection() { 
    { "fileName", "test" }, 
});