Question How to upload file and POST vars to php

sbondo1234

Member
Joined
Jan 21, 2020
Messages
8
Programming Experience
1-3
I have a C# script that uploads an image to my webserver with PHP here:

C#:
C#:
WebClient Client = new WebClient();

Client.Headers.Add("Content-Type", "binary/octet-stream");

byte[] result = Client.UploadFile("https://example.com/test.php", "POST", @"C:\mario.jpg");

string s = Encoding.UTF8.GetString(result, 0, result.Length);

PHP:
PHP:
$uploads_dir = 'img'; //Directory to save the file that comes from client application.
if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) {
    $tmp_name = $_FILES["file"]["tmp_name"];
    $name = $_FILES["file"]["name"];
    move_uploaded_file($tmp_name, "$uploads_dir/$name");
}

This all works, but I also want to send along a variable that can be accessed in the PHP code like this:
PHP:
$variable = $_POST['variable'];

I want to send all of this in one request because the path the file ends up in is going to be decided by the C# and sent as 'variable' in the last PHP example.
 
You neglected to ask a question.

I'd like to point out that your post seems more geared towards php than it does C#. This might result in your post being closed at any point, as php questions are not supported on these forums.

If you wanted to upload additional values, wouldn't you use Client.UploadValues? WebClient.UploadValues Method (System.Net)
 
The OP wants the value(s) to be sent along with the call to WebClient.UploadFile().

Off the top of my head, I think the brute force approach to accomplish this is to use WebClient.UploadData() setting the content type to be "multipart/form-data", and then build the body of upload yourself.

For an overview, see Multipart formposts
 
Back
Top Bottom