I'm trying to upload a file and some data with POST request from my C# program to my server, but I receive always error 403.
The post params are "id" = folder where the file will be saved "pos" = the name of the file
So, if an user upload file "abc.text" and POST data are id="Mario" pos="first" the file will be saved in /users/Mario/first.txt
I tried to change params id and pos as GET, but I always have error 403
C# response
{StatusCode: 403, ReasonPhrase: 'Forbidden', Version: 1.1,
Content: System.Net.Http.StreamContent,
Headers:{ Vary: Accept-Encoding X-Varnish: 818481486 Age: 0
X-Cache: MISS Transfer-Encoding: chunked Connection: keep-alive
Date: Thu, 18 Apr 2019 14:29:10 GMT Content-Type: text/html;
charset=iso-8859-1}}
My Code:
<!DOCTYPE html>
<html>
<head>
<title>Upload your files</title>
</head>
<body>
<form enctype="multipart/form-data" action="uploader2.php" method="POST">
<p>Upload your file</p>
<input type="file" name="uploaded_file"></input><br />
<input type="input" name="id"></input><br />
<input type="input" name="pos"></input><br />
<input type="submit" value="Upload"></input>
</form>
</body>
</html>
<!-- language: lang-php -->
<?PHP
if(!empty($_FILES['uploaded_file']))
{
$path = "users/".$_POST['id']."/";
if(!is_dir($path))
{
if(!mkdir ($path,0777,true))
echo 'Error creating folder!';
}
$path = $path.$_POST['pos'].".txt";
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
echo "Ok";
} else{
echo "Failed!";
}
}
?>
This is my C# code
using (var httpClient = new HttpClient())
{
MultipartFormDataContent multipartContent = new MultipartFormDataContent();
var fp = File.ReadAllBytes("file.txt");
multipartContent.Add(new StringContent("Mario"), "id");
multipartContent.Add(new StringContent("first"), "pos");
multipartContent.Add(new ByteArrayContent(fp, 0, fp.Length), "uploaded_file", "file.txt");
HttpResponseMessage response = await httpClient.PostAsync("http://host.com/uploader2.php", multipartContent);
response.EnsureSuccessStatusCode();
httpClient.Dispose();
string sd = response.Content.ReadAsStringAsync().Result;
}
}
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
Use this in your php script:
header("Access-Control-Allow-Origin: *"); // wildcard allows access to all domains
Access-Control-Allow-Origin is a CORS (Cross-Origin Resource Sharing) header.
When Site A tries to fetch content from Site B, Site B can send an Access-Control-Allow-Origin response header to tell the browser that the content of this page is accessible to certain origins. (An origin is a domain, plus a scheme and port number.) By default, Site B's pages are not accessible to any other origin; using the Access-Control-Allow-Origin header opens a door for cross-origin access by specific requesting origins.