Uploading files using .NET as client and PHP as Server

I was fed up with uploading the attachments using FTP as it was too slow (and vulnerable too), maintaining credentials to connect to server, managing permissions to specific folder etc. and all that nasty stuff.  Clients have also complained on this. After head-scratching and wall banging efforts, I planned to search for an alternative for FTP to upload the files. Found this way… Its pretty cool and uploading files much faster compared to FTP approach. Just wanted to share it with you, hoping that it may help someone who are in need!

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 here 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&#8221;,”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 am testing with an image file, I am 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 googling!

Advertisements

3 thoughts on “Uploading files using .NET as client and PHP as Server

  1. could you please tell me the tip “how to run a PHP code using VS 2008” I will be gr8ly thankfull for you.

    i am having a C# Web application and have some of the PHP files need to run them at one Dot net server..

    ????

    Thanks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s