PHP
PHP website starter
A PHP website starter project is avalable at https://github.com/adamschricker/PHP-website-starter. Example file structure and starter pages with starter CSS.
Some Helpful Information
-
Declare an array
Indexed Array $php_variable = array("value1", "value2", "value3"); Associated Array $php_variable = array("key1"=>"value1", "key2"=>"value2", "key3"=>"value1");
-
General use DB function for query, insert, update, create, delete, etc.
function talk_to_db($dbQuery) { //DB Variables $hostname = ''; $username = ''; $password = ''; $dbname = ''; $dbConnection = mysqli_connect( $hostname, $username, $password, $dbname ); if (!$dbConnection) { die('Could not connect: ' . mysqli_error()); } $queryResult = mysqli_query($dbConnection, $dbQuery); if (!$queryResult) { printf('Error: %s\n', mysqli_error($dbConnection)); exit(); } $resultArray = array(); while ($row = mysqli_fetch_array($queryResult)) { array_push($resultArray, $row); } mysqli_close($dbConnection); return $resultArray; }
-
Redirect to https
if(!isset($_SERVER["HTTPS"]) || $_SERVER["HTTPS"] != "on") { header("Location: https://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"], TRUE, 301); exit; }
-
Redirect to no www
if (substr($_SERVER['SERVER_NAME'], 0, 4) === 'www.') { header("Location: https://" . substr($_SERVER['SERVER_NAME'], 4) . $_SERVER["REQUEST_URI"], TRUE, 301); exit; }
-
Redirect when URL does not end in /
if (substr($_SERVER['REQUEST_URI'], -1) !== "/") { header("Location: " . $_SERVER['REQUEST_URI'] . "/", TRUE, 301); exit; }
-
Limit URL to alphanumeric, dash, and forward slash
if (preg_match('/[^a-z0-9\/\-]+/i', $_SERVER['REQUEST_URI'])) { http_response_code(404); // Change output to 404 page }
-
$_SERVER Information
Put this on a test webpage and see what $_SERVER can give you. Useful if you need URL, Server, Client, URL vars, etc.
foreach ($_SERVER as $key => $value) { echo "key='" . $key . "', value='" . $value . "'<br>"; }