PHP - What Are The Best Practices For Search?
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. 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? 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 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? 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> The result pages is supposed to have pagination like google help me please
I require a page to be added to my website. This page will facilitate a refined search via Google, Bing and Yahoo search engine simultaneously , show the top 5 of each engine. Is this possible using php ? Thank's Hello, Does anyone know a tutorial I can follow to create my own search engine over the items I have in my SQL database? I find a lot of tutorials but they are all 'one word searches' which means if you type two words you will get all results that contain either word (too many hits). If the search engine tutorial displays result with AJAX even better. Thanks for help. df Hello. I am working on a php script for searching a database table. I am really new to this, so I used the this tutorial http://www.phpfreaks.com/tutorial/simple-sql-search I managed to get all the things working the way I wanted, except one important and crucial thing. Let me explain. My table consist of three columns, like this: ID(bigint20) title(text) link (varchar255) ============================= ID1 title1 link-1 ID2 title2 link-2 etc... Like I said, I managed to make the script display results for a search query based on the title. Want I want it to do more, but I can't seem to find the right resource to learn how, is to place a "Download" button under each search result with its corresponding link from the table. Here is the code I used. <?php $dbHost = 'localhost'; // localhost will be used in most cases // set these to your mysql database username and password. $dbUser = 'user'; $dbPass = 'pass'; $dbDatabase = 'db'; // the database you put the table into. $con = mysql_connect($dbHost, $dbUser, $dbPass) or trigger_error("Failed to connect to MySQL Server. Error: " . mysql_error()); mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {$dbDatabase}. Error: " . mysql_error()); // Set up our error check and result check array $error = array(); $results = array(); // First check if a form was submitted. // Since this is a search we will use $_GET if (isset($_GET['search'])) { $searchTerms = trim($_GET['search']); $searchTerms = strip_tags($searchTerms); // remove any html/javascript. if (strlen($searchTerms) < 3) { $error[] = "Search terms must be longer than 3 characters."; }else { $searchTermDB = mysql_real_escape_string($searchTerms); // prevent sql injection. } // If there are no errors, lets get the search going. if (count($error) < 1) { $searchSQL = "SELECT title, link FROM db WHERE title LIKE '%{$searchTermDB}%'"; $searchResult = mysql_query($searchSQL) or trigger_error("There was an error.<br/>" . mysql_error() . "<br />SQL Was: {$searchSQL}"); if (mysql_num_rows($searchResult) < 1) { $error[] = "The search term provided {$searchTerms} yielded no results."; }else { $results = array(); // the result array $i = 1; while ($row = mysql_fetch_assoc($searchResult)) { $results[] = "{$row['title']}<br /> Download - this is the button I want to link to the title results - and maybe other links too - <br /> "; $i++; } } } } function removeEmpty($var) { return (!empty($var)); } ?> <?php echo (count($error) > 0)?"The following had errors:<br /><span id=\"error\">" . implode("<br />", $error) . "</span><br /><br />":""; ?> <form method="GET" action="search?" name="searchForm"> Search for title: <input type="text" name="search" value="<?php echo isset($searchTerms)?htmlspecialchars($searchTerms):''; ?>" /> <input type="submit" name="submit" value="Search" /> </form> <?php echo (count($results) > 0)?"Rezultate lucrari de licenta sau disertatie pentru {$searchTerms} :<br /><br />" . implode("", $results):""; ?> $results = array(); // the result array $i = 1; while ($row = mysql_fetch_assoc($searchResult)) { $results[] = "{$row['title']}<br /> Download - this is the button I want to link to the title results - and maybe other links too - <br /> "; $i++; I would like the results to be displayed like this Results for SearchItem: Result 1 Download | Other link Result 2 Download | Other link etc.... or something like this. So, how do I add the data from the link row into a text(Dowload), within an <a href> tag (well, at least I guess it would go this way) ? My first tries (fueled by my lack of knowledge) where things like $results[] = "{$row['title']}<br /> <a href="{$row['link']}">Download</a> <br /> "; but I keep getting lots of errors, and then I don't know much about arrays and stuff (except basic notions); So there it is. I am really stuck and can't seem to find any workaround for this. Any suggestions? (examples, documentation, anything would do, really) Thanks, Radu I am developing a intranet forum in Php and MySQL and I am using ajax to display searched results on the same page but right now I am using query LIKE text% to search in database which is slower. but I want to make it fast search engin which can parse *,+ and show result. Since I am using ajax i am not able to use free search engin,so if possible pls provide a complete solution Hi all How do I modify the below code to search multiple tables in mySQL database? $query = "select * from store_items where description like \"%$trimmed%\" or title like \"%$trimmed%\" or dimensions like \"%$trimmed%\" order by id ASC"; $numresults=mysql_query($query); $numrows=mysql_num_rows($numresults); It is for a search function and I need it to search another table called 'about_text' and 'faq_text' Thanks Pete Hello, I'm developing a website that asks the user to submit a keyword for a search. The results should display matches for this keyword, but also show matches for related keywords (in order of relevenace!). I'm planning on building up a library of which search terms users use in the same sessions (e.g. if someone searches for "it jobs" and "php jobs", I'll know the terms are correlated), and I'll also measure the click-through rates of the items on the results list. I've been spending all weekend trying to map out the design for this but it's proving incredibly complicated and I think the solution is likely to be on the internet somewhere already?! Please could someone point me in the right direction if you've come accross this problem before? Thanks a million, Stu Friends, I want to extract the Search Keyword from the URL, a visitor came from. I am using a PHP CMS and want to show the Keyword on my Blog. So if they search "abcd" from google, i want to extract "abcd" and echo on my blog. Here is the coding i could got hold of, but its not working, not echoing anything <?php function pk_stt2_function_get_delimiter($ref) { $search_engines = array('google.com' => 'q', 'go.google.com' => 'q', 'images.google.com' => 'q', 'video.google.com' => 'q', 'news.google.com' => 'q', 'blogsearch.google.com' => 'q', 'maps.google.com' => 'q', 'local.google.com' => 'q', 'search.yahoo.com' => 'p', 'search.msn.com' => 'q', 'bing.com' => 'q', 'msxml.excite.com' => 'qkw', 'search.lycos.com' => 'query', 'alltheweb.com' => 'q', 'search.aol.com' => 'query', 'search.iwon.com' => 'searchfor', 'ask.com' => 'q', 'ask.co.uk' => 'ask', 'search.cometsystems.com' => 'qry', 'hotbot.com' => 'query', 'overture.com' => 'Keywords', 'metacrawler.com' => 'qkw', 'search.netscape.com' => 'query', 'looksmart.com' => 'key', 'dpxml.webcrawler.com' => 'qkw', 'search.earthlink.net' => 'q', 'search.viewpoint.com' => 'k', 'mamma.com' => 'query'); $delim = false; if (isset($search_engines[$ref])) { $delim = $search_engines[$ref]; } else { if (strpos('ref:'.$ref,'google')) $delim = "q"; elseif (strpos('ref:'.$ref,'search.atomz.')) $delim = "sp-q"; elseif (strpos('ref:'.$ref,'search.msn.')) $delim = "q"; elseif (strpos('ref:'.$ref,'search.yahoo.')) $delim = "p"; elseif (preg_match('/home\.bellsouth\.net\/s\/s\.dll/i', $ref)) $delim = "bellsouth"; } return $delim; } /** * retrieve the search terms from search engine query * */ function pk_stt2_function_get_terms($d) { $terms = null; $query_array = array(); $query_terms = null; $query = explode($d.'=', $_SERVER['HTTP_REFERER']); $query = explode('&', $query[1]); $query = urldecode($query[0]); $query = str_replace("'", '', $query); $query = str_replace('"', '', $query); $query_array = preg_split('/[\s,\+\.]+/',$query); $query_terms = implode(' ', $query_array); $terms = htmlspecialchars(urldecode(trim($query_terms))); return $terms; } /** * get the referer * */ function pk_stt2_function_get_referer() { if (!isset($_SERVER['HTTP_REFERER']) || ($_SERVER['HTTP_REFERER'] == '')) return false; $referer_info = parse_url($_SERVER['HTTP_REFERER']); $referer = $referer_info['host']; if(substr($referer, 0, 4) == 'www.') $referer = substr($referer, 4); return $referer; } $referer = pk_stt2_function_get_referer(); if (!$referer) return false; $delimiter = pk_stt2_function_get_delimiter($referer); if( $delimiter ){ $term = pk_stt2_function_get_terms($delimiter); } echo $term; ?> May someone help? Natasha T I have code to search a database of members, I can search by lastname but having a little problem. I want to be able to search by lastname starting with the first letter. (ie: a or b or c or d and so on). As it is right now I can only search by first letter of last name if I add % to the search (ie: a% b% c%) will give me all members with the last names starting with the approiate letter designation. I'm not sure how to handle this, any help would be appreciated. Thanks. Code: [Select] <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> </head> <body> <center><table cellspacing="10" cellpadding="10" width="750" border="0"> <h4>Search</h4> <form name="search" method="post" action="<?php $PHP_SELF?>"> Seach for: <input type="text" name="find" /> in <Select NAME="field"> <Option VALUE="lname">Last Name</option> <input type="hidden" name="searching" value="yes" /> <input type="submit" name="search" value="Search" /> </form> <?php // check to see if anything is posted if (isset($_POST['find'])) {$find = $_POST['find'];} if (isset($_POST['searching'])) {$searching = $_POST['searching'];} if (isset($_POST['field'])) {$field = $_POST['field'];} //This is only displayed if they have submitted the form if (isset($searching) && $searching=="yes") { echo "<h4>Results</h4><p>"; // If they did not enter a search term we give them an error if (empty($find)) { echo "<p>You forgot to enter a search term"; exit; } // Otherwise we connect to our Database mysql_connect("localhost", "root", "1910") or die(mysql_error()); mysql_select_db("cmc_member") or die(mysql_error()); // We preform a bit of filtering $find = strtoupper($find); $find = strip_tags($find); $find = trim ($find); // Now we search for our search term, in the field the user specified $results = mysql_query("SELECT * FROM members WHERE upper($field) LIKE'$find'"); // And we display the results if($results && mysql_num_rows($results) > 0) { $i = 0; $max_columns = 3; while($row = mysql_fetch_array($results)) { // make the variables easy to deal with extract($row); // open row if counter is zero if($i == 0) echo "<tr>"; // make sure we have a valid product ALIGN='CENTER' if($fname != "" && $fname != null) echo "<td ALIGN='CENTER'><FONT COLOR='red'><b>$fname $lname</b></FONT><br> $address <br> $city $state $zip <br>$phone<br><a href=\"mailto: $email\">$email</a><br></td>"; // increment counter - if counter = max columns, reset counter and close row if(++$i == $max_columns) { echo "</tr>"; $i=0; } // end if } // end while } // end if results // clean up table - makes your code valid! if($i < $max_columns) { for($j=$i; $j<$max_columns;$j++) echo "<td> </td>"; } //This counts the number or results - and if there wasn't any it gives them a little message explaining that $anymatches = mysql_num_rows($results); if ($anymatches == 0) { echo "Sorry, but we can not find an entry to match your query<br><br>"; } //And we remind them what they searched for echo "<b>Searched For:</b> " .$find; } ?> </tr> </table></center> </body> </html> Hello All, Need some help I have 2 tables in a database and I need to search the first table and use the results from that search, to search another table, can this be done? and if it can how would you recommend that I go about it? Thanks For Your Help Guys! |