Level: Beginner (coder)
This is a small tutorial which will teach you how to upload files using a C# client application to a server running PHP.
We’ll call the PHP script “upload.php”, this is what it should contain:
<?php
$uploaddir = ‘upload/’; // Relative Upload Location of data file
if (is_uploaded_file($_FILES[‘file’][‘tmp_name’])) {
$uploadfile = $uploaddir . basename($_FILES[‘file’][‘name’]);
echo “File “. $_FILES[‘file’][‘name’] .” uploaded successfully. “;
if (move_uploaded_file($_FILES[‘file’][‘tmp_name’], $uploadfile)) {
echo “File is valid, and was successfully moved. “;
}
else
print_r($_FILES);
}
else {
echo “Upload Failed!!!”;
print_r($_FILES);
}
?>
and this is the C# code:
System.Net.WebClient Client = new System.Net.WebClient ();
Client.Headers.Add("Content-Type","binary/octet-stream");
byte[] result = Client.UploadFile ("http://your_server/upload.php","POST","C:\test.jpg");
string s = System.Text.Encoding .UTF8 .GetString (result,0,result.Length );
In the C# part, replace “your_server.com” with your server, also notice that this is a test code, it will upload c:\\test.jpg, because i’m testing with an image file, im using the header “binary/octet-stream” as it works with all files (image, txt, etc)…
Hope this helps someone out there as I couldn’t find any tutorials about this specific matter on google! Let me know if you got any questions,
Happy Coding

