[英]how do I prevent empty data inserting into mysql database from post http request
我在c#中從應用程序中創建了post函數,然后我想通過php文件將post數據插入到mysql數據庫中。
如何防止空數據進入數據庫? 因為如果我直接在瀏覽器中打開URL http://example.com/api/index.php ,那么除了ip地址之外,都會有空數據進入數據庫。
我不希望如果有人直接打開url http://example.com/api/index.php ,那么就會有空數據進入數據庫,因為它會導致垃圾郵件。
代碼:
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
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);
?>
驗證輸入。
這可以通過多種方式完成。 其中之一可能是檢查$_FILES
全局變量是否包含file
密鑰,以及$_GET
包含license_id
、 username
和address
。
if (isset($_FILES['file'])) {
die('Request invalid');
}
附注。 通常,使用全局變量會帶來安全風險。 在不完全重構的情況下,您可以考慮添加自定義標頭(如X-Client: My Fancy CSharp Application
),並在 PHP 代碼中驗證它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.