|
This is a collection of
different scripts that show ways to improve PHP interaction security and
protect against SQL injection
<?php
//This section allows or disallows remote access to the script based on the
calling web browser's CORS settings
//Comment the next line if scripts are on same server as converted
spreadsheet, un-comment to allow remote access
//header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Cache-Control: no-cache, must-revalidate");
//The next section will exit the script immediately if called from outside
the current domain, limiting remote access
//Uncomment next 2 lines if scripts are on same server as converted
spreadsheet, comment to test from remote location
$domain = 'yourdomain.com';
$pos = strpos($_SERVER['HTTP_REFERER'], $domain); if (($pos === false) or
($pos == '')) {die("Have a nice day!");}
?>
The section above is included in every file in previous demonstrations but
typically this code would go into a separate
file (settings.php for example) in a directory above your server's public
html directory to improve script protection and
reduce future maintenance, using the syntax below, which means go up two
directory levels from the current directory,
include the code found in the settings.php file. Good place to store
database connection and authentication settings.
<?php
require '../../settings.php';
?>
<?php
//This script shows a few different methods that help to reduce the risk of
SQL injection or other query tampering
header("Content-Type: application/json; charset=UTF-8");
header("Cache-Control: no-cache, must-revalidate");
$domain = 'yourdomain.com';
$pos = strpos($_SERVER['HTTP_REFERER'], $domain); if (($pos === false) or
($pos == '')) {die("Have a nice day!");}
$host = '127.0.0.1';
$db = 'CUSTOMERSdb';
$user = 'CUSTOMERSdbUSER01';
$pass = 'CUSTOMERSdbUSER01password';
$charset = 'UTF8';
$options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES =>
FALSE];
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$pdo = new PDO($dsn, $user, $pass, $options);
//The next line will truncate string input up to where it finds # or &
characters, remove all \ characters, and remove leading or trailing
spaces
$searchterm =
htmlspecialchars(stripslashes(trim($_GET["searchterm"])));
//The next 3 lines define the allowed sort parameters
$whitelist =
["Company","Address","City","County","ZIP","Phone1"];
$selection = array_search($_GET['orderby'], $whitelist);
$orderby = $whitelist[$selection];
//The next line uses the ternary operator to set the variable $direction.
If the URL parameter for 'direction' is not 'DESC', it defaults to
'ASC'.
$direction = $_GET['direction'] == 'DESC' ? 'DESC' : 'ASC';
//The next line hardcodes the maximum number of rows returned
$limit = 10;
//The next line sets the starting record in the found set, making it
possible to page through records
$offset = $_GET["offset"];
//The next 5 lines execute the query using a PDO prepared statement and
typed variables
$stmt = $pdo->prepare("SELECT Company, Address, City, County, ZIP,
Phone1 FROM customers WHERE Company LIKE :searchterm ORDER BY
".$orderby." ".$direction." LIMIT :limit OFFSET
:offset");
$stmt->bindValue(':searchterm', "$searchterm%");
$stmt->bindValue(':limit', (int) $limit, PDO::PARAM_INT);
$stmt->bindValue(':offset', (int) $offset, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetchAll();
$json = json_encode($data);
echo $json;
?>
<?php
//The next 4 scripts work together to encrypt and decrypt data and also
show a way to increase script protection
//This script sends input variables to the encryption script stored in a
password-protected directory on the server
header("Access-Control-Allow-Origin: *");
header("Content-Type: text/html; charset=UTF-8");
header("Cache-Control: no-cache, must-revalidate");
$message = $_GET["message"];
$reference = $_GET["reference"];
$url =
'https://yourdomain.com/yoursecurefolder/aes256gcmEncryptor.php';
$username = 'yoursecurefolderusername';
$password = 'yoursecurefolderusernamepassword';
$headers = array(
'Content-Type:
multipart/form-data',
'Authorization: Basic '.
base64_encode("$username:$password")
);
$postRequest = array(
'message' => $message,
'reference' =>
$reference
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postRequest);
$response = curl_exec($ch);
if(curl_errno($ch)){
throw new
Exception(curl_error($ch));
}
echo $response;
curl_close($ch);
?>
<?php
//this is the aes256gcmEncryptor.php, called from the script above, which
is stored in yoursecurefolder
header("Content-Type: text/html; charset=UTF-8");
header("Cache-Control: no-cache, must-revalidate");
if (! sodium_crypto_aead_aes256gcm_is_available()) {throw new
\Exception("AES-GCM is not supported on this platform");}
$message = $_POST["message"];
$reference = $_POST["reference"];
$encryptionkey = random_bytes(SODIUM_CRYPTO_AEAD_AES256GCM_KEYBYTES);
$nonce = random_bytes(SODIUM_CRYPTO_AEAD_AES256GCM_NPUBBYTES);
$encryptedtext = sodium_crypto_aead_aes256gcm_encrypt($message,$reference,$nonce,$encryptionkey);
echo
"<br>EncryptedText<br>".sodium_bin2hex($encryptedtext)."<br>";
echo "<br>EncryptionKey<br>".sodium_bin2hex($encryptionkey)."<br>";
echo
"<br>Nonce<br>".sodium_bin2hex($nonce)."<br>";
echo
"<br>Reference<br>".$reference."<br>";
?>
<?php
//This script sends input variables to the decryption script stored in a
password-protected directory on the server
header("Access-Control-Allow-Origin: *");
header("Content-Type: text/html; charset=UTF-8");
header("Cache-Control: no-cache, must-revalidate");
$encryptedtext = $_GET["encryptedtext"];
$encryptionkey = $_GET["encryptionkey"];
$nonce = $_GET["nonce"];
$reference = $_GET["reference"];
$url =
'https://yourdomain.com/yoursecurefolder/aes256gcmDecryptor.php';
$username = 'yoursecurefolderusername';
$password = 'yoursecurefolderusernamepassword';
$headers = array(
'Content-Type:
multipart/form-data',
'Authorization: Basic '.
base64_encode("$username:$password")
);
$postRequest = array(
'encryptedtext' =>
$encryptedtext,
'encryptionkey' => $encryptionkey,
'nonce' => $nonce,
'reference' =>
$reference
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postRequest);
$response = curl_exec($ch);
if(curl_errno($ch)){
throw new
Exception(curl_error($ch));
}
echo $response;
curl_close($ch);
?>
<?php
//this is aes256gcmDecryptor.php, called from the script above, which is
also stored in yoursecurefolder
header("Content-Type: text/html; charset=UTF-8");
header("Cache-Control: no-cache, must-revalidate");
$reference = $_POST["reference"];
$encryptedtext = sodium_hex2bin($_POST["encryptedtext"]);
$nonce = sodium_hex2bin($_POST["nonce"]);
$encryptionkey = sodium_hex2bin($_POST["encryptionkey"]);
$decrypted = sodium_crypto_aead_aes256gcm_decrypt($encryptedtext,$reference,$nonce,$encryptionkey);
echo $decrypted;
?>
|