web dev – Internet Strategy Guide https://phpprotip.com Together we can defeat the internet Tue, 07 Mar 2017 02:01:20 +0000 en-US hourly 1 https://wordpress.org/?v=4.7.30 55205001 Copyright © Internet Strategy Guide 2013 chance@chancegarcia.com (Internet Strategy Guide) chance@chancegarcia.com (Internet Strategy Guide) http://phpprotip.com/wp-content/plugins/podpress/images/powered_by_podpress.jpg Internet Strategy Guide https://phpprotip.com 144 144 Together we can defeat the internet Internet Strategy Guide Internet Strategy Guide chance@chancegarcia.com no no fun with arrays and requirement chains https://phpprotip.com/2010/12/fun-with-arrays-and-requirement-chains/ https://phpprotip.com/2010/12/fun-with-arrays-and-requirement-chains/#comments Wed, 01 Dec 2010 21:21:09 +0000 http://phpprotip.com/?p=484 Recently, I had to figure out if a given set of features contained all of their necessary requirements.

For better or worse, the table was modeled so that the feature table referenced itself so that it could create a parent/child requirement chain. For example:

feature_id requirement_id
2 null
5 2
7 null
11 5

So my problem is to find out if a given set of requested features, make sure that the requirements are also present. This includes any requirements the requirement feature may have. In this example, 11 requires 5 which requires 2.
Let’s take $featureRequest1=array(2,5,7,11) and $featureRequest2=array(7,5,11). If I were to run a look up of requirements, I would find that we have

$requirements=array(2,5).

I tried to use the php in_array function but it didn’t work as I expected it to.

in_array($requirements,$featureRequest1); // i expect true
var_dump(in_array($requirements,$featureRequest1)); // false
in_array($requirements,$featureRequest2); // i expect false
var_dump(in_array($requirements,$featureRequest2)); // false

I then realized what I need is for there to be a clear intersection between the requirements and the request.

$requirements==array_intersect($requirements,$featureRequest1); // expect true
var_dump($requirements==array_intersect($requirements,$featureRequest1)); // true
$requirements==array_intersect($requirements,$featureRequest2); // expect false
var_dump($requirements==array_intersect($requirements,$featureRequest2)); // false

I should probably note that array_interest will preserve the array keys. To fix it, you can either flip the 2 arguments or pass the return array to array_values

]]>
https://phpprotip.com/2010/12/fun-with-arrays-and-requirement-chains/feed/ 2 484
visibility and inheritance. https://phpprotip.com/2009/08/visibility-and-inheritance/ https://phpprotip.com/2009/08/visibility-and-inheritance/#comments Fri, 07 Aug 2009 15:16:40 +0000 http://phpprotip.com/?p=164 An interesting topic came up in #phpc today. It revolved around some issues I’ve been encountering in my latest code designs/structures. It also leads into some side topics that I will attempt to explore.

From my point of view, the discussion centered around what is the best ‘default’ visibility to use for methods. Another thing touched upon is the Open/Closed principle, which I think I subscribe to or may subscribe to(this depends on my ability to determine what half of the words in the entry mean).

Out of the whole discussion, here is the points I got (aka understood) out of it. Please correct me in the comments if I’m off base in any way.

Methods should only be public when necessary. This is to help reduce the amount of side-effects that can occur because of method overrides.

K, I can accept that and in thinking about my past code, I use to use protected more than private. I used public very sparingly.
Now I find, since I started unit testing, that I have a large amount of public functions than I’ve had in the past. That is because I can’t figure out how to test private methods. One way that I can think of is to create public methods that allow you to test the private ones. Unfortunately, this makes me wonder why the method isn’t public to begin with since it seems redundant and wasteful to have these public methods to access private methods.
Please note the key word methods, property accessors are a different story.
The best solution (I can think of) to testing private methods is Mock Objects. Unfortunately, even though I’ve started to use mocks/doubles more, I’m unsure if my implementation is correct. Until I’m confident in my understanding of mocks/doubles, I worry about having false positives in test results.

Another assertion that was made in the discussion was that private methods allow you to preserve the class’ core functionality.
Unfortunately, no matter what the visibility of the method is, you’re able to override it (and potentially mess with the core functionality you were trying to preserve).
Example:

class foo{
    private function foobar() {
        echo "foo\n";
        return "foo foo\n";
    }
    
    public function bar() {
        echo "w00t ";
        return $this->foobar();
    }
}

class bar extends foo{
    private function foobar() {
        return "bar\n";
    }
    
    public function baz() {
        echo $this->bar();
    }
    
    public function wut() {
        echo $this->foobar();
    }
}

$f=new bar();
$f->baz();
$f->wut();

By running the above code, you get:

w00t foo
foo foo
bar

If preservation of core functionality is your main concern, then you’re better off using final.

So after all that rambling, you’re probably wondering what I’m trying to get to. It still comes down to visibility’s effect on inheritance. The way I see it, unless you declare the method as final, you can’t lock down the parent functionality because private methods can still be overridden. Trying to figure out what level of visibility for a method is a situational call. There is no correct ‘default’ visibility. Sure private is safer because of least privilege but it makes testing a bear (or at least a bear at my current skill level in testing). Public potentially opens you up for abuse or misuse.

What I would still like to know is, how do you do class method visibility? How does that affect your testing methodology? Can someone give me an example (that isn’t a singleton) where private is a better choice over protected? I like protected because it seems less limiting to me and my current coding style appreciates that degree of flexibility.

]]>
https://phpprotip.com/2009/08/visibility-and-inheritance/feed/ 10 164
headers exception with Zend_Session while unit testing https://phpprotip.com/2009/06/headers-exception-with-zend_session-while-unit-testing/ https://phpprotip.com/2009/06/headers-exception-with-zend_session-while-unit-testing/#comments Tue, 30 Jun 2009 14:57:18 +0000 http://phpprotip.com/?p=154 While the manual for Zend_Session does discuss unit testing and the read-only exception, it has no mention of an exception I encountered recently while unit testing. I admit that the reason I encountered the exception is most likely because I’m Doing It Wrong. However, given reality, I did not have time to properly make the class, or at least do it better. I received the following exception:

exception ‘Zend_Session_Exception’ with message ‘Session must be started before any output has been sent to the browser; output started…’

The problem was, of course, that the feedback from previous tests was already outputted to the screen. I could’ve solved this by playing with my test suite and just starting sessions at that level but that wouldn’t have been the best solution. In fact, I’d qualify that solution under bandaids (solutions that mask a problem instead of fixing them). If you can’t see why it is a bandaid, I’m happy to discuss it but for once, I”m going to try to stay on topic and not digress any further than I have.

So, here’s the scenario:

  • not enough time to refactor the class so that sessions are only called/created when necessary
  • sessions are being called because we’re testing some auth stuff which relies on session information, we might not be able to do DI (see above)
  • we want to minimize contributing factors to test failure so session has to be called/destroyed for the tests that need it, all other tests should never have session existing

The solution? A little ‘undocumented’ static variable:

Zend_Session::$_unitTestEnabled = true;

Ok, undocumented is a bit misleading. You won’t find out about it by looking at the Manual but will find it when you’re digging through the API. So it is documented, just not well. I’m guessing because it is rare to encounter the exception. I’m not surprised that I encountered it since my projects always seem to have some degree of weirdness, which makes for an interesting learning curve thats compounded with Zend’s curve.

]]>
https://phpprotip.com/2009/06/headers-exception-with-zend_session-while-unit-testing/feed/ 1 154
zend_log_exception ‘bad log priority’ https://phpprotip.com/2009/02/zend_log_exception-bad_log_priority/ https://phpprotip.com/2009/02/zend_log_exception-bad_log_priority/#comments Tue, 24 Feb 2009 18:43:28 +0000 http://phpprotip.com/?p=117 I’m writing this post because there are a few times I’ve gotten this particular exception and then look at the trace and can’t figure out what’s wrong. More often than not, I’ll get to the line in the trace and be like, “wtf! there’s no priority here. It’s a method call not a constant”. This turns into, let’s see if something is happening before this method is called and finally comes down to looking at the Zend_Log source and remember, “oh yeah, Zend_Log allows you to use log by priority name as a method in lieu of using the log method” and what I once thought of as slick when I read the documentation turns into a waste of a few minutes and added amount of aggrevation. So to save myself and others some time and aggrevation, I’m going to go into a bit of detail as to why you may be getting this exception.

Take the following for example:

// assume taht $log is a valid instance of Zend_Log
$log->addEventItem('foo','bar');

It looks like it should work, right? It won’t because the correct method call would be

$log->setEventItem('foo','bar');

As I explained in the introduction, the ‘bad log priority’ exception will be thrown for this sort of error. This error will occur because Zend_Log overloads the __call function so that you can do

$log->priorityName('message');
// instead of logging with the log method
$log->log('message',Zend_Log::PRIORITY_NAME);

So if you’re like me and get this exception but only see a method where this error is being thrown, you now know why and hopefully be less confused and aggrevated.

I wish I could provide a solution to this issue but I see no way that Zend_Log can contextually tell if you’re wanting to use the priorityName shortcut or not. This only leaves the option of removing the the priorityName shortcut entirely, which will break somebody’s code. The shortcut is nice because of its flexibility but definitely a case where flexibility can increase complexity or rather, flexibility leading into complications that require complex understanding. I haven’t had time to read all the arguments in the comments on the flexibility/complexity issue that Federico Cargnelutti brought up recently to have an overall opinion on the matter but in regards to Zend_Log, the flexibility should’ve been left out. I would’ve preferred that Zend kept it simple and just made log the only method of logging. Or maybe I’m an edge case that logs more information than the initial event items give me.

]]>
https://phpprotip.com/2009/02/zend_log_exception-bad_log_priority/feed/ 4 117
openid seems to hate me https://phpprotip.com/2009/02/openid-seems-to-hate-me/ https://phpprotip.com/2009/02/openid-seems-to-hate-me/#respond Thu, 12 Feb 2009 19:40:04 +0000 http://phpprotip.com/?p=115 been trying to comment on Chris Shiflett’s post on the twitter “Don’t Click” debacle and can’t seem to get authenticated through openid. so having to post my reply here (below).

cavaet: i’m not an expert on anything and a n00b at a lot of things

liked the article, however I want to disagree that it isn’t a csrf attack since “The attack works by including a link or script in a page that accesses a site to which the user is known (or is supposed) to have authenticated” (according to wikipedia [oh no, i’m that guy. *sigh*]). @ramsey said it didn’t affect him because he wasn’t logged in on the website.

It seems to me that it used clickjack ui redressing to carry out the authentication exploit.

Want to know the funny thing? The only reason I logged into the website was to follow @shiflett.

]]>
https://phpprotip.com/2009/02/openid-seems-to-hate-me/feed/ 0 115
string searching, you’re doing it wrong https://phpprotip.com/2008/12/string-searching-youre-doing-it-wrong/ https://phpprotip.com/2008/12/string-searching-youre-doing-it-wrong/#respond Thu, 18 Dec 2008 15:01:35 +0000 http://phpprotip.com/?p=86 First off, I’m not trying to be a complete jack-ass, just a helpful one. This article, by Stefan Ashwell, popped up on my news feed and I wanted to comment on it but can’t remember my login for the site and after 10 minutes of waiting the password reset email has yet to arrive. The non-arrival of the password process is irritating me and shows in this article title and my tone.

In the article, Stefan shows how strpos or stripos to locate a desired string or block of text.

The example he gives is as follows:

if ( stripos($sentence, 'string') ) {
   // yes it does
} else {
   // no it doesn't
} 

The problem with this example is that it will yield a false positive. This is a common mistake made by a lot of people. If we examine the php manual entry further we see, “Returns the numeric position of the first occurrence of needle in the haystack string.” The key word being numeric. This means if the string position is 0, then the expression ( stripos($sentence, 'string') ) will evaluate to false.

EDIT: Expanded explaination on why this can yield a false positive. If the string your searching for is at the beginning of the sentence, then the position returned is 0. When php reaches the statement if ( stripos($sentence, 'string') ) it interprets the return value (0) as false.

Here is a more expanded example:


$eval=(stripos('The quick brown fox jumped over the lazy dog','The'));

echo '($eval) : ';
echo ($eval) ? "pass\n" : "fail whale\n";
echo '($eval==0) : ';
echo ($eval==0) ? "pass\n" : "fail whale\n";
echo '($eval===false)';
echo ($eval===false) ? "pass\n" : "fail whale\n";
echo 'eval is '.$eval."\n";

/**
output is:

($eval) : fail whale
($eval==0) : pass
($eval===false)fail whale
eval is 0

*/

As you can see, if you want to properly search for a string using stripos or strpos, you must test for the boolean value of false ($eval===false). Alternately, you can use regex, if you’re comfortable with it. I’m of the opinion that learning some basic regex doesn’t ever hurt you.

I want to re-iterate that I wanted to leave this whole post as a comment but that doesn’t seem possible right now since that email has yet to arrive and the article requires login for commenting.

]]>
https://phpprotip.com/2008/12/string-searching-youre-doing-it-wrong/feed/ 0 86
Zend_Log quickstart https://phpprotip.com/2008/12/zend_log-quickstart/ https://phpprotip.com/2008/12/zend_log-quickstart/#respond Wed, 17 Dec 2008 18:54:15 +0000 http://phpprotip.com/?p=74 Lately, I’ve found that I need to create a more robust logging system for both audits and debugging. I found a great logging primer from DevShed that offers some good insight into going about making a more robust system. Other than the theory, you shouldn’t really take much more away from it since, as one comment points out, the implementation is poor aka globals are bad. Caveat: my implementation probably won’t be all that great either but I hope to avoid making beginner’s mistakes.

That being said, the reason this particular article is centered on Zend is because I’m pretty much in love with Zend right now. The main reason for writing this article is that, while the Zend documentation on Zend_Log is thorough and easy to understand when you read it, I hate back and forth between the sections of Zend_Log to make sure I understand what I’m needing to do.

I’m assuming you have at least gone through the Zend Quickstart before reading on. For my filesystem and db configuration, I use Zend_Config to load up settings such as the logfile name and log database adapter. I could’ve set the path for the file but I want a certain degree of flexibility.

At this point, I have the logger configuration from zend configĀ  and the db adapter so let’s move on to some code examples. This is partially taken from my in-progress class.

making a full filepath:

$filepath=(isset($options['FilePath'])) ? $options['FilePath'] : INC_PATH."/".$this->_systemConfig->system->logfile;
$writer = new Zend_Log_Writer_Stream($filepath);

the filepath is used with the Zend_Log_Writer. Next we set a format for the writer and then instantiate Zend_Log with the writer

$formatter=new Zend_Log_Formatter_Simple($format);
// specify format
$writer->setFormatter($formatter);
$logger=new Zend_Log($writer);

Note: $format is a text string that indicates how each log entry will appear.

The important things to remember here is that Zend_Log creates an associative array with all the basic useful log information. This array can be accessed in a variety of ways. For my purposes, knowing what is accessible by the stream and database writers are important.
If you have read the documentation thoroughly, you will have found that in section 30.1.6 Zend documents this array expressly. Unfortunately, unlike some most of their other documentation, this useful bit of information is almost secreted away. I’ve scoured the docs a lot to find the keys created by Log so here they are as a quick reference.

  • timestamp
  • message
  • priority
  • priorityName

These little gems are pretty much the keys to the Kingdom of Zend_Log.
If you want to reference them for formatting in a stream, you can do something like:

$format = (isset($options['LogFormat'])) ? $options['LogFormat'] : '%timestamp% '
.PHP_EOL.'%priorityName% (%priority%)'
.PHP_EOL.'%message%' . PHP_EOL.PHP_EOL
.str_repeat("=",100). PHP_EOL;

or if you need to use them for your db, you can use set column mapping like so:

$columnMapping = array('lvl' => 'priority','Priority'=>'priorityName', 'msg' => 'message');
$writer = new Zend_Log_Writer_Db($db, 'log_table_name', $columnMapping);

That should cover the basics.

Pro-tip discussion: For auditing, you may want to make separate log files for access,create,and changes made to your app/system. Error logging should log everything into files, but a separate debug copy would probably out in the development environment. I usually do a tail -f on debug/log file. It seems obvious to, me that any logging/exception system you make should have a simple outside error handling function to alert you of that logging broke. I believe this can be done by setting the error handler in the constructor. Haven’t played with this yet. It seems to me that any robust logging system you implement will run into a chicken vs the egg type problem

]]>
https://phpprotip.com/2008/12/zend_log-quickstart/feed/ 0 74
INSERT INTO `table` (`column`,`col2`) VALUES isn’t completely worthless https://phpprotip.com/2008/11/insert-into-table-columncol2-values-isnt-completely-worthless/ https://phpprotip.com/2008/11/insert-into-table-columncol2-values-isnt-completely-worthless/#respond Fri, 14 Nov 2008 21:03:55 +0000 http://phpprotip.com/?p=59 In most cases, when doing an insert statement I use SET to increase readability. It is also nice because I can make dynamic statements with insert/update. It is because of these two reasons I never saw any value (for lack of a better term that isn’t punny) to using VALUES. That is until I ran into a situation where I wanted to have a database level solution as opposed to making an application layer solution. The situation is as follows:
– create an entry in the parent table
– create entries in the child table that depends on the last insert id of the parent table.

Now that I think about it, there may have been a way to do it procedurally in SQL but the first solution I was stuck on how to make my next INSERT statement fulfill my criteria and be readable. This is where VALUES comes in. By using VALUES instead of SET, you can do a multi-row insert statement.

example:

INSERT INTO Resource SET ModuleID=LAST_INSERT_ID(), Name='contact', Description='Contact resource in the default module';
/* multi-row insert */
INSERT INTO Privilege (ResourceID,Name,Description) VALUES
	(LAST_INSERT_ID(),'*','All privileges for this resource'),
	(LAST_INSERT_ID(),'browse','Browse only privilege for this resource'),
	(LAST_INSERT_ID(),'read','Read only privilege for this resource'),
	(LAST_INSERT_ID(),'edit','Edit only privilege for this resource'),
	(LAST_INSERT_ID(),'add','Add only privilege for this resource'),
	(LAST_INSERT_ID(),'delete','Delete only privilege for this resource');

So now, VALUES isn’t completely useless after all.

]]>
https://phpprotip.com/2008/11/insert-into-table-columncol2-values-isnt-completely-worthless/feed/ 0 59
SXSW https://phpprotip.com/2008/08/sxsw/ https://phpprotip.com/2008/08/sxsw/#respond Wed, 20 Aug 2008 12:49:37 +0000 http://magic.garciawebapps.com/?p=10 So after reading this post, I want to go. There’s a list of other things that seem interesting to. At a glance this guy seems cool and oddly familiar. The name reminds me of some of the DJs I knew in PBS when I was at Purdue. So if anyone is going, vote for them. I want to hear audio on this at the very least.

]]>
https://phpprotip.com/2008/08/sxsw/feed/ 0 10