I made the post function from the application in c#, then I want to insert the post data into the mysql database via the php file.
how can I prevent the entry of empty data into the database? because if I open the URL http://example.com/api/index.php directly in the browser, then there will be empty data that goes into the database, except the ip address.
I do not want if someone opens the url http://example.com/api/index.php directly, then there will be empty data entering the database because it can cause spam.
c# code :
public void uploadFile(string url, string filepath)
{
WebClient webClient = new WebClient();
try
{
webClient.UploadFile(url, "POST", filepath);
}
catch
{
}
finally
{
webClient.Dispose();
}
}
string lickey = desktoppath + randnumber + ".lic";
uploadFile(string.Format(url + api,
new object[]
{
licKeyID,
name,
GetAddress(),
}),
lickey);
private string url = "http://example.com/api";
private string api = "/index.php?lickey_id={0}&username={1}&password={2}&address={3}";
php code :
<?php
include('config.php');
$uploaddir = 'newdir/';
$uploadfile = $uploaddir . basename($_FILES['file']['name']);
$id = mysql_real_escape_string($_GET['license_id']) . '.lic';
$blacklist = array(".php", ".phtml", ".php3", ".php4", ".html", ".htm");
foreach ($blacklist as $item)
if(preg_match("/$item\$/i", $_FILES['file']['name'])) exit;
$f1 = file_get_contents($_FILES['file']['tmp_name']);
$fd = fopen($uploaddir.$id, 'w') or die("failed to create file");
fwrite($fd, $f1);
fclose($fd);
$check = mysql_query("SELECT * FROM `License` WHERE
`license_id`='".mysql_real_escape_string($_GET['license_id'])."' AND `checked`='false'");
if(mysql_num_rows($check) > 0)
{
exit(0);
}
mysql_query("INSERT INTO `License` SET
`ip`='".$_SERVER['REMOTE_ADDR']."',
`file`='$uploaddir".$id."',
`license_id`='".mysql_real_escape_string($_GET['license_id'])."',
`username`='".mysql_real_escape_string($_GET['username'])."',
`address`='".mysql_real_escape_string($_GET['address'])."',
`checked`='false'");
echo mysql_error();
mysql_close($dbcon);
?>
Validate input.
This can be done in many ways. One of them could be checking if $_FILES
global variable contains file
key, and if $_GET
contains license_id
, username
and address
.
if (isset($_FILES['file'])) {
die('Request invalid');
}
PS. Generally, using global variables is burdened with a security risk. What you could do, without refactoring this completely, think about adding a custom header (like X-Client: My Fancy CSharp Application
), and validating it inside PHP code.