-
Posts
2,000 -
Joined
-
Last visited
-
Days Won
1
Everything posted by Andy-H
-
http://blip.tv/phpnw contains all the talks from the PHPNW conferences, running back to 2k8
-
https://github.com/reactphp/react Written by @igorwesome, although personally, I'd just use NodeJS
-
@andigutmans @zeevs @patrick_allaert @phpmasterdotcom @akrabat @zend @lornajane @dshafik @igorwesome @php_net @derickr You can follow me at @ndyHolland1991
-
Flaw In Php's Namespace, Cannot Import An Entire Namespace,
Andy-H replied to Hall of Famer's topic in Miscellaneous
I think autoloading makes this feature redundant, take kicken's example, is it really that much of a burden to have to type 5 more characters to make your code far more self-explanatory and easier to debug? Not to mention that you're only loading the classes that you actually use... As for Exception and ArrayObject, couldn't you just: use \Exception as Exception; use \ArrayObject as ArrayObject; I can't test this as I'm on my Dad's laptop which doesn't have PHP installed, but it should work? -
I think I understand what you're asking for now: $table = $_GET['table']; $query = "SELECT * FROM `". mysql_real_escape_string($table) ."`"; // limit 1? $result = mysql_query($query); $content = ''; while ( $row = mysql_fetch_assoc($result) ) { $content .= '<li>'. implode('</li><li>', $row) .'</li>'. PHP_EOL; } echo $content; // '<li>Field 1 Value</li><li>Field 2 value</li>'... Or with limit 1 $table = $_GET['table']; $query = "SELECT * FROM `". mysql_real_escape_string($table) ."` LIMIT 1"; $result = mysql_query($query); $content .= '<li>'. implode('</li><li>', mysql_fetch_assoc($result)) .'</li>'. PHP_EOL; echo $content; // '<li>Field 1 Value</li><li>Field 2 value</li>'... For a result like this: $name = $row['name']; See the extract function, but be sure that if your'e extracting from an unknown source (i.e. $_GET/$_POST) you use EXTR_SKIP or EXTR_PREFIX_ALL i.e. extract($_GET, EXTR_SKIP); // only extract key names to variables if they don't already exist extract($_POST, EXTR_PREFIX_ALL, 'incase_it_already_exists'); // $already_exists_name
-
http://www.optimum7.com/css3-man/animation.html
-
From what I can gather, you're not asking to use the data without it being fetched, but you want the column names (i.e. associative key names) bad practices aside, I think you're asking for something along these lines? /* TABLE - users username - James password - somehash ip - 127.0.0.1 */ $query = "SELECT * FROM users"; $result = mysql_query($query); while( $row = mysql_fetch_assoc($result) ) { $new_query = "SELECT `". implode('`, `', array_keys($row)) ."` FROM othertable"; // effectively "SELECT `username`, `password`, `ip` FROM othertable"; } So basically, if you're asking what I think you're asking, you need array_keys?
-
When you create the user: // add user to database // "INSERT INTO users ( id, username, ..., activated ) VALUES ( NULL, ..., 0 )"; // generate an identifiable hash // from some include file (without the comment (/* ... */)) /* function getActivationId($username) { return md5($username . 's0m3r4nd0m54lt'); } */ $link = 'http://'. $_SERVER['SERVER_NAME'] .'/activate.php?user='. $username .'&activation_id='. getActivationId($username); // send link in email // activate.php if ( $_GET['activation_id'] == getActivationId($_GET['username']) ) { // query "UPDATE users SET activated = 1 WHERE username = :username" } else { echo 'Incorrect activation ID'; }
-
echo '<pre>'; $hello = 'hello world!'; echo 'First we\'re going to pass by value: '. PHP_EOL; echo "\t" . 'We are in the global scope: $hello = '. $hello . PHP_EOL; function ucase($hello) { $hello = strtoupper($hello); echo "\t\t" . 'We are in the local scope of the function "ucase": $hello = '. $hello . PHP_EOL; } echo "\t" . 'We are back in the global scope: $hello = '. $hello . PHP_EOL . PHP_EOL; echo 'Now we\'re going to pass by reference: '. PHP_EOL; echo "\t" . 'We are in the global scope: $hello = '. $hello . PHP_EOL; function ucase(&$hello) { $hello = strtoupper($hello); echo "\t\t" . 'We are in the local scope of the function "ucase" passing by reference: $hello = '. $hello . PHP_EOL; } echo "\t" . 'We are back in the global scope after passing to "ucase" by reference: $hello = '. $hello . PHP_EOL . PHP_EOL; Try running this, hopefully it will help
-
$query = "SELECT p.username, ps.players_killed FROM players p INNER JOIN player_stats ps ON ( p.id = ps.playerid ) WHERE ps.players_killed > 100 ORDER BY ps.players_killed DESC LIMIT 50"; $result = mysql_query($query); while ( list($name, $kills) = mysql_fetch_assoc($result) ) { echo sprintf(' <tr bgcolor="#bfffff"> <td>%s</td> <td bgcolor="#00ff00" class="td_b">%s</td> </tr>', htmlentities($name, ENT_QUOTES, 'UTF-8'), number_format($kills, 0)); }
-
Can You Echo A $Var That Is Defined Later On In The Script?
Andy-H replied to icthos's topic in PHP Coding Help
// styles.php $stylesheets = array(1 => 'red', 'green', 'blue', 'black', 'purple', 'yellow'); <?php include('functions.php'); include('styles.php'); include('head.php'); include('body.php'); ?> <?php $pageNumber = 6; ?> <!doctype html> <html> <head> <link rel="stylesheet" href="<?php echo $stylesheets[$pageNumber]; ?>.css" type="text/css"> </head> <p>This is page six! You will notice that page six is coloured yellow, unlike any of the other pages</p> -
Interesting Techniques To Get Click Through Results For Ads
Andy-H replied to Andy-H's topic in Miscellaneous
Yeah a lot of people in Manchester seem to. Not too far then, I think I'll be going to the next one, missed this months, which was on MySQL binary logging If you're interested in PHPNW, they have a facebook page and a twitter account (@phpnw) and the PHPNW website, they also put the conference videos online about 8 weeks after it finishes, so the 2012 ones should be online within the next couple of weeks. -
Interesting Techniques To Get Click Through Results For Ads
Andy-H replied to Andy-H's topic in Miscellaneous
Ahh OK, where abouts? I'm on Lever street -
Interesting Techniques To Get Click Through Results For Ads
Andy-H replied to Andy-H's topic in Miscellaneous
Well, I was an event helper, so I got my ticket for free, but I would say it's definitely worth it. There's a tutorial day which is on a weekday, I didn't attend that but they had some interesting talks going on, the most notable in my opinion was 'PHP core hacking' by Derick Rethans (@derickr). The day I attended was great, there was a talk by Igor Wiedler (@igorwesome) on ReactPHP and 'Building a firehose' by Ian Barber (@IanBarber) There was also a free lunch, and an open bar after 9pm, I learned quite a lot, but if anything, it's well worth going for the social side of things, it was great just getting the opportunity to talk to other developers, about tools and practices they use, projects they've worked on. I also heard about Composer there, which I didn't know about previously, I haven't had the chance to use it yet as I'm mostly developing in RoR at the moment and when I do get the chance to work on a PHP project, it always seems to be CubeCart :'( But it seems like a great tool. If you fancy a primer there's a PHPNW meetup on the first Tuesday of every month at @JoshuaBrooksMCR, I know it's probably a little far for you though. -
Interesting Techniques To Get Click Through Results For Ads
Andy-H replied to Andy-H's topic in Miscellaneous
Perhaps it's because I have google set to never show instant results and 100 results per page -
That's a good point actually, OOP is commonly used in conjunction with MVC (Model View Controller), which is about separation of control flow logic, business logic (or model logic) and view logic, generally you would have a main template containing your page layout, and insert a yield into an appropriate place in that page. This also couples with re-usable models, as the data a model interfaces to, can be applied across many views. The controllers responsibility is basically to take a request URL (often aided by a router), and control what models are used, what data is returned and what views are invoked to return the content to the browser. I would checkout the Github repositories of some open source frameworks, such as Zend Framework, Yii or Rails (for Ruby) and start hacking away at them to learn about how they work. I haven't read this as I'm at work at the moment, it's just the first organic google result when searching MVC principles: http://www.htmlgoodies.com/beyond/php/article.php/3912211/Principles-Of-MVC-for-PHP-Developers.htm
- 12 replies
-
Has anyone else noticed that Google seem to have started loading their sponsored ads a second or so after page load (in Chrome at least), in what would seem like an attempt to get people to accidentally click on them when trying to select the first organic result? I remember a while back AOL did the exact same thing with their mail link.
-
Personally, I never understood the benefits of OOP by having someone explain them to me, something just 'clicked' one day and I 'got it', but I'll have a go 1) Encapsulation (hide the implementation, expose the interface) This basically means, hiding away the 'implementation' and exposing an interface to that behaviour, take a lock for example, you don't need to know how a lock works, but generally, locks have a universal interface, so most people know how to unlock one (i.e. you don't have to know that when you put a key in a yale lock, that it pushes back the pins to compress the springs underneath, until the pin is completely removed from the cylinder, then when you turn the key, it also turns the catch, allowing the door to be opened, knowing the public interface is, in effect, having the key) <?php interface Lock { public function insertKey(); public function releaseKey(); public function turnKey($degrees, $direction); public function isUnlocked(); } class YaleLock implements Lock { /* * @var array $_pins Array of pin lengths */ protected $_pins = array(); /* * @var array $_pinPositions Array containing current pin positions in milimeters */ protected $_pinPositions = array(); /* * @var integer $_catchPosition Current position of the catch in degrees */ protected $_catchPosition = 0; /* * @param array $length_of_pins Array containing length of pins */ public function __construct(array $length_of_pins) { $this->_pins = $length_of_pins; $this->_pinPositions = $length_of_pins; } public function insertKey() { $this->_pushBackThePins(); return $this; } public function releaseKey() { $this->_releaseThePins(); return $this; } public function turnKey($degrees, $direction) { if ( !$this->isCorrectKey() ) throw new Exception('Incorrect key'); $degrees = $direction == 'left' ? -$degrees : $degrees; $this->_catchPosition += $degrees; while ( $this->_catchPosition < 0 ) $this->_catchPosition += 360; while ( $this->_catchPosition > 360 ) $this->_catchPosition -= 360; return $this; } public function isUnlocked() { return $this->_isCorrectKey() && $this->isCatchReleased(); } protected function isCorrectKey() { $positions = array_unique($this->_catchPosition); return count($positions) == 1 && $positions[0] == 0; } protected function isCatchReleased() { return $this->_catchPosition > 90 && $this->_catchPosition < 100; } protected function _pushBackThePins() { foreach($this->_pins as $pinKey => $pinLength) { $this->_movePin($pinKey, -$pinLength); } } protected function _releaseThePins() { foreach($this->_pins as $pinKey => $pinLength) { $this->_movePin($pinKey, $pinLength); } } protected function _movePin($which_pin, $number_of_milimeters) { $this->_pinPositions[$which_pin] += $number_of_milimeters); } } $Lock = new YaleLock(array(3, 7, 4, 5, 2)); $Lock->insertKey()->turnKey(90, 'right'); if ( $Lock->isUnlocked() ) { echo 'The door is unlocked'; } else { echo 'The door is locked'; } $Lock->turnKey(90, 'left')->releaseKey(); if ( $Lock->isUnlocked() ) { echo 'The door is unlocked'; } else { echo 'The door is locked'; } So now using all of these functions enforced to be defined by the interface, we know we can operate a lock properly. We could create many different locks that implement this interface (see below), and anyone who knows the interface can operate the lock, you only need know the encapsulated functionality if you're a locksmith (hacker, extending a lock's functionality) or a thief (cracker). class MorticeLock implements Lock { // the juciy bit } We can now unlock a mortice lock using the same interface as a yale lock, a 'universal interface' to the underlying functionality. 2) Code re-use If you make code generic enough, it should be easy to extend on that code for use in the same project, or plug that code into another project (or both). I.e. Lets say someone installed an intercom to allow this lock to be unlocked electronically. To do this we need to encapsulate some functionality to be re-used programmatically. <?php interface Lock { public function insertKey(); public function releaseKey(); public function turnKey($degrees, $direction); protected function _lock(); protected function _unlock(); } class YaleLock implements Lock { /* * @var array $_pins Array of pin lengths */ protected $_pins = array(); /* * @var array $_pinPositions Array containing current pin positions in milimeters */ protected $_pinPositions = array(); /* * @var integer $_catchPosition Current position of the catch in degrees */ protected $_catchPosition = 0; /* * @param array $length_of_pins Array containing length of pins */ public function __construct(array $length_of_pins) { $this->_pins = $length_of_pins; $this->_pinPositions = $length_of_pins; } public function insertKey() { $this->_pushBackThePins(); return $this; } public function releaseKey() { $this->_releaseThePins(); return $this; } public function turnKey($degrees, $direction) { if ( !$this->isCorrectKey() ) throw new Exception('Incorrect key'); $degrees = $direction == 'left' ? -$degrees : $degrees; $this->_catchPosition += $degrees; while ( $this->_catchPosition < 0 ) $this->_catchPosition += 360; while ( $this->_catchPosition > 360 ) $this->_catchPosition -= 360; return $this; } public function isUnlocked() { return $this->_isCorrectKey() && $this->isCatchReleased(); } protected function _lock() { $this->_pushBackThePins(); $this->turnKey(90, 'right'); } protected function _unlock() { $this->_releaseThePins(); $this->turnKey(90, 'left'); } protected function isCorrectKey() { $positions = array_unique($this->_catchPosition); return count($positions) == 1 && $positions[0] == 0; } protected function isCatchReleased() { return $this->_catchPosition > 90 && $this->_catchPosition < 100; } protected function _pushBackThePins() { foreach($this->_pins as $pinKey => $pinLength) { $this->_movePin($pinKey, -$pinLength); } } protected function _releaseThePins() { foreach($this->_pins as $pinKey => $pinLength) { $this->_movePin($pinKey, $pinLength); } } protected function _movePin($which_pin, $number_of_milimeters) { $this->_pinPositions[$which_pin] += $number_of_milimeters); } } interface ElectronicLock { public function pushTheButton(); } class ElectronicYaleLock extends YaleLock implements ElectronicLock { public function pushTheButton() { $this->unlock(); } } Now we can extend any lock to allow for it to be electronically unlocked, and by implementing ElectronicLock, we also encapsulate this behaviour. As well as these advantages, lets say you have a project with say, 9000 lines of code, if this is programmed in a procedurally, you may have 450 instances of: echo htmlspecialchars($variable); But now you decide you don't want to use htmlspecialchars, you want to use htmlentities instead, you have to change 450 instances of that function call, now, lets say you programmed your project in OO PHP: class Sanitize { public static function html($variable) { return htmlspecialchars($variable); } } Now you have 450 instances of Sanitize::html($variable); now, implementing this change is simple, just change the method body: class Sanitize { public static function html($variable = '', $ent = ENT_QUOTES, $charset = 'utf8') { return htmlentities($variable, $ent, $charset); } } Now I know you can just use a function to do this in procedural code, but I believe it is a lot cleaner to use the OO method, this way you can group all of your sanitization methods into one class, and you know if you need to re-use your sanitization class, it's just a case of dropping that file into another project. There's also the advantage of autoloading: <?php set_include_path(get_include_path() . PATH_SEPARATOR . 'lib' . PATH_SEPARATOR . 'models'); spl_autoload_register(function($class) { include str_replace('\\', '/', $class) .'.class.php'; }); Now if you stick to a naming convention with your classes, files and locations, you shouldn't really have to use include(_once) or require(_once) in the entire lifespan of your project. The above code expects a naming convention of - namespaces map to a folder in root_directory/lib or root_directory/models, files containing class definitions should be saved as class name the .class.php extension i.e. // root_directory/lib/ORM/DataMapper.class.php namespace ORM; class DataMapper { } Hope that helps.
- 12 replies
-
I've just bought this on behalf of my girlfriends little brother, it arrived the day before yesterday, I was surprised that it was actually legit at that price, but the spec checks out, no wireless NIC tho. Maybe give them a go unless you REALLY want to build it yourself, although you will almost definitely end up paying more; it's just too hard to compete with companies that can bulk-buy components and put a computer together dirt cheap. http://www.ebay.co.uk/itm/221127252096?ssPageName=STRK:MEWNX:IT&_trksid=p3984.m1497.l2649
-
1) I would agree with what these people are saying, I've been programming PHP for about 6 years in total and almost 2 years commercially, my employer has recently paid for me to take my ZCE and I'm not sure whether I'm going to pass, also, as Jess said before, the vast majority of the test is not relevant to a career in programming PHP, there's a lot of 'trick questions' and the practice exams I've used aren't very clear on what they want you to do, for example, a question asked: When updating one or more values in an array, which looping construct would be most suitable: A. A for loop B. A foreach loop C. A while loop I answered C, a foreach loop, because I find the easiest way (of the 3) is to use a foreach loop that references the values, however, the answer was a for loop, I had thought about the question not stating whether or not the foreach loop implied a reference, and thought it best to assume it did, it would make things much easier if things like this were explicitly stated. 3) I would say no but there's too many variables there to give a definitive answer.
-
First one prints 1345, I don't know why it doesn't work in PHP 5.4? Looking again, I assume it's because of the missing semicolon? The second one, I think will output 9, 8, 7, 6, 5, 4, 3, 2, 1 ? // eidt Or is the second a trick question, and throws an error like invalid object operator?
-
AFAIK Zend only offer the practice exams if you purchase their ZCE training? That test is REALLY easy, also, this is quoted from the page, although I know this isn't relevant to the questions asked on there: "This test was created based on php 4.0.5, and is updated for php 4.2.2." Thanks for the reply
-
Thank you, that's very kind, may I recommend SMF
-
<div class="container"> <div class="content-container1"> <div class="content-container2"> <div class="section-navigation"></div> <div class="content"> <div class="topheader"> <?php if ($_SESSION['userLoggedIn']) { ?> <?php /* * SHORT ECHO TAG (< ?=) IS ALWAYS AVAILABLE SINCE PHP 5.4.0 * OUTPUT SHOULD BE ESCAPED WITH htmlentities TO AVOID XSS * ALSO, IF OUTPUTTING LITTLE OR NO VARIABLES, IN A LARGE CHUNK OF HTML, * IT'S GENERALLY CLEANER TO JUMP OUT OF PHP TAGS RATHER THAN USING HEREDOC OR ECHO/PRINT */ ?> <div class="loggedin"> <?= htmlentities($_SESSION['userfirstname'] .' '. $_SESSION['usersurname'], ENT_QUOTES, 'UTF-8'); ?> <a href="/test/closesession.php">Logout</a> </div> <?php }else{ ?> <div class="headersignin"> <a href="/users/login.php" rel="nofollow" class="blacklink" >Sign in</a> </div> <div class="headerjoin"> <a href="/users/register.php" rel="nofollow" class="whitelink">Join free</a> </div> <?php } ?> <form method='post' action='upload.php' enctype='multipart/form-data'> Select a JPG, GIF, PND or TIF File <input type='file' name='filename' size='20' /> <input type='submit' value='Upload' /> </form> <?php if ( !empty($_FILES) ) { $errors = array(); // list of allowed extensions (filetypes) $allowed_extensions = array('jpg', 'gif', 'png', 'tif'); $filename = $_FILES['filename']['name']; // list created variables (in the scope in which it is called) from an array of values // i.e. list($a) = array('a') is the same as $a = 'a'; list($width, $height, $type, $attr) = getimagesize($_FILES['filename']['tmp_name']); // image_type_to_extension is available in PHP 5 $extension = image_type_to_extension($type, false); // param 2, true/false, include '.', i.e. '.jpg' if ( $extension == 'jpeg' ) $extension = 'jpg'; // add an error message instructing the user of allowed filetypes if they try to upload on thats not allowed if ( !in_array($extension, $allowed_extensions) ) $errors[] = "'". htmlentities($filename, ENT_QUOTES, 'UTF-8') ."' is not an accepted image file, please upload a ". implode('/', $allowed_extensions) .' image'; // create unique filename $new_filename = uniqid() .'.'. $extension; // if moving the file fails add an error message if ( !move_uploaded_file($_FILES['filename']['tmp_name'], $new_filename) ) $errors[] = 'There was an unexpected error uploading your file'; // Using PDO, you should probably include this from somewhere // $dbh = new PDO('mysql:dbname=mysql_dbname;host=127.0.0.1', 'mysql_username', 'mysql_password'); // $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // this prevents SQL injection if ( emtpy($errors) ) { $stmt = $dbh->prepare('INSERT INTO users ( logo ) VALUES ( :logo )'); $stmt->bindParam(':logo', $new_filename, PDO::PARAM_STR, strlen($new_filename)); if ( $stmt->execute() ) { echo 'Your file was successfully uploaded to '. $new_filename; }else{ echo 'An unexpected database error has occured' } }else{ echo implode('<br />', $errors); } } ?> //edit This forum software is
-
<div class="container"> <div class="content-container1"> <div class="content-container2"> <div class="section-navigation"></div> <div class="content"> <div class="topheader"> <?php if ($_SESSION['userLoggedIn']) { ?> <?php /* * SHORT ECHO TAG (< ?=) IS ALWAYS AVAILABLE SINCE PHP 5.4.0 * OUTPUT SHOULD BE ESCAPED WITH htmlentities TO AVOID XSS * ALSO, IF OUTPUTTING LITTLE OR NO VARIABLES, IN A LARGE CHUNK OF HTML, * IT'S GENERALLY CLEANER TO JUMP OUT OF PHP TAGS RATHER THAN USING HEREDOC OR ECHO/PRINT */ ?> <div class="loggedin"> <?= htmlentities($_SESSION['userfirstname'] .' '. $_SESSION['usersurname'], ENT_QUOTES, 'UTF-8'); ?> <a href="/test/closesession.php">Logout</a> </div> <?php }else{ ?> <div class="headersignin"> <a href="/users/login.php" rel="nofollow" class="blacklink" >Sign in</a> </div> <div class="headerjoin"> <a href="/users/register.php" rel="nofollow" class="whitelink">Join free</a> </div> <?php } ?> <form method='post' action='upload.php' enctype='multipart/form-data'> Select a JPG, GIF, PND or TIF File <input type='file' name='filename' size='20' /> <input type='submit' value='Upload' /> </form> <?php if ( !empty($_FILES) ) { $errors = array(); // list of allowed extensions (filetypes) $allowed_extensions = array('jpg', 'gif', 'png', 'tif'); $filename = $_FILES['filename']['name']; // list created variables (in the scope in which it is called) from an array of values // i.e. list($a) = array('a') is the same as $a = 'a'; list($width, $height, $type, $attr) = getimagesize($_FILES['filename']['tmp_name']); // image_type_to_extension is available in PHP 5 $extension = image_type_to_extension($type, false); // param 2, true/false, include '.', i.e. '.jpg' if ( $extension == 'jpeg' ) $extension = 'jpg'; // add an error message instructing the user of allowed filetypes if they try to upload on thats not allowed if ( !in_array($extension, $allowed_extensions) ) $errors[] = "'". htmlentities($filename, ENT_QUOTES, 'UTF-8') ."' is not an accepted image file, please upload a ". implode('/', $allowed_extensions) .' image'; // create unique filename $new_filename = uniqid() .'.'. $extension; // if moving the file fails add an error message if ( !move_uploaded_file($_FILES['filename']['tmp_name'], $new_filename) ) $errors[] = 'There was an unexpected error uploading your file'; // Using PDO, you should probably include this from somewhere // $dbh = new PDO('mysql:dbname=mysql_dbname;host=127.0.0.1', 'mysql_username', 'mysql_password'); // $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); // this prevents SQL injection if ( emtpy($errors) ) { $stmt = $dbh->prepare('INSERT INTO users ( logo ) VALUES ( :logo )'); $stmt->bindParam(':logo', $new_filename, PDO::PARAM_STR, strlen($new_filename)); if ( $stmt->execute() ) { echo 'Your file was successfully uploaded to '. $new_filename; }else{ echo 'An unexpected database error has occured' } }else{ echo implode('<br />', $errors); } } ?> Hope that helps, if there are any functions you don't understand go to http://php.net/functionname, i.e. if you don't understand how the list function works, go to http://php.net/list NOTE: I didn't test this code, so it may not work straight out of the box // EDIT Trying to fix indenting problem