LoginSignup
14
16

More than 3 years have passed since last update.

C#からPHPにPOSTする

Last updated at Posted at 2018-02-03

C#のプログラムからWebサーバー上のPHPにHTTPのPOSTで送信したデータをもとにサーバー上で処理を行うプログラムを作るときのメモです。

C#からPHPに普通にPOST送信

単純なPOSTでPHPに複数の文字列を送信する方法

client.cs
var hc = new HttpClient();
var dic = new Dictionary<string, string>();
dic["hiragana"] = "ほげ~";
dic["katakana"] = "ホゲ~";
var cont = new FormUrlEncodedContent(dic);
var url = "http://〇〇.com/server.php";
var req = await hc.PostAsync(url, cont);
var html = await req.Content.ReadAsStringAsync();
Console.WriteLine(html);
server.php
$hoge1 = $_POST['hiragana'];
$hoge2 = $_POST['katakana'];
echo $hoge1 . $hoge2;

これを実行すると、client.csのhtmlには、"ほげ~ホゲ~" が代入されています。
(参考:第7回 C#で自作Android アプリを作ろう:簡易アンケートを作ろう

C#からPHPにファイルも併せてPOST送信

client.cs
var hc = new HttpClient();
var dic = new Dictionary<string, string>();
dic["hiragana"] = "ほげ~";
dic["katakana"] = "ホゲ~";
dic["FileName"] = "hogehoge.jpg";

var fileName = @"C:\hoge.jpg";
var fileContent = new StreamContent(File.OpenRead(fileName));
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
  FileName = Path.GetFileName(fileName),
  Name = @"userfile[]"
};

var content = new MultipartFormDataContent();
foreach (var param in dic)
{
    content.Add(new StringContent(param.Value), param.Key);
}
content.Add(fileContent);

var hc = new HttpClient();
var url = "http://〇〇.com/uploadfile.php";
var req = await hc.PostAsync(url, content);
var html = await req.Content.ReadAsStringAsync();
Console.WriteLine(html);
uploadfile.php
$hoge1 = $_POST['hiragana'];
$hoge2 = $_POST['katakana'];
echo $hoge1 . $hoge2;

//アップロードされたファイルの数をカウント
$count = count($_FILES['userfile']['name']);
if($count==0){
  echo 'File is not uploaded';
  return;
}

for ($i=0; $i<$count; $i++) {
  $tem_fname = $_FILES['userfile']['tmp_name'][$i];
  if (!is_uploaded_file($tem_fname)) {
    echo "There is no temporary file";
    return;
  }
  if (!move_uploaded_file($tem_fname, $fname)) {
    echo "Unable to move file";
    return;
  }
}

hogehoge.jpgという名前で、サーバーにファイルが保存されます。
※ファイル属性(権限)が777とかになっていないと、PHPによる書き込みが制限されるため移動でません。

(参考:HttpClient を使ってPOSTでマルチパートのファイルを送受信する

PHPからPHP

PHPからPHPにファイルを送信する場合、PHPのcliからcurlでファイルアップロード にまとめてあった(すごくお世話になりました。感謝です!)ので省略しました。

14
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
16