|
Iron Squid posted:Does PHP have anything like a const? I hope you wouldn't make that an integer too If you want class level constants, see the keyword const.
|
# ¿ Sep 27, 2010 10:53 |
|
|
# ¿ May 7, 2024 13:58 |
|
Yes, this is a bad way of doing things. The reason being it's harder to write unit tests because the constructor of Authenticate always requires a valid DatabaseControls object. The preferred way of doing this is called dependency injection.php:<? class Authenticate { private $db; public function __construct() { } public function attachDb(DatabaseControls $db) { $this->db = $db; return $this; } public function checkUserExists() { $db = $this->checkDb(); // rest of code here } private function checkDb() { if ( is_null($this->db) ) { throw new Exception('a valid DB object is not attached'); } return $this->db; } } ?> php:<? require_once 'PHPUnit/Framework.php'; class AuthenticateTest extends PHPUnit_Framework_TestCase { /** * @expectedException PHPUnit_Framework_Error */ public function testAttachDb_RequiresValidDbObject() { // You could optionally write a dataProvider that attempts to inject many data types $authenticate = new Authenticate; $authenticate->attachDb(NULL); } public function testAttachDb_DbIsAttached() { $authenticate = new Authenticate; $this->assertType('Authenticate', $authenticate->attachDb($this->getMock('DatabaseControls')); } /** * @expectedException Exception */ public function testCheckUserExists_RequiresDbObject() { $authenticate = new Authenticate; $authenticate->checkUserExists(); } // Rest of your tests here } ?> Edit: And stop with the stupid // end constructor, // end function(), // end if bullshit. Every modern editor can brace match so it's easy to find where they end. musclecoder fucked around with this message at 23:41 on Oct 28, 2010 |
# ¿ Oct 28, 2010 23:38 |
|
Begby posted:Excellent example musclecoder. I don't like putting it in the constructor because it makes having to have a mock object each time you create the object in your tests. It's not a huge thing, and setUp() can handle creating the mock database object for you, but I prefer to attach it at a later point. For example, you're writing a test for a method of the class that doesn't require the database at all. No need to inject it into the constructor. Personal preference though. You're right, but I just extend the Exception class and have a custom exception that includes a trace. Just go back one more trace level and you have the method that called checkDb(). To gwar3k1, what is that? code:
|
# ¿ Oct 29, 2010 18:32 |
|
php:<? sprintf('%01.2f', '1.234');?>
|
# ¿ Nov 3, 2010 14:36 |
|
Could you just do aphp:<? round(sprintf('%01.2f', '1.20'), 2);?> Then wrap a strval() to cast it back to a string.
|
# ¿ Nov 3, 2010 15:08 |
|
Fluue posted:I'm having some trouble getting this custom error handling to agree with me. You may also want to install xdebug and you'll get a nice stack trace automatically with errors. Personally, I store errors in the server log file so I can just tail -f that during a request. Also, you're echoing the value of $_POST['name'] or something like that directly back into an input value="" field. While it's probably not a true XSS vulnerability, it's not a good habit to get into because it'll become one on another page. Also, I see that you're md5'ing the password after escaping it. If you don't create the user in the exact same way, you'll have problems. If the user creates their account with a password with some escapable characters in it and you don't escape it, md5 it, and store it, it'll be a different value than if you escape it, md5 it and attempt to load it. Just something to be careful about, especially if this is a shared codebase and someone makes some changes that breaks your authentication system.
|
# ¿ Nov 6, 2010 11:10 |
|
DholmbladRU posted:Can I use range() with the greek alphabet, like Did you see if you could? Bring up your shell: php -a print_r(range('alpha', 'omega')); // show's a through o So now, you can't.
|
# ¿ Nov 10, 2010 21:41 |
|
gwar3k1 posted:If I'm using PDO and binding my parameters, do I need to use strip slashes? What other sanitation should I apply to my userform data before sending it to the database? Ideally, your data shouldn't be sanitized before it comes into the program. In other words, magic_quotes and register_globals should be off. Thus, if someone enters: code:
Then: php:<?php $pdo = new PDO('dsn....'); $statement = $pdo->prepare('query'); $statement->bindParam(':param', $value, PDO::PARAM_STR); // or PARAM_INT, BOOL, NULL, etc. $statement->execute();
|
# ¿ Nov 14, 2010 23:44 |
|
Use Filtering: http://php.net/filter
|
# ¿ Dec 16, 2010 19:28 |
|
I believe it compiles it down to bytecode and probably sets up tables of methods, variables, classes, etc. and can search through that to find what it needs. In PHP3 function ordered was important, but that was 11 years ago.
|
# ¿ Jan 6, 2011 22:29 |
|
Symbol Table, that was the term I was looking for I couldn't remember from my compilers class.
|
# ¿ Jan 6, 2011 22:38 |
|
rotaryfun posted:I'm attempting to get PHPMailer setup but I'm getting this error when attempting to send even a basic message with it. Rather than resetting the *entire* include path, just append includes/phpmailer/ to the current one. What's happening is that the PHPMailer class is attempting to include/require some files and it probably can't include them because the include path has been overwritten.
|
# ¿ Jan 11, 2011 16:51 |
|
To see what your include path is currently defined as, do anphp:<? echo get_include_path();?> Try this instead: php:<? set_include_path(get_include_path() . ';./includes/phpmailer');?>
|
# ¿ Jan 11, 2011 18:15 |
|
Optimus Prime Ribs posted:Hey goons. I've been working on a mini-CMS type thing, and specifically at the moment: SQL management. Everyone is going to tell you to use PDO: http://php.net/pdo And so am I: Use PDO. Edit: Also, backticks aren't ANSI standard SQL, it's a mysql thing. sqlite handles them because it has to. Not sure about other databases.
|
# ¿ Jan 27, 2011 02:24 |
|
I R SMART LIKE ROCK posted:Yeah w3schools; well I've done traditional languages too like c++, c#, java, and .net. I did read through the entire manual and may do so again. I haven't used Php specifically for a while, and I didn't want to confuse syntax; and come off like I was bullshitting. Wait, you read through the *entire* PHP (PHP, please, not Php) manual? Like, all 10,000 pages of it? That's an incredible waste of time because you'll never use half of the extensions available. Syntax is pretty easy to memorize for PHP. If this is an online test for an interview, they'll probably ask you bullshit questions like argument order of some obscure functions. Unfortunately, PHP and it's extensions are so large and change frequently enough that knowledge from a few years ago is outdated. Maybe open up some popular open source projects/frameworks and see how they do things?
|
# ¿ Jan 28, 2011 02:53 |
|
Hammerite posted:When it comes to objects I think it's different, but for scalar values and ordinary arrays it works like above. It's the same way for objects, which is why there's the clone keyword. It's called copy-on-write.
|
# ¿ Jan 30, 2011 16:06 |
|
Hammerite posted:I'm having a hell of a time trying to work out why my file upload script works inconsistently. I typed a fairly detailed description of the problem and posted it on StackOverflow. (I hope it isn't inconsiderate to link to a question I asked on another web site, it's just that I spent a fair amount of time typing it all in over there.) What's your php.ini setting for memory_limit?
|
# ¿ Feb 5, 2011 14:07 |
|
Is CURDATE() a function you wrote, if not, it's a Mysql function. Edit: Also you have a single = there instead of a ==
|
# ¿ Feb 8, 2011 23:42 |
|
Email header injection attacks. http://en.wikipedia.org/wiki/E-mail_injection
|
# ¿ Feb 21, 2011 00:11 |
|
Oh, I wasn't saying you had that problem, just something to be worried about.
|
# ¿ Feb 22, 2011 10:24 |
|
Look Around You posted:I'm really new to php (learning it for a class...). Is there a good template engine for php? I saw smarty linked on the main page, but was wondering if that was the best or if there was a better one. Also, one with vim highlighting would be pretty awesome. In all honesty, just use the PHP Alternative Syntax. It's native PHP, your code looks like normal HTML, and it's fast. So: code:
|
# ¿ Feb 24, 2011 22:09 |
|
That's in $_GET, and in $_SERVER['QUERY_STRING']. Is there only ever going to be one variable? If so, than just popping the top key off $_GET will give you it's name.
|
# ¿ Mar 1, 2011 23:14 |
|
Lamb-Blaster 4000 posted:where can I get the php id3 extension dll? Googling php_id3.dll just gives me a bunch of shady dll download sites, I found the source package on PECL, but it's asking for php.h and a couple other header files I assume are provided with the full php source... I just want to install the extension! You may be SOL - http://www.php.net/manual/en/id3.installation.php Reading ID3 tags is fairly easy, it's just a block of data at the top or bottom of an MP3 file. I think it's the first 512 bytes for ID3v1 and the last 2048 bytes for ID3v2. Here's some screencaps: http://i.imgur.com/ZUuLP.png - ID3v1 http://i.imgur.com/H5kbt.png - ID3v2 Should be pretty easy to open those up in binary mode and read them into a class.
|
# ¿ Mar 4, 2011 21:02 |
|
Or you have multiple database connections open and PHP can't determine which one to use because one wasn't passed to mysql_query().
|
# ¿ Mar 15, 2011 17:21 |
|
Doctor rear end in a top hat posted:Anyone used pcntl_fork? I have a script that would benefit from multithreading, but apparently it's a really horrible idea to do this in PHP. The manual page says that if two children processes are making queries, they might get each others' result sets, which would make attempting this worthless. If there's a way to make it work, I'll do it, otherwise I guess I'm going to have to do it in ruby. I've used it with good results. Wouldn't you create a new database connection in child process so it's entirely self contained? My script to use it was processing huge log files and getting general data from them, so race conditions weren't an issue fortunately.
|
# ¿ Mar 18, 2011 16:47 |
|
McGlockenshire posted:I'm still a big fan of using a message/work queue instead of forking, especially when you're working with mod_php. True, but since he mentioned he might have to do this in Ruby, I imagined it would be on the command line. Doctor rear end in a top hat posted:I would be using new connections, but the comments on the PHP manual were nebulous. A guy put a class in the comments that seems to be perfect for what I'm doing. Are you doing something similar? Thats a pretty clean implementation. Let me rip out some identifiable information and post my script here. It wasn't object oriented, just a single script.
|
# ¿ Mar 19, 2011 02:40 |
|
Here you go, I think I've removed any identifiable information:php:<? #!/usr/bin/env php <?php declare(ticks=1); if (2 !== $argc) { echo('Usage: '.$argv[0].' /path/to/logs'); exit(1); } $directory = realpath($argv[1]).DIRECTORY_SEPARATOR; if (!is_dir($directory)) { echo($directory.' is not a valid directory.'); exit(1); } // Get all of the files in the directory in an array $files_per_process = 10; $log_files = glob($directory.'*.log'); $log_files_count = count($log_files); $children_count = (int)($log_files_count/$files_per_process)+1; $log_file_results = '/tmp/log_file_parsing.results'; $log_file_results_handler = fopen($log_file_results, 'w'); for ($i=0; $i<$children_count; $i++) { $pid = pcntl_fork(); if (-1 == $pid) { echo('Fork #'.$i.' failed.'); exit(1); } elseif ($pid) { // Parent, let the children do it's stuff } else { // Here's a child $files_to_process = array_slice($log_files, $i*$files_per_process, $files_per_process); foreach ($files_to_process as $log_file) { $log_file_handler = fopen($log_file, 'r'); $users_added = 0; $start_time = microtime(true); if ($log_file_handler) { fwrite($log_file_results_handler, 'Started working on file '.$log_file.PHP_EOL); do { $log_line = fgets($log_file_handler); // Do the actual work on each line of the log file here. } while (!feof($log_file_handler)); } $end_time = microtime(true); $run_time = round($end_time - $start_time, 6); fwrite($log_file_results_handler, 'Finished working on file '.$log_file.PHP_EOL); fwrite($log_file_results_handler, 'Took '.$run_time.' seconds to run'.PHP_EOL.PHP_EOL); fclose($log_file_handler); } exit(0); } } // Clean everything up pcntl_wait($status); fclose($log_file_results_handler); echo('Done with everything'.PHP_EOL); exit(0); ?>
|
# ¿ Mar 19, 2011 13:44 |
|
Reo posted:Seriously? Weird. Neither Chrome nor Firefox asks me for a resubmit confirm. You may want to check they don't submit an empty query. I was able to seriously bog down your server by just clicking Search.
|
# ¿ Mar 19, 2011 20:27 |
|
I would suggest you not use an ENUM column, just treat it as a normal VARCHAR and store valid values in an array somewhere. Then let your application validate against those values and you can use those values in your dropdown. I've never used an ENUM and not had it come back to bite me in the rear end later.
|
# ¿ Mar 20, 2011 19:42 |
|
Would like to share a little project of mine: Kwolla. About 18 months ago my buddies and I wanted to strike it rich by building our own social network. It essentially fell flat (for numerous reasons), but the code was still perfectly good. We decided to sell it at first and we made some decent money in a month after selling it, but it lacked a lot of features so I decided to give the first version away for free. Kwolla is social networking software so if you want to build your own social network, you can do so with it. Version 1.x is free to download, but we're selling version 2.0 which is a total rewrite. I think the code is of good quality and it would be a good thing to learn on as well. Right now we're selling install help and premium support to make money. I would love to hear your thoughts and opinions on it if you decide to download. kwolla.com
|
# ¿ Apr 5, 2011 14:37 |
|
Golbez posted:What's the best way to look for exceptions? I have two things I'm thinking of, one where I catch the whole block, and one where I catch each part: Well you have several options. The first is obviously less code, but if something unexpected throws an exception and you blindly echo out the error, you could be in trouble (for example, if one of those connected through PDO and couldn't, a PDOException is thrown. PDOException's parent is Exception so you would catch that at the same time). The second allows for more granular way of handling errors. You could certainly make it more succinct: php:<? try { $var = $manager->get($id); $var->setFoo('bar'); $var->setShazbot('fnord'); $manager->write($var); } catch (DataException $e) { /* do stuff */ } catch (ValidationException $e) { /* do other stuff */ } catch (Exception $e) { /* final stuff, since PHP decided not to have the final keyword. */ }?>
|
# ¿ Apr 5, 2011 15:36 |
|
But now unit testing your stuff is going to be harder because you have a DOC - depended on component - in the Repository class. Use manual dependency injection instead:php:<? class bar_manager { private $foo_manager = NULL; /* constructors */ public function attach_foo_manager(foo_manager $foo_manager) { $this->foo_manager = $foo_manager; return $this; } } $foo_manager = new foo_manager; $bar_manager = new bar_manager; $bar_manager->attach_foo_manager($foo_manager);?>
|
# ¿ Apr 8, 2011 20:11 |
|
Thanks! I'm giving a talk on it (my first talk) to Lone Star PHP (http://lonestarphp.com) in June so I'm also trying to figure out the best way to present it.
|
# ¿ Apr 8, 2011 21:03 |
|
Alright, lets break it down a bit. First, I'm a huge fan of unit testing. It really does make your code better, so if you're not testing, do it. Test all the loving time. You don't have to be so disciplined that you do TDD all the time, but writing tests is never a bad thing. Which, when you start unit testing, you'll immediately stop clouding your constructors with a lot of activity because you have to, well, construct your object often. In this case, the fixture of each of your test cases (the code to set everything up in a test) would require setting up all of the necessary things to avoid the exception being thrown. Now you're not unit testing anymore because you have a DOC. And you either have to do this for each test or in the setUp() method (assuming an xUnit framework) and it gets tedious quickly. So, keep stuff out of your constructor. Unfortunately I haven't been keeping up with your posts over the last few days, and I don't want you to rework a lot of code. What you have now seems like it works and is clean. For example, last week I had to write a class that deals with a SOAP API. php:<? class api { private $soap_client = NULL; public function __construct() { } public function attach_soap_client(SoapClient $soap_client) { $this->soap_client = $soap_client; return $this; } public function add_user($email_address, $fields=array()) { $soap_client = $this->check_soap_client(); if (empty($email_address)) { throw new Exception('Email address is empty.'); } $result = $soap_client->addUser($email_address, $fields); if (false === $result) { throw new Exception('Error returned from service.'); } $user_id = $result->user_id; return $user_id; } private function check_soap_client() { if (is_null($this->soap_client)) { throw new Exception('SoapClient object not attached.'); } return $this->soap_client; } } ?> php:<? class api_test extends PHPUnit_Framework_TestCase { /** * @expectedException Exception */ public function test_add_user__requires_soap_client() { $api = new api; $api->add_user('user@email.com'); } /** * @expectedException Exception */ public function test_add_user__requires_email_address() { $soap_client_mock = $this->getMock('SoapClient', array('__construct')); $api = new api; $api->attach_soap_client($soap_client_mock); $api->add_user(); } /** * @expectedException Exception */ public function test_add_user__must_return_valid_response() { $soap_client_mock = $this->getMock('SoapClient', array('__construct', 'addUser')); $soap_client_mock->expects($this->once()) ->method('addUser') ->will($this->returnValue(false)); $api = new api; $api->attach_soap_client($soap_client_mock); $api->add_user('user@email.com'); } public function test_add_user__returns_user_id() { $user_id = mt_rand(1, 10000); $valid_result = new stdClass; $valid_result->user_id = $user_id; $soap_client_mock = $this->getMock('SoapClient', array('__construct', 'addUser')); $soap_client_mock->expects($this->once()) ->method('addUser') ->will($this->returnValue($valid_result)); $api = new api; $api->attach_soap_client($soap_client_mock); $actual_user_id = $api->add_user('user@email.com'); $this->assertTrue($user_id, $actual_user_id); } } ?> Now I have a nicely abstracted and tested class. The SoapClient object is injected manually (there are automatic DI frameworks, but I find them unecessary, just know your API's). From there I can write some functional tests to ensure the api class actually communicates with the server properly. So, uh, I hope this helps someone.
|
# ¿ Apr 8, 2011 22:17 |
|
Quick and dirty: php:<? $file = file_get_contents('http://path/to/that/document'); $file_raw = stripslashes($file); // Do stuff with $file_raw now?>
|
# ¿ Apr 10, 2011 21:20 |
|
Have you tried the memory limitations? I just wrote this little script and it used 0.32MB of RAM to read through a 66MB file.php:<?php $fh = fopen('/tmp/big-rear end-file.csv', 'r'); while ($line = fgetcsv($fh)) { $line_length = strlen($line[0]); } fclose($fh); $peak_memory_usage = (memory_get_peak_usage()/(1024*1024)); echo($peak_memory_usage.'MB'.PHP_EOL);
|
# ¿ Apr 12, 2011 22:27 |
|
I don't like it. That means you have to mock those objects each time you're testing your code because at a minimum you have to construct the SUT (system under test, or the object you're testing).
|
# ¿ Apr 16, 2011 11:43 |
|
It's called heredoc and was taken from Perl (kinda).
|
# ¿ Apr 20, 2011 01:25 |
|
What happens if you just echo out the URL and then do a code:
|
# ¿ Apr 20, 2011 15:43 |
|
|
# ¿ May 7, 2024 13:58 |
|
Safety Shaun posted:I'm not exactly sure what you mean but I found the cURL class, but I am not receiving any errors to indicate i'm doing it wrong or any data back Open up your shell, and use the curl program to fetch the URL so at least you can ensure XML is being returned. For example, code:
Try that and make sure you get the XML you're wanting to STDOUT. musclecoder fucked around with this message at 16:09 on Apr 20, 2011 |
# ¿ Apr 20, 2011 16:07 |