PHP - Php Best Practices?
Similar TutorialsHi, I am developing a large management/CRM system for my company. I would like to hear your thoughts on what is the best way to organise functions and files. I know of a few ways: 1. having all your PHP at the start of each page which fetches all the data from the DB and then echo it out into the right places in that page, e.g. fetching a list of options then later echoing out the option data into a 'select' tag, creating a dynamic list. 2. Have the majority of the PHP completely seperate from the page in a seperate page, and you INCLUDE that at the start of your html page. 3. Have many seperate PHP files that do different bits for that page, e.g. one php file is for fetching a list of sales contacts, another for fetching enquiries numbers etc and have it all injecting into the correct containers on your page using Jquery and AJAX, which lets you have dynamic updates if you stick them in a setInterval loop. 4. This is the one I most fancy. You have one PHP file that has several 'modes'. Now when you call it in an AJAX statement, you pass a mode variable to it which is the condition for one of the IFs in your PHP files. So if I wanted to fetch an up to date contact list every x seconds, I would also pass a variable like 'FETCH_CONTACTS' i.e.: $.post('record-control.php', {targetCustomer:thidId, mode:'FETCH_CONTACTS'}, function(data){$('#targetDiv').html(data)}) ; Which way would you prefer if it was you? I had general question about security in php. Suppose i have a value submitted from a form called $form that would go to the database. What functions would good to clean it before it goes to the database. Suppose I want to display the $form variable in the browser, what would i use to display to prevent javascript or html injection other than strip_tags. On another note, what security practice should i follow when dealing with sessions? Hi guys, I am using Domdocument for parsing xml, i am concerned about the impact of the performance on using this Domdocument. what are the best practices to reduce the impact performance using Domdocument ? Please share your ideas. Thanks I want to add a search feature to my site so that users can search for videos. Let's say that a user conducts a search and I GET their search query: $squery = isset($_GET['query']) ? $_GET['query'] : '';Now what should I do? What are the best practices to ensure the security of my database and to provide the most relevant results to the user? Here's what I've got so far. // Make sure a search query was entered. if($squery == '') { echo "<p>You didn't enter a search query.</p>"; } // Strip HTML tags. $squery = strip_tags($squery); // Trim white space. $squery = trim($squery); // Set minimum query length. $min_length = 3; // Make sure query length is more than minimum. if(strlen($squery) < $min_length) { echo "<p>The search query you entered is too short. The minimum number of characters is ".$min_length.".</p>"; } // Connect to MySQL. // Select database. // Escape search query. $squery = mysql_real_escape_string($squery); // Break query into keywords. $keywords = explode(' ', $squery); // Count number of keywords. $no_of_keywords = count($keywords); // If just one keyword, then build statement. if($no_of_keywords == 1) { $sql = "SELECT whatever FROM `video_table` WHERE (col1 LIKE '%.$squery.%' OR col2 LIKE '%.$squery.%')"; } // If multiple keywords, then build statement. else { $sql = "SELECT whatever FROM `video_table` WHERE "; for($i = 0; $i < $no_of_keywords; $i++) { $sql .= "(col1 LIKE '%.$keywords[$i].%' OR col2 LIKE '%.$keywords[$i].%')"; if($i < $no_of_keywords) { $sql .= " OR "; } } } // Run mysql query. $raw_results = mysql_query($sql, $con); // Put results into an array for later use. $results = mysql_fetch_array($raw_results);Can this code's security be improved? How can it be altered to provide more relevant results? Should I omit words such as "to" and "the" from the query? If so, how do I do it? Should I remove punctuation? As always, I appreciate your help. You guys have taught me LOADS! Edited by Fluoresce, 06 November 2014 - 05:21 PM. I'm developing a REST API for a website. As far as I know, the rules for RESTfulness are sort of broad. I'm just wondering if there are any good resources with tighter guidelines to developing a good, useable API. What are the common practices etc. Some of the things I'm unclear on a Should it use GET and POST, or just one of them? From what I've read about HTTP, GET is a "safe method" and shouldn't allow data to be changed on the server. Should we use GET to retrieve data off the server, and POST to save data to the server? Or is it common practice to use POST for getting and storing data? Should we utilize the HTTP status codes? Should the HTTP status change when things go wrong? Should it be 400 if something doesn't work properly? Or 404 if the method doesn't exist? If the request is successful, and there's no data to return, should it be 204 No Data or 200 with JSON/XML that shows it was successful? To execute code on successfully submitting text input, is this "bare minimum" code secure enough?
if(!empty($_POST["textfield_input"])) { ...or is it best to make sure all 4 of these are confirmed:
if (
The html portion is simply: I've searched on the net about this several times, and see different answers, and it looks like each PHP expert has their favorite.... but I would rather know the "best practices" answer to this. Thank you!!
Edited November 5, 2019 by StevenOliver This topic has been moved to Miscellaneous. http://www.phpfreaks.com/forums/index.php?topic=351660.0 Scenario: My page generates several PHP variables. Some of those variables get posted to another page. Question: If a variable is to be assigned to a Session, is there any reason to assign this value to a regular PHP variable? Example: When an API generates a "shipping label tracking number, which is better, "A" or "B" or subtle variation "C":
A.) ... and then use $_SESSION["trackingNumber"] throughout the rest of my script (like this: echo "Hello, here's your tracking number: ".$_SESSION["trackingNumber"]).
B.) ... and then use "$trackingNumber" throughout the rest of my script (like this: echo "Hello, here's your tracking number: ".$trackingNumber).
C.) ... and then use "$trackingNumber" throughout the rest of my script (like this: echo "Hello, here's your tracking number: ".$trackingNumber). Thank you! I've always wondered about this. Which is best?
Hello all. I'm looking to build a website in php that will be large in scope and I'm looking for some direction as to how to go about coding it. What I'm referring to exactly is the programming model. I'm new to the language, but not to programming, and I've read up on it and familiarized myself with the syntax over the past few days. Normally when I go about building a project I like to plan ahead how I'm going to build It so I don't run into tedious issues later on and this is what I need help with.
My concerns:
I am looking to use the alternative syntax for control structures as to make the php code inside my html readable and easier to manage but in terms of OOP when is it best for me to use classes vs functions?
I am leaning towards using both classes and functions. Classes to handle polling data, sanitizing it and storing it while the functions will be used , with the alternative syntax, to display the data.
How should I go about properly setting my project assuming I will have many concurrent users using the website at once?
Is using xml / INI files as a directory to look up information a good practice? Is it better to declare constant variables instead?
When working with multiple includes is there an easier way to include a file than having to explicity write "dirname( dirname(__FILE__) )" everytime?
I'm essentially looking for guidance / tips as to good programming practices with this language Advanced practices are welcomed as well.
Development Tools:
XAMPP ( Windows 7 Pro )
PHPStorm
Current directory structure plan:
Here is what I currently have:
The API class is a collection of functions that returns an object to be used at a later data.
<?php /* * Development API Key * @since 1.0 * * Rate Limit(s): * 10 request(s) every 10 second(s) * 500 request(s) every 10 minute(s) */ define( "__API_KEY__" , "---------------------------------" ); require_once dirname( dirname(__FILE__) ) . "\\settings.php"; class API { // If successfull it returns an object from the url that's passed to this function. private function api_call($url) { $result = null; // end result // Create a new curl handle. $ch = curl_init(); curl_setopt($ch , CURLOPT_URL, "https://" . $url . "?api_key=" . __RIOT_API_KEY__); // set the URL curl_setopt($ch , CURLOPT_RETURNTRANSFER , true ); // return the transfer as a string of the return value curl_setopt($ch , CURLOPT_SSL_VERIFYPEER , false ); // turn off ssl certificate verification // Execute the api call $response = curl_exec($ch); // Get info to analyze the result $ci = curl_getinfo($ch); $httpcode = $ci["http_code"]; // If a curl error occured if(curl_errno($ch) || ($httpcode != "200")) { $die = "Curl Error Code: " . $httpcode . "<br/>"; $die .= "Curl Error Message: " . curl_errno($ch) . "<br/>"; $die .= "Curl URL: " . $ci["url"] . "<br/>"; die($die); } else { // Check if the api call we made was valid $response = json_decode($response, true); // If our response is an array check if it's an error response if(is_array($response)) { $error_key = "status"; if(array_key_exists($error_key, $response)) { $er = $response[$error_key]; $die = "API Error Message: " . $er["message"] . "<br/>"; $die .= "API Error Code: " . $er["status_code"] . "<br/>"; die($die); } } // Our response is a valid object $result = $response; } private function sanitize_url($url) { // removes all whitespaces return trim(preg_replace( '/\s+/','',$url)); } private function regional_endpoints() { static $regionini; if(is_null($regionini)) $regionini = parse_ini_file(INI_REGIONAL_ENDPOINTS, true); return $regionini; } private function region_host($shortcode) { /* * regionalendpoints.ini * @since 1.0 * * [SHORTCODE] * Description=<region_description> * Host=<host_url> */ return $this->regional_endpoints()[strtoupper($shortcode)]["Host"]; } public function region_description($shortcode) { /* * regionalendpoints.ini * @since 1.0 * * [SHORTCODE] * Description=<region_description> * Host=<host_url> */ return $this->regional_endpoints()[strtoupper($shortcode)]["Description"]; } public function api_object_by_name($name, $region) { /* * @Description: Get summoner objects mapped by standardized summoner name for a given list of summoner names. * * * @Returns: Map[string, SummonerDto] * * Object * ------------------------------------------------------------------------------------------------------ * Name Data Type Description * ------------------------------------------------------------------------------------------------------ * id long ID. * name string Name. * profileIconId int ID of the summoner icon associated with the summoner. * revisionDate long Date summoner was last modified specified as epoch milliseconds. * Level long Level associated with the summoner. */ $api_url = "%s/api/col/%s/v1.4/obj/by-name/%s"; return $this->api_call(sprintf($api_url, $this->region_host($region), strtolower($region), $this->sanitize_url($name))); } }Class that acts as the middle man between the api and the front end. Currently how it is set up it handles an internal queue. <?php include dirname(__FILE__) . "\\class-riotapi.php"; define( "SUMMONER_NAME" , 0 ); define( "SUMMONER_ID" , 1 ); class Summoner { private $riotapi = null; private $summoner = null; private $arr_summoners = null; private $region = null; public function __construct() { // Create our riot api object $this->riotapi = new RiotAPI(); } public function summoner_exists($summoners, $region, $type = SUMMONER_NAME) { static $eoa; // end of array // If our array of summoners is empty or we have reached the end of the array. if( empty($this->arr_summoners) || $eoa ) { // Get an array of summoner information from the riot api based on the type of information // supplied. switch($type) { case SUMMONER_NAME : $this->arr_summoners = $this->riotapi->api_summoner_by_name($summoners, $this->region = $region); break; case SUMMONER_ID : $this->arr_summoners = $this->riotapi->api_summoner_by_id($summoners, $this->region = $region); break; } // If our array of summoners isn't empty. if( !empty($this->arr_summoners) ) { // Set our current summoner the first element in the array. $this->summoner = reset($this->arr_summoners); } else { // We failed to acquire any summoner information so return false. return false; } $eoa = false; } else { // If we have not reached the end of the summoners array set our current // summoner to the next element. $next = next($this->arr_summoners); // Have we reached the end of the array? if( $next ) { // No. Set our current summoner to the next element. $this->summoner = $next; } else { // Yes. Set our end of array variable to true. $eoa = true; // End the loop return false; } } return true; } public function summoner_id() { return $this->summoner["id"]; } public function summoner_name() { return $this->summoner["name"]; } public function summoner_profile_icon_id() { return $this->summoner["profileIconId"]; } public function summoner_last_updated() { return $this->summoner["revisionDate"]; } public function summoner_level() { return $this->summoner["summonerLevel"]; } public function summoner_mastery_pages() { return $this->riotapi->api_summoner_masteries($this->summoner_id(), $this->region)[$this->summoner_id()]["pages"]; } }Functions.php file that is a collection of functions that echo out information. <?php require_once "settings.php"; include DIR_INCLUDE . "class-summoner.php"; function summoner_exists($summoners, $region = "NA", $type = SUMMONER_NAME) { global $cs; if(!isset($cs)){ $cs = new Summoner(); } return $cs->summoner_exists($summoners, $region, $type); } function summoner_name() { global $cs; if(isset($cs)){ echo $cs->summoner_name(); } } ?>index.php - Example of how I'm currently using the functions.php file. <?php include "functions.php"; ?> <html xmlns="http://www.w3.org/1999/xhtml"> <body> <?php while(summoner_exists("cyllo")) : ?> <div>Summoner Name: <?php summoner_name(); ?></div> <div>Summoner ID: <?php summoner_id(); ?></div> <div>Summoner Profile icon ID: <?php summoner_profile_icon_id(); ?></div> <div>Last Updated: <?php summoner_last_updated(); ?></div> <div>Summoner Level: <?php summoner_level(); ?></div> <div> <?php mastery_pages(); ?> </div> <?php endwhile; ?> </body> </html> |