PHP - Is This Bad Practice?
mysql_query("INSERT INTO people (company, lname) VALUES ('clean($_POST[Company])', 'clean($_POST['lname'])' ");
using a clean function in the query instead of doing it before hand? Similar TutorialsHi. I've been learning OOP and watched a video on YouTube about a "secure" OOP PHP login script. It was pretty good, and helped me to understand some OOP approaches, but I couldn't help thinking some of it was wrong. I'm not sure so feedback appreciated! The class starts of something like this: Code: [Select] <?php class Login { private $_id; private $_username; private $_password; private $_passmd5; private $_errors; private $_access; private $_login; private $_token; public function __construct() { $this->_errors = array(); $this->_login = isset($_POST['login'])? 1 : 0; $this->_access = 0; $this->_token = $_POST['token']; $this->_id = 0; $this->_username = ($this->_login)? $this->filter($_POST['username']) : $_SESSION['username']; $this->_password = ($this->_login)? $this->filter($_POST['password']) : ''; $this->_passmd5 = ($this->_login)? md5($this->_password) : $_SESSION['password']; } Isn't "hard" setting variables, like the POST vars in the contruct bad? Shouldn't they be passed through elsewhere? I've learnt that OOP needs to be reusable and manageable as it's primarily the point of using OOP in the first place. I might be wrong but I noticed straight away that the above class doesn't seem reusable (in the true sense). Hopefully i'm getting the hang of it... Thanks Hi,
I study a php book and every thing is going fine, the problem is that I dont know how to practice what I study...
iv'e searched alot in the internet of exercise and found few but not every thing there is the same as what I study and sometimes they ask me to do things that I dont know yet..
some people saying that you need to think about a project and start building it but I dont have enough knowledge so start build something on my own..
right now I know about if/else, loops, operators, functions and objects, arrays, date and time, and file handling.
so most of the exercise I find involving mysql that I dont know yet.
can someone give me tips maybe how he started to study php?
it will help me alot and im sure it will help to more people.
thakns in advance,
guy.
Until participating and reading this topic, I had though the following code was perfectly fine. I don't claim to even be good at OOP or application design, although I would like to be lol Anyway, the only functionality regarding google maps polylines I could think of in PHP, was encoding and decoding them, so I placed them in a static class: <?php /* -- Polyline.class.php @return string (encoded lat/lng) - polyline::getEncoded(-2.5675, 2.5456); @return string (encoded lat/lng's) - polyline::getEncoded(array(-2.5675, 2.5456), array(-2.5675, 2.5456)); @return string (encoded lat/lng's) - polyline::getEncoded(-2.5675, 2.5456, -2.5675, 2.5456); @return array (decoded array(lat, lng)'s) - polyline::getDecoded('zmtn_?_epn_?zmtn_?_epn_?zmtn_?_epn_?'); */ class Polyline { private static $_calls = 0; private static $_lastLat = 0; private static $_lastLon = 0; // public accessors public static function get_encoded() { // $encoded to store encoded points $encoded = ''; $args = func_get_args(); if ( is_array($args[0]) ) { while ( list($k, $arg) = each($args) ) $encoded .= self::_encode($arg[0]) . self::_encode($arg[1]); } else { $cnt = count($args); if ( !$cnt ) return false; $i = 0; while ( $i < $cnt ) $encoded .= self::_encode($args[$i++]); } self::$_calls = 0; self::$_lastLat = 0; self::$_lastLon = 0; return $encoded; } public static function get_decoded($str) { $points = array(); $lat = 0; $lon = 0; while (strlen($str)) { $lat += self::_decode($str); $lon += self::_decode($str); $points[] = array($lat * 1e-5, $lon * 1e-5); } return $points; } // private private static function _encode($dec) { $dec = round($dec * 1e5, 0); if ( !(self::$_calls % 2) ) { //lon if ( self::$_calls >= 2 ) $ndec = $dec - self::$_lastLon; self::$_lastLon = $dec; } else { //lat if ( self::$_calls >= 2 ) $ndec = $dec - self::$_lastLat; self::$_lastLat = $dec; } $dec = isset($ndec) ? $ndec : $dec; $is_neg = stristr($dec, '-'); $dec <<= 1; // invert bits if negative if ( $is_neg ) $dec = (~$dec); //0 pad to 32 bits $dec = str_pad(sprintf('%b', $dec), 30, '0', STR_PAD_LEFT); // chunk into 5 char strings and reverse $dec = array_reverse(str_split($dec, 5)); // or with 0x20 except last one ( add 63 to each and convert to ascii ) $c = count($dec); for ( $i = 0; $i < $c; ++$i ) $dec[$i] = (isset($dec[$i+1]) && $dec[$i+1] & 31) ? ((bindec($dec[$i]) | 32) + 63) : (((bindec($dec[$i])) > 0) ? bindec($dec[$i]) + 63 : ''); // set times called self::$_calls++; return vsprintf('%c%c%c%c%c%c', $dec); } private static function _decode(&$str) { $shift = 0; $result = 0; $i = 0; do { // while ascii($str[$i++]) > ascii([space] " ") $b = ord($str[$i++]) - 63; $result |= ($b & 0x1f) << $shift; $shift += 5; } while ($b >= 0x20); $str = substr($str, $i); return (($result & 1) ? ~($result >> 1) : ($result >> 1)); } private function __construct() {} private function __clone() {} } ?> not that it matters much, since the rest of the application in which this class resides went to design shit, but; is this bad practice in your opinion? Hi, (Apologies in advance if this is a total newbie question - if it is, just give me some idea on what I need to search for!) I have written php code that essentially pulls together multiple records (using mySQL) and displays them in a webpage. The challenge I have now is making the output pretty. What is the best way to do this? I have my css file (with several styles in the format below): Code: [Select] .textstyle0 {font-family:Tahoma;font-weight:normal;font-style:normal;font-size:48px;text-decoration:none;color:#ffffff;} div.Object50 { position:absolute; padding-right:5px; top:189px; left:92px; z-index:0; text-align:left; width:437px; } And my html file (that I want to bring in the php output): Code: [Select] <div class="Object50"><span class="textstyle0">Q. THIS IS A TEST?<br></span></div> My php code is sitting in a tidy block: Code: [Select] $result = mysql_query("SELECT * FROM tbl_scores WHERE ID=$f_id") or die(mysql_error()); $row = mysql_fetch_array( $result ); $f_score = $row['score']; $f_freq = $row['freq']; echo "test" . $f_score; Do I need to update all my php code with the relevant css tags or can I reference the php? Or do I split up my php code? Do I leave my php code at the top and store all the values somewhere? Then these get pulled into html? I guess I am trying to reduce how much of the php coding I need to modify while leaving the flexibility in the design.... Hi Guys, I have a query regarding best practice for performance on a web application I'm developing. I am retrieving data via an API that I then need to display on a website. The data retrieved all relates to a product ID. The issue I am having is that each product has a UniqueID, but also a GroupID. The GroupID is used to display the same products but of different colour/size combinations. ie. UniqueID GroupID Size Colour 1 1 n/a n/a 2 2 Small Red 3 2 Medium Blue 4 2 Large Green I need to display the products in a list, but where there are multiple products in a group, I need to provide a dropdown selector for size and a dropdown selector for colour. I'm struggling a bit with how to structure it with just the array spat out by the API, so I was considering saving the data to a MySQL database and then querying that to get what I need. Is this a good way to go or is the double query hit going to be horribly inefficient? Cheers! Hey everyone,
I am working on a project for fun. This is a LAMP application that is going to run on my intranet server, and hold NO VALUABLE data. I am doing it just to get better at programming, and learn some best practices and techniques. at this point, I am working on some things, and I don't know what the best practices are. Can someone help me go down the pest route?
1. A log-in system and I want to include a "remember me" button. What is the best practice for this? Obviously leaving user data in a cookie is asking for trouble, so I was thinking of leaving a unique id of some sort? 2. Information in a login SESSION. What information do you put in a log in session? I have seen lots of different techniques on this. I don't really know which is the best. For the moment, I keep an array like this: array('Status'=>True, 'Username'=>'Users name" ,'email'=>'users Email'). If a hacker can inject session information, this seems like it would be really easy to break, because they only need a user's name and email to gain access. Is there something more I should do? 3. Config file that holds Mysql Information. I made a file that contains all the values that might change over time. That way I only need to change it in one spot. In this file I have things like the Mysql Database information. Should these files be encrypted? Or can I use a .htaccess file to make sure it isn't accessible to a hacker (as I mentioned before, this isn't a project that's going live, its more of an exercise to help me learn)
Thanks everyone 2 PART QUESTION (so I don't have to ask two questions 😀 )
1.)
2.) On my particular coding, I can use either the NULL/isset style, or, the ""/== style, with no errors or ill effects.... but something tells me the expert PHP coders prefer one over the other... Thank you!! Edited July 10 by ChenXiuHi guys, so I tried searching this, but I had some issues being able to find the proper wording and keywords to query. Everything I searched PHP, HTML, Coding Standard, Coding Style, Coding, Style, Standard, etc. I got varying results. With that being said, if anyone knows of a topic that already addresses this, please feel free to link it and I will gladly do the footwork.
^ TL;DR --> I searched, but couldn't find a topic for this...
Alright, now down to the brass tacks... I am having some trouble building a function in PHP that will display the header. I believe (if I am not mistaken) that I have seen people warning against peppering PHP code with echo <HTML HERE> throughout your code. I can sort of understand why, but I admit I am not completely sure why this is. I am trying to figure out a way to display HTML without doing the following...
<?php // -------------------------------------------------------------------------- // ADMIN BAR HANDLER // -------------------------------------------------------------------------- /** * First we need to determine if the user * is logged in or not. After determining * the user's logged in status, we will then * choose to display the admin bar or * redirect the user to the login page. */ function admin_bar() { if ( defined( USER_IS_LOGGED_IN ) ) { echo "<div class='admin_bar'> Admin Bar Here </div>"; } else if ( defined( USER_IS_NOT_LOGGED_IN ) ) { header( "Location: " . LOGIN_PAGE ) ; } } ?> I don't really have an issue with my script... I simply want to know if it is a bad practice to create a script that recurses through your root directory and zips up everything into one large zip file... I am creating a backup deal for my site and my site is rather large... Is this considered bad practice? Hi
I have a self calling script which does the following:
Stage 1: First run, it detects that $_POST is empty, and so displays a chunk of html which prompts for a password.
Stage 2: When resubmitted, it detects $_POST and displays another chunk of html which prompts the user for some values
Stage 3; When resubmitted the second time, $_POST is detected, along with the user values and some php is executed and a menu displayed.
So, question is this, what is the best method to output the html at stage 1 and stage 2?
I have tried using echo statements and wrapping each chunk in a function = messy.
I have tried using HEREDOCS (<<<VARNAME), better but ties my HTML to my script which is a pain
I am thinking to use file_get_contents("../html/chunk1.htm") this seems quite elegant and allows me to get someone else on our team to design the HTML keeping it out of my script
Thoughts and suggestions?
Thanks as ever
p.s. who pays for this site, are donation accepted?
Hello. I'm working on a website with an editor that allows image uploading. Ideally I want to be able to develop a framework for this and use it in later projects. What I have in mind is this: Database has an images table Entries contain these fields: id, filename, and a short description Images are referred to by their ids in other parts of the application. That part seems simple to me, but now there are two details I need to determine: the file name, and storing the images. Big sites like Facebook - as far as I know - parse uploads and store them all in the same format. I can see the huge security benefit there. What are the best ways of doing that? As for the file name, I know PHP has a function to generate a file with a unique name. Is there any benefit to doing that over using the id? (i.e. 1.jpg, 2.png, 3.jpg, etc) Hi, I have a working PHP app with limited functionality that I use daily. Some months ago I wanted to add functionality, but soon came to a conclusion I should convert my procedural code to OO PHP. So I read some books by David Powers and Matt Zandstra (the latter was sometimes a little bit too complex for me) and started converting. I now have converted some parts of my app and created new functionality and everything was working perfectly, until I started to use methods from class A inside methods of class B. I started getting irrational errors: sometimes it worked, sometimes it returned an error. I think I have narrowed it down to the use of __construct() and __destruct() in all of my classes, and I'm wondering what is the (better/best) solution. My classes at the moment are all built the same way: Code: [Select] class A { function __construct() { $this->_conn = @ pg_connect( "host=localhost dbname=* user=* password=*" ); } function get_detail() { $this->_res = @ pg_query($this->_conn, "SELECT detail FROM table WHERE ph_id='$id'" ); } function __destruct() { @ pg_free_result( $this->_res ); @ pg_close( $this->_conn );} } I thought I was doing the correct thing by instead of repeating the setting of $this->_conn inside every method, setting that variable upon instantiating the object. But now, I have to make a $this->_conn2 and so on to circumvent the irrational errors (always the same: '5 is not a valid result resource', where '5' should be the '$this->_conn'. Is this a bad practice, or am I doing something else wrong? I also tried 'unset( $this->_conn )' after calling the method, but that didn't seem to work. I'm thinking of looking for a generic PostgreSQL-class so that I can establish the connection inside every method itself, rather than in the __construct() - do you think that would solve my problem? This might be an easy question for someone who is used to OO PHP, so I'm hoping to get an answer which helps me understand the problem. thanks for all the help I can get! Hey all. I was curious what is the best practice when creating a user login system? I've seen them done in the following 2 ways. First I've seen tutorials on logins where after the post data is verified against the database a username session is created and member pages are accessed if the user session is set. Second I've seen tutorials on logins where the username session is verified against the database on every single page. What is the best practice along these lines? Cheers! I have some simple test code: Code: [Select] echo memory_get_usage(true); echo("\n" . '<br />' . "\n"); echo memory_get_usage(false); echo("\n" . '<br />' . "\n"); echo memory_get_peak_usage(); that prints out the three types of memory usage in bytes for my basic admin page. All three values are around 2.25 MB in bytes. What's best practice for PHP memory usage? Is 2.25MB far too much for a single user's visit? Do these PHP memory values include images in the page? hey guys i used defined variables inside my index.php and these defined varaibles are called and used through the site...is this good or bad? defined varaibles Code: [Select] define('DS', DIRECTORY_SEPARATOR); define('PARENT_DIRECTORY_PATH', dirname(dirname(__FILE__)) . DS); define('PUBLIC_DIRECTORY', BASE_URL . DS .'public' . DS); define('PRIVATE_DIRECTORY', BASE_URL .'private' . DS ); thank you I'm trying to teach myself OOP PHP, and I've been looking up a number of tutorials on how to to make OOP MVC frameworks. I came across this one (cached version - their site is down at the moment of posting), and noticed something interesting about it that I've not seen in other tutorials.
Basically, it creates a registry class as $registry (which just uses the __set and __get functions to populate an initially empty array), and then stores variables in there. After that, $registry is passed on to the other classes via their __construct functions, so that they can access site-wide variables.
I think I understand how it's working, and see how it can be used, but this tutorial is the only time I've found such a thing. I was wondering, is using such a class good practice, or how should I store and access globally needed variables (like configuration, database connections, etc)?
Hi I am looking to develop a public facing website and would like some good practice info on php, what you should and shouldnt do and which way to do things, e.g. for security and efficiency, etc. I have read through the PHP security guide from the PHP Security Consortium and was really good, does any one have any more info like this regarding PHP and general good practice Thank you Hey guys, Why exactly do people use multiplication when calculating time? Like when setting cookies, timeouts or something that requires second-based definitions. For example, some do: Code: [Select] $thirty_days = time()+60*60*24*30; As opposed to what I do: Code: [Select] $thirty_days = time()+2592000; Why do they do that? Does it help them calculate it without a calculator? Make it easier to manage/adjust in the future? Personal preference? These are the only possible explanations I can think of. This has been bugging me for a while...am I doing something wrong? I'm reading over this book and I came across something that looked very odd:
public function DisplayHeader() { ?> <table width="100%" cellpadding="12" cellspacing="0" border="0"> <tr bgcolor ="black"> <td align ="left"><img src = "logo.gif" /></td> <td> <h1>TLA Consulting Pty Ltd</h1> </td> <td align ="right"><img src = "logo.gif" /></td> </tr> </table> <?php }In the function it closes a php tag, uses raw html that is rendered as is on the page, and then returns back to opening the php tag. I understand why it is being done. It is easier to write raw html here than to echo it in a php block, but it just looks odd. Anyone actually use this technique? What is the best practice for using site-wide constants in a class? E.g. COMPANY_NAME is set in a config file and used on many pages. How would it be best to use this in a class. I'm guessing just calling COMPANY_NAME anywhere in the class would not be considered best practice. Thanks. |