States With Abbreviations in PHP
To whom it may concern… and that person probably is me… here is a list of the 50 US states in array form, nice and easy to copy+paste into your PHP code.
These entries are about PHP so they’re tagged with the “php” tag.
They’re likely coupled with other framework-related tags like the Laravel, Symfony or Zend Framework tags.
To whom it may concern… and that person probably is me… here is a list of the 50 US states in array form, nice and easy to copy+paste into your PHP code.
I’m a huge fan of the live-server package for running local HTML servers to test my HTML and Javascript code. What about if you want to run a local PHP server quickly to test something? That’s easy. But I tend to forget the exact command - so I came up with a ZSH-based solution.
If you’re going to use an Action pattern for your application, be careful what you expect coming in as input. In fact, input should be loose and output should be tightly coupled. Let me explain…
I love PHPStorm, but it can only do so much. Even with plugins like Laravel Idea, you may still have some missing features. One that I wish I had was autocomplete of models from collections or paginators in blade files. Well, turns out there’s an easy enough way to add this functionality for yourself.
I love Laravel request classes for validation. You should be using these whenever you can! But sometimes, writing the rules seems redundant between store and update. There’s a quick fix, though.
The prepareForValidation()
method is really useful in Laravel requests: it helps modify the incoming data so that validation might be easier. But you need to be careful that you implement it correctly and don’t mess up your data. Let me explain.
“Do you even lift, bro?!” What a way to ask if you work out while simultaneously insulting you. Well, maybe I shouldn’t have named this “do you even sprintf” but it really surprises me how many PHP devs forget about (or don’t even know about) this useful tool - and instead do some pretty icky looking string concatenation. Let’s take a look at what sprintf()
can do for us.
I love using Policies in Laravel. A particularly useful feature is the interception of checks. But what if only some of our policies need that? That’s where we can judiciously use traits.
What’s the difference between unit test, integration test, and a feature test? Which should you use for what type of test? Is it just preference or does performance factor in when using Laravel? Let me give you my take from over a decade of unit testing experience.
There seems to be an endless debate: clearly written code doesn’t need comments vs comments are needed to explain code and give context. I can see both sides of this debate, but there is a middle ground. Let me show you one way.
The question is this: When creating a helper method in PHP, should you use a named function in the global scope, or an anonymous function assigned to a variable?
The State of Security of Laravel Apps in 2021 is a whitepaper based on the quiz submissions from Laravel programmers.
What if you need to see your config quickly in Laravel from the command line? And you don’t want to use Tinker? Let me show you how I do it…
First off, if you can use something like mailtrap I definitely recommend doing it. Mailtrap provides credentials and configuration so you can capture all of your email into a test inbox. But if that’s not possible, there is another option - and it has to do with Laravel’s mail events.
If you follow the instructions to customize the configuration of Bugsnag’s Laravel package, they’ll tell you to run vendor:publish
. But this is not what I want.
I use Laravel Nova in a lot of my projects, but I’ve never liked the idea of storing the files in a local directory after download. Yes, you can use credentials for a Composer-based install, true, but I wanted something that didn’t require that. Turns out you can install packages like Laravel Nova from a zip file locally. Here’s how.
I’ll say it again: do not install Laravel Tinker in production, and certainly do not use it. It’s a great tool to do work in your application, but only in test and development environments. That’s why I only install it in my require-dev
section of my composer.json
file.
Laravel Hacker is no longer a brand. You can find my security work at MasteringLaravel.io/security
Laravel is a great framework that is pretty secure by default. However, configuration mistakes or coding errors can still leave your app open for attack. Where do you go for help?
I’m not a huge fan of todo
comments in code because I think they’re mainly forgotten. However, I don’t have the same opinion for PHPUnit tests. Let’s talk about why - and how to easily add them in your code.
When given a choice of methods and ways to do something, it might not be clear which way is the best. As programmers, we tend to pick the easiest, then. However, the easiest can have security implications. Let me illustrate why we should use more stringent controls in a Laravel project.
Since you’re a programmer, you’re always looking for ways to be a bit more efficient. Because of this, it can be easy to fall into the trap of being too programatic, too calculation-heavy in your unit tests. But, this isn’t a test then - its just another block of quite fallible code. Let’s talk about why and show what to do instead.
When your unit test suite gets larger, it can take quite a long time. One of the many ways to speed this up is to hunt down and fix slow tests. Let’s use PHPUnit’s test listeners to do just that.
It’s great to run code coverage at the very end before you push your changes. This gives you some idea what’s tested and what’s not. But you don’t have to wait till the end; code coverage can help you all throughout writing your test suite, too.
I’m a sucker for those little badges at the top of the README files in Github repos. I know you can get them from external services, but could I host my own? Let’s find out.
Please stop using assertDatabaseHas
in Laravel. There are many reasons why this is bad, and there are better options available. Let’s find out why.
Currently, there are two pretty common packages for interacting with your database: Eloquent and Doctrine. Eloquent is part of Laravel and Doctrine, while used often on its own, is usually referenced with Symfony. If you’ve come to read this article, you’re probably versed in Doctrine and wondering why you can’t just - or shouldn’t just - use it with your new Laravel project.
tldr; Using Sqlite in Laravel (or most PHP apps) for unit testing causes false positives in unit tests. Things that work will not work when you move to production and use a different db like MySQL. Instead, spin up a test database that is the same tech and engine as your application will be.
Open source software is wonderful for many reasons. One of the best is we can see and inspect the software for vulnerabilities. But, far too many people actually do this. Let me demonstrate, using a Laravel package, how this lack of review might backfire and cause you grief.
There are a lot of debates about trying to achieve test coverage of 100%. Some people swear you need to do this. Others say, get 80% or more… the rest doesn’t matter. Each side has strong arguments.
Sometimes it makes sense to filter user input before it goes to validation. If you’re using controller-based validation in Laravel, this is pretty easy. But, if you’re doing your validation in request classes, your approach needs to be different.
The average webpage seems to contain tons of bloat and increase in size - and this is no good. I decided that I wanted to create a proof-of-concept website that would act like a single page application that didn’t require a framework like Vue or React. I only need to support the latest evergreen browsers.
There’s a struggle to balance the easy-to-use Laravel helpers and functions with very verbose, complicated methods in unit tests. As I’ve been relying on Laravel’s way of doing testing more, I’ve ran into a couple of gotchas that I should share.
There are tons of ways to answer this question each with its own benefits. Let’s check out a few.
Turns out there’s a few different mechanisms to remove a package from your composer project. It’s important to understand what each method does and what its side effects are.
Laravel has a built in request helper called wantsJson()
that determines if the request is requesting JSON with the Accept: application/json
header. But, what if you want to only accept JSON responses? I set up a Laravel middleware that rejects anything that isn’t JSON.
One of the lesser known pieces of functionality from Composer is the ability to create a project from skeleton/scaffolding. This ability allows you to create a project structure, directory, files and requirements based on the suggested setup from the project maintainer. A common installation mechanism of Laravel uses this functionality. (Even I use it to save time and set up my own custom configuration for new project skeletons.)
By now, you’ve probably written many database migrations in Laravel. But, then something else happens. Perhaps your business model changed, your data attributes changed or you’re just refactoring to a stronger architecture. Doesn’t matter which, you’re going to need to convert and migrate some data.
Whether you’ve made the class yourself or you’re using a pre-made SDK, there are times when the construction of an object might be expensive. Expense, in this case, pertains to memory, time, CPU cycles, basically anything that is above baseline.
When you’re creating cookies on your server side application, it’s good security practice to flag the cookie as HTTP Only. This way, it instructs the browser that it should sandbox this cookie from the client side scripts. It still will send it between client and server on each subsequent request, but javascript can’t access it directly.
I started noticing a disturbing trend on one of my projects: developers were doing too much logic in the setup
and data provider methods of their PHPUnit tests. However, before we could address this, a “limitation” popped up which helped them kick this habit.
In an earlier post titled Use $this->fail()
with Mockery::on()
, I explained the challenges of debugging a failing test with the closure passed to Mockery::on()
. Instead of returning false
, I opted to use $this->fail()
- which seemed like a good idea at the time. After all, I was doing my test, then failing with a useful bit of information. (Previous to this, it would just say that you don’t have a matching handler for this assertion, which was really confusing).
Measurement is important. Metrics, while not sexy, are concrete to a good business strategy. When you bring a problem to your superiors, they’re going to want to know what is your measurement, what metrics did you use to determine this is a problem. With tasks I’ve given developers, I’ve always said “show me the metrics that your fix is better” versus just looking at the code.
When someone breaches the security of a web app, sometimes it’s not discovered to weeks or months later. There are a number of tools that specialize in intrusion detection, but they may be costly or difficult to set up. Another idea is to use a canary in the coal mine or a honey pot. Here we’ll talk about the concept and then demonstrate some easy and quick methods.
Laravel has a lot of the most common functionality built into the framework. However, decisions need to be made to balance the needs of the majority of use cases with the stability and agility that programmers need. No one really wants a bloated library. Because of this, you might find that you need functionality that is not directly built into Laravel. When I started working with Laravel-based CSV responses, this was the case. (This article is based on Laravel 5.6.)
How often have you heard this phrase?
The other day I was looking for an image from one of my iMessage chats. When you browse through the attachments on the iPhone, it takes forever to scroll through them. At one point, I kept having the iMessage app crash as well (I think I was maybe 400 or 500 images into the history). Turns out, if you have your iMessage and iCloud accounts configured properly on your Mac, you’ll have duplicate copies of all the attachments (for at least the messages you haven’t deleted) on your Mac as well.
For some API work in Laravel, I wanted to validate that the incoming request parameter was a boolean value. At first I tried using the built in boolean
slug validator but it didn’t accept all of the ‘boolean’ values I wanted to use. (Also there were weird scenarios where string values of false
were triggering as true - like what I wrote about here.
You can make use of guarded or fillable attributes in Eloquent models in Laravel to help control what values you might allow to be updated via your API. But, I wanted to go a step further and actually stop certain values from being passed in. You could go pretty wild with this and try to block everything, but that’s not what I did. I made this validator.
If you check out array_filter
without a callback, you’ll notice that it will basically check each array key to make sure it doesn’t equal false. If you have an object, you get call of the properties as an array using get_object_vars
. This quick snippet will allow you to look at an object and verify each property is non-false (or non-empty).
This isn’t a one-size-fits-all suggestion, but it’s a start to help you think about how you actually interact with factories in Laravel. They are used for test data, and are ran very often, multiple times in a row. You don’t need as much random information as you need. (In fact, a lot of times I see people overusing Faker even.)
I wrote instructions in 2011 to add a PHPUnit Listener to Watch for Long Running Tests which seem to be a bit out of date now. But, here’s a quick refresher:
I’ve used the anonymous self-executing paradigm a few times in JavaScript over the years. Something like this:
For testing, I tend to use Postman - which gives you the option to view your API JSON responses in a preview mode (interactive), pretty and raw. But, the other day I heard someone saying sometimes they just want to invoke pretty print in their JSON responses without having to use an external tool and set up a whole environment.
It’s hard to come up with a title for this - but - basically I found some rogue code the other day that I thought was pretty interesting. I was fixing a “hacked” website when I came across the source of the symptoms of the hack. One file had the following code in it:
In Laravel, the Support\Str
class has a lot of useful methods for switching formats of strings between each other. I needed to take a hyphenated slug and change it to title case words. In Laravel land, I think this is referred to as “Studly” - because I found something very similar called Str::studly()
. This converts underline or hyphenated words into a single string with capital letters. I wanted to not concatenate all of these.
I think around 2015, there was a big splash of good training online for PHP. Frameworks upgraded/changed, helped programmers write better code faster earlier than that. Before that, it was a lot of RTFM. So, before, in the earlier days (maybe somewhat still today), I think PHP developers did this:
Often times, I find myself targeting a single file with PHPUnit by specifying the file after the binary in the command line:
It’s important to unit test your application code - even your console commands. So many times, I’ve seen people using the Artisan
facade inside of console commands to either queue up new commands or call a different command. This makes it more difficult to unit test the application - you have to rely more on fakery (requiring you to reset your application each time then) and/or integration tests.
As a PHP programmer, I struggle to understand the reason for private methods and properties. Now, don’t get me wrong, I know the official explanation for them: “Use this to hide properties and methods from child classes” - but why? There have been a number of times when I’ve done stuff that is way more of a cluster-fnck because of private methods that I couldn’t slightly modify.
From time to time, I get thrown onto a project that has many, many errors in the unit tests. It can be hard to try to figure out what to fix first with so many errors on the screen. Sadly, I’ve had my scroll-back buffer filled many times.
Just another case of RTFM I’m sure, but I was wondering how to preview the changes that will happen if I do a composer update
on my current project. I wanted to get an idea of how many libraries would change so I could see if it would be a short or long project (potentially) to do a 3rd Party Library update. (I already hear you - and I agree - the number of files changing isn’t always indicative of how long the task to update your project’s dependencies will take. Shhh - quiet you.)
When you’re testing inside of your PHPUnit test methods, you will use many assert-based methods. Two that are seemingly very similar are assertSame()
and assertEqual()
One thing I like about Laravel is the amount of built-in functionality that is available. But when this functionality is left in default configuration (much like many default configuration items getting hacked), there can be consequences.
I’ve written a few helpful methods and systems that help out my unit testing. There are many arguments for and against these tools (don’t test protected methods, don’t introduce global namespace methods, etc) - and those are discussions for another day - but perhaps these might help you out in the mean time.
When PHP errors happen, often times there is an error log. This might be in the PHP error log itself or in a log file. For example, in one of my Laravel projects, I have two log files, one for errors and one for info or debug level information.
In my Laravel application, I have an end point that will retrieve a collection of Client models. I have many other unit tests that validate that my repository returns the proper clients when requested, that my client model is sound. My last test is a feature test checks that if I retrieve a list of clients from the end point there is proper pagination and client models exist. I don’t really need to test the exact values because I know this will work - from all my other tests.
If you deal with integers, you validate them, right? You make sure they’re a valid integer? Well, what about the value 9223372036854775808
? That’s right, that’s one more than the PHP_INT_MAX
on a 64 bit system.
When you have a more complex assertion you need to make on the parameters of a mocked object, you might use the Mockery::on()
method. It can be hard to tell how this fails, though, because if the assertion fails somewhere, the message is confusing - it basically says that there was no matching call to that method, which is technically correct.
A nice feature of Laravel is the ability to add a listener to the DB
object’s events (or SQL queries). I’ve seen some people add this, then comment it out when it’s done, then un-comment it if they need it again. I don’t like that - I don’t want commented code in my files (also that’s why we have version control).
A pet-peeve of mine is pagination that doesn’t work properly. One that I ran into lately with Laravel is related to the pagination system it has built in. I was able to request pages that were larger than the last page with no discernible error. So, I decided to write a middleware to handle this issue for all of my content.
Sometimes it’s the little things that get you. This is more of just a reminder than anything else. One of the fun quirks (and I hesitate to call it a quirk because it’s technically working as defined) in PHP.
I’m guilty of creating stub-like classes in my tests to unit test traits, sometimes. So, you end up with a special class inside your unit test file, perhaps at the bottom, that is empty but only extends the trait or something like that. This is not a good idea, but it was my only way that I could figure out how to unit-test traits separately - especially if they were made of protected methods.
Every PHP programmer knows you can’t extend multiple classes with PHP. You can only do one - which is fine. In fact, if you need more shared code, make sure to focus on using traits instead.
I hate to admit it, but I do like Laravel’s Tinker package. Sometimes, just testing out your relationships on the command line before you go further is super helpful.
Normally, when I write unit tests, I don’t use Laravel’s facade and fakery methods. I do a lot of injection of services, but in one particular case, when working with the Queue system, I had to use the facade for faking the queue and asserting some jobs were pushed.
If you’re not using Swagger (or OpenAPI) yet to document your APIs, you should start. It’s pretty simple to get started - especially in PHP. I recommend using the swagger-php package - it’s pretty easy. Just use annotations, and then generate the Swagger definition when you’re done.
Have you ever submitted a debug log for a piece of desktop software? I’m always enthralled at the sheer amount of information that is included in some of these error reports. It reminds me that I don’t do enough logging. As a matter of fact, I think most PHP developers don’t do enough logging.
I’m a huge fan of the service architecture paradigm - and that means that I use services in my controllers to handle persistence. I wanted to abstract the add and update methods from my services and put them into an abstract class. In addition, I didn’t want to have to specify the exact method - I just wanted to call save
on the entity. Finally, I wanted to log it properly and verbosely.
I love namespaces in PHP as much as the next programmer - but there’s always been something about namespaces in my own applications that bothered me. And that’s when I have similar or identical named services, forms, entities or models.
One of the things that was really bothering me when I first started using Gearman was my consistently failing doctrine database connection.
I can’t help but think a lot of PHP applications have a problem. These beautifully crafted, object oriented, highly engineered applications are still making one vital mistake. And that’s using one of the various templating libraries or languages that PHP has.
I’m a big fan of PHP DotEnv for creating my environment variables for my scripts. (It’s always a good thing to keep your passwords and credentials separate from your source code, according to OWASP).
I’m all for coding standards and rigorous approval processes for software in app stores, I really am. However, I’m currently responsible for creating a number of different CMS plugins that all share some code. Unfortunately, that shared library will never follow the coding standards and requirements for all app stores - each has some differences. That’s why I created…
If you haven’t been following my twitter feed or my open source on github, you might not have seen that I recently released PHProblemLogger, an environment and run-time logger designed to help log everything during an error condition.
Every year, they come out with a list of the top 20 most used passwords and it makes me wonder… how many users on any one of my websites are using those passwords?
From a very young age, we’re told to brush our teeth regularly. We know we should, but it can be a struggle. The reasons to invest our important play-time aren’t always compelling. (If they were, why would some parents have to check to make sure the children had brushed their teeth before bed?)
When I went to a University for a Computer Science degree, a required class was Introduction to Java Programming. I remember the first thing the professor taught seemed very confusing at the time. I can still hear his voice very clearly: “So to begin with, we’ll type… string string equals new string.”
When I was growing up, having chocolate milk was a huge treat. My mom would mix together some sugar and some dry cocoa powder into the glass and then slowly add milk. After some more vigorous stirring, I had my small glass of chocolate milk. It was quite the process, but it tasted great. Imagine my surprise when I found out that chocolate milk also came from the store pre-mixed!
“Trust falls” are a team-building activity that some of my friends have had to endure. I’ve been threatened with this exercise a few times. But, I’ve never had to do it. Luckily, I’ve been able to convince my team members I will participate without having to test their bicep and shoulder strength. Or, perhaps I’m just not trusting enough. (I once worked at a place that had a few employees that were really good friends and would force-trust-fall on each other. When a group of colleagues were walking in a row, one would just throw himself backwards into the person behind him surprising them and shouting “trust fall!” This was the only “trust fall” that I was forced to participate in.)
Here is a PDF download of the presentation I made at the Greater Milwaukee Area WordPress Meetup.
I like to think that I’m somewhat of a PHP purist. And, when I travel to user groups, one of my favorite talks to give is named “Tell Aaron What To Do.” Basically, the goal is to solve two problems I pose using plain HTML and PHP. Oh, and do it with core PHP, no frameworks, no libraries, just plain vanilla PHP. At the end, I’ll run a number of integration and security tests against the code the group has written to see if we were successful.
I’m going to say something that I never thought I’d say in my life. In fact, I’m not sure that a single programmer has ever said this! Ready?
In the last decade or two, the US proliferation of low quality reality television shows has been unstoppable. “Big Brother” would be ashamed by some of his siblings. There are shows that follow famous people (although, I’m not entirely certain why some of them are famous), shows that involve the audience, shows that support nerds; basically anything you can imagine! I pretend I’m above this, I surely don’t fall into the category of people who sit at home and pine over “The Bachelor.” I normally flip the channel right past these shows.
Every leader has a particular methodology or key point they focus on. Whether it be a small detail, a general philosophy or a repeated phrase, you know that if you are near that leader, you will become very familiar with their demand. In my team, my demand is to pay attention to detail.
In an earlier column, I discussed the advantage of using longer and more verbose variable and method names. When you program using this more descriptive style, the code is easier to understand and more maintainable. However, a short and concise method with a revealing name may not always be sufficient when it comes to complex processes. To fill this gap, PHP has comments.
Bugs in code suck. It’s bad enough when you misspell a function or forget a semi-colon. That’s embarrassing and annoying. But what’s worse is when you write code that seems to work fine, is syntactically correct, yet still has a bug. You know you did it right, but somehow it’s also wrong. That’s not good. That makes me paranoid and second guess the rest of my work. That doesn’t help me be a Confident Coder at all.
There are two reactions to reading a new section of code for the first time. Sadly, one of the most common seems to be of confusion, dismay, followed possibly by some sort of expletive (or many, depending on the length of the code). The other is one of the most beautiful reactions, the most flattering, the most sought after reaction: “Oh, that makes sense” or “That’s cool.”
Sweaty palms, a fast heart rate and an overwhelming sense of dread.
Let’s talk a little bit about session fixation in PHP. Such a fun topic, right? Tons to get into here. But, let’s just touch the surface on two VERY SIMPLE things you can be doing now to make sure that your website is safe.
At Small Shops United, we use MadMimi for our email list software. I took a look at the PHP libraries that were available and found them extremely out of date, lacking, and just plain not working in certain areas.
I’m a huge fan of tools like PHPUnit. Or any other tool that will help my project carry on.
Well - I really couldn’t think of a good title - it’s really not catchy at all.
I’ve been working with Pimple Dependency Injector lately, and I’ve come up with an interesting question.
I’m so used to PHP’s liberal allowance for single and double quotes, that I forget that other languages and tool-sets don’t play that way. Case in point, my most recent error:
Today, I was working with a custom form themed symfony / twig project. The previous developer had developed a bootstrap based theme (yes, this is an older Symfony project at this moment - I think this is a bundled theme now). I was struggling with the block field_row
item. Inside of this, there was a call to form_label
passing in just the form view again. I was setting a custom label on the form_row() call in the main template, but nothing was happening.
So I’m going to try this new thing - watch a motivational quick movie in the morning via youtube. I made a playlist of videos and have put the following code in cron for 5:30 every morning. It will send an email (which is actually email to txt on my phone) with a link to open the youtube player on my phone with a random item from my playlist. Hope you find it useful!
Oh, PHP - your love affair with arrays is like no other language. You can always tell if someone learned PHP first before all other programming languages. They think, design, and talk in arrays. Have a list? Make it an array. Have a heap? You mean array, right? Collection object? Naw, I’ve got an array right here.
I created this Udemy course a while ago - but unfortunately they said it was too short and the audio was too poor. In order to post the course, I’d need to add another 10 minutes of fluff and get a better microphone. I decided just to share with you.
I actually very much enjoy spreading “the word” on PHP. I go to a lot of conferences, and present a lot. One of the most interesting concepts I’ve developed lately, however, is not a presentation but more of a group coding session. This is how it goes…
This means that: how to translate between PHP and System-i lingo.
Just finished a talk at the Wisconsin Midrange Computer Professional Association and wanted to share the info. This particular talk was an introduction to PHP.
Finished presenting today at MidwestPHP 2013. My talk on Enterprise PHP Architecture through Design Patterns and Modularization went great - at least I hope!
One of the things I struggle with is the validation of data objects. I submit that there is such a thing as a dumb data object and a validation domain object. The validation object could also be some sort of helper or a service I guess. But, the point is, that the main data object doesn’t have validation on it. It has coupled objects that provide that validation.
I was doing some code challenge review for an open web developer position I have for my team, and I came across one piece of code that made me smile.
There are two things that really grate on me as a PHP developer. First, people claiming that PHP is not powerful. And second, those who don’t actually work in the language, but have similar disciplines, trying to teach it. Let me elaborate.
This is a weird one… I had a form in the body of my page. Every time I would submit it, the csrf token would not match.
One thing I’m really passionate about is using PHP in enterprise situations. I obviously care about Design Patterns in PHP. I’ve also done a lot of technical review of other books about refactoring away from bad code.
I tend to want to use PHP Exceptions when I can. But, I don’t just leave them as is. I tend to have a large custom exception library. These exceptions extend the base Exception class in PHP - that’s about it.
I’m currently at ThatConference here at the Kalahari Resort, in Wisconsin Dells.
I just finished glancing over Real-World Solutions for Developing High-Quality PHP Frameworks and Applications. I gotta say it…
I have a new love affair… PHP’s DateTime object. I’m not sure when it started, but it’s going on strong now. If you haven’t taken a look at it, I invite you to run over there now and just look at the methods. If that isn’t enough, let me give you a bit of example code… see if this makes you really want to do it:
I was looking at mock objects in PHPUnit the other day and started to get confused. When I asked for a Mock
object, the entire object was a mock. In all actuality, it wasn’t so much a Mock of the object but a complete shell of it.
So, often I have to show a masked credit card on the screen. However, I really want to go the extra mile and show the user a secure, fully masked credit card number that still reflects their original card. For example, if their credit card number is only 15 numbers long, I shouldn’t show a 16 character long string. So, I’ve developed this code snippet:
I’m not entirely certain why this escaped me for so long, but it’s remarkably easy to set terminal colors with PHP.
I no longer work for LPi and do not know what job openings are available.
Do you like to be challenged, learn new things, and have a supportive team? Well, let’s chat a bit. I’m building a team and I’m looking for great PHP developers to join it.
You may find while working with projects like Zend Framework that you have a number of publicly available properties of your classes that are not defined and documented. They might be part of a getter/setter magic method or just purely dynamic. Well, using PHPDoc, there is a cool tag called property that helps. For example…
When generating a CSV file with PHP in the UTF-8 encoding, Microsoft Excel freaks out. It just doesn’t show the proper encoding. Thank you Microsoft! However, I did find a way to handle this encoding and make it compatible for Windows/Microsoft Excel.
While I’m infinitely happy that all uses of a class in PHP now are references, that’s just not good enough. Sometimes I want to use my newly created object in many different methods. I have two options. First, I could create it as a Singleton, and always call the instance getter. Or, I could use an object cache.
So, if you’re not familiar with CSRF, check out this blog post about AJAX Security. Some of the steps talking about Cross Site Request Forgeries will help you understand the problem.
A nice free open source alternative to Crazy Egg is ClickHeat. One of my clients wanted this implemented but didn’t want to have to log in again using different criteria. I looked at the code and saw it was surprisingly easy to edit to allow a different authentication method. Let’s check it out:
When developing an application, there are usually various different environments that you run the code in. First is the development environment. Next, you have the QA or test environment, staging, and then live or production. It stands to reason that if you are using outgoing e-mail in your application, and your application is in production, it should send to the proper recipients. However, what do you do in testing and development?
For whatever reason, I can never remember the exact coding of MCrypt. And maybe that is a good thing - so I stop doing so much code duplication and start using a class I wrote. For this reason, I’ll save you the same frustrations and share how I do my encryption.
Everyone I’ve spoken to recently no longer puts mailto://
links in their code for fear that the owner of that address will get more spam. However, there are still legitimate uses for a link like this. In order to foil very simple email parsing bots, I’ve come up with the following script.
Update: I’ve gotten a lot of comments on this code. This was a simple proof of concept at the time when Facebook was creating messages like this. They no longer do it in this manner. I also am not supporting any updates to this code. Thanks for your interest!
So Facebook has been really cool in the way that they have designed and implemented some new paradigms in the electronic communication realm. However, one thing is a problem: they’re too smart. They have hired the best of the best - and have made that the norm. The rest of us are struggling to keep up.
Where was this book 4 years ago? Or even 2 years ago? (Uh - it was published in 4/2010… so… just in the author’s head apparently).
I just profiled some of my code and found out that the biggest chunk of my processing time was used by uniqid()
. I use this to generate form tokens to prevent cross site request forgeries. On one page, I have 6 forms each with its own unique uniqid()
.
The error log can be fun to parse through and figure out what happened. Ok, so if you just read that and agreed, you need to move on. This is not for you. That’s not fun. However, you CAN make error gathering easier on yourself by including the right information in the error log. To top it off, you can present your users with something that is a bit more ‘friendly’ than the standard error display or blank page. Let’s check it out.
I wasn’t in favor of the Facebook fanbox on the site I was working on… but that’s what the client wanted - and that is what they get. I added it and moved on. Well, later, I started noticing a bit of errors in my Javascript Error log.
I rarely find myself needing to chain methods in PHP - but it’s not an altogether bad idea.
The BlueFish editor is a primarily linux based visual editor for various web languages. Visit the site for more…
During one of my random dreams of how to become an internet millionaire, I thought about displaying the top youtube videos on an aesthetically pleasing backdrop.
A while back, a colleague mentioned to me that he was moving his site from one webserver to another. He hated having to FTP everything down, then reupload it. Invariably, we’ve all done this - and forgot to apply proper file permissions, etc.
A while ago, I saw a website that provided a javascript error reporting service. You implemented some code and then they would send you reports on javascript errors on your site. I thought, this can’t be that hard. So I went to work to create my own. (It’s now used on this website as well as some political website I’ve worked on recently.)
A friend of mine posed a question: Do you know of any good PHP based vulnerability scanners? I told him I did not (add any in the comments, if you know! :) ) - but it wouldn’t be that hard to build one. He asked me to give him a code example, so here goes:
One of the most irritating things to me about the Elgg messaging plugin is the requirement to choose my friends from the select box. This SHOULD be generated using the input/pulldown view in Elgg. Unfortunately, they are doing it by hand. However, I’ve patched my plugin to do it using the proper view. Then, I wanted to have an Auto Complete type box to choose a friend. With JQuery I was able to do this. Check out the specs and download below:
Today marked the second time I had to write this code from scratch. To save my self time - and hopefully you too! - I’m going to post what I’ve developed.
The Elgg Generate Users Plugin made me wonder why there was no group functionality… So…
After working some with the open source Community building application Elgg, I found some settings to be irritating. I had to keep hacking my plugins to get these settings activated the way I wanted. Also, I really wanted to put useful settings in the same location.
Now, I won’t bore you with the actual details of how I came across this - let’s just skip to the explanation and example:
I thought I’d take some time to look at the 3 main ways that I’ve handled forgotten passwords on my websites, why I did them that way, and if there was anything wrong.
I remember a while ago hearing about a few theoretical collisions of the MD5 algorithm, but I thought nothing of them. Now, as more information emerges, Microsoft is issuing advisories, and people are proving more and more collisions with example code, and even md5 is out of vista, I figure its time to remind everyone not to use MD5.
After many times of coding relatively the same thing, it becomes prudent to have a standard library for certain sets of processes. Of course - that is why there are things like frameworks! At any rate, one of the biggest things I run into is password complexity. Each website has its own requirement for the security they want to implement. So, let’s talk about the requirements and then look at the code:
I really hate to see people accessing and designing objects with public attributes. So many times I’ve seen this backfire. Let’s take a few examples and see why this matters:
After looking at the Windows model for controlling file access, I realized I could also do that for user authorization control.
While listening to someone complain through twitter about their MySQL conf file, I came up with a cool idea: what if I created a PHP.ini creator that would suggest changes to your php.ini file as well as generate an updated version?
I’ve been thinking more and more about having unique ID’s - especially with working with larger datasets - and I thought it was high time that I investigated the UUID.
Simple enough question. Let’s check out some test code:
The PHP Date manual page has a ton of interesting features to format the date that you can display to the user. However, when you look closer at it, there are actually some really useful modifiers that will help us with our date calculations as well.
I’ve been wondering if I should be concerned about re-preparing a prepared statement when using PDO. Right now, I use code like this when preparing a statement:
You may remember the article I wrote about the observer pattern in php - but it lacked some of PHP’s advanced features.
For a while, I’ve been looking at plugin systems, but not really fully understanding the pattern behind them. Don’t get me wrong, I see how they work, but I didn’t know the reason why - the theory or pattern behind it. Well turns out, generally, they’re based upon the observer pattern. I decided to write my own observer pattern demonstration here.
Can it be done? YES! Luckily, functions like file_get_contents()
support stream contexts.
The predefined PHP constant DIRECTORY_SEPARATOR
is useless.
So, the other day, I saw a horrible thing. I saw two PHP associative arrays that needed to be combined into one, and the worst example of NOT using PHP’s built in functions to combine them. They weren’t using array_merge
- instead they were looping through each value.
While working on a larger site that I may need to use many external libraries, I realized I need to come up with a better __autoload()
function (for example, I think it was DOMPDF that had its own autoload function as well. Last time I used that, I had to hack my own autoload to use their code as well to locate files). I researched into SPL autoload functionality, and I’ve found what I need.
This is more of a proof of concept than anything else - as most of my scripts are ;) But, let’s say you have some files that have css in them, either external stylesheets, internal one with style tags or even style attributes - and you need to update the browser support. Wouldn’t it be great to have a tool that could look through these files and point out that there are incompatibilities?
We’ve all been there before, committing code - and then realizing that it was broken (hrm - our unit test didn’t catch it? or… “what unit test?” if you’re in another environment). Well, there is a solution.
Apparently, a few programmers I know have been getting confused about access of public, public static variables in PHP classes. I’ve written this example code with the following comments to explain what will work - and what won’t.
One of the biggest time wasters I deal with is parsing out static web designs given to me by designers. They don’t know programming, so they design it with static HTML in mind. Even if you’re using a tool like dreamweaver, updating static pages can be a hassle. Then, a lot of times, they have to remove their ’lorem ipsum’ text and send it to me - and then I continue to chop it up. Now, I’m talking about smaller 5 to 10 page sites here, not huge sites like JEMDiary or something. However, that idea birthed…
PHP’s heredoc - good or bad? All silly titles aside, let’s check out some points.
There are many interpretations of MVC - there are less definitions but more implementations. I want to cover what I personally do when using PHP for MVC. I call it MVCFDH.
A useful reminder: you can make use of returning the results of comparisons for is*() functions. Let me explain that further…
Constants can be great. They can stand for things like web services keys, integers, flags, etc. Basically, anything that you aren’t going to be changing in your script - and most likely things that don’t change much outside of the script either. However, I’ve seen people use them in the global name space far too many times. A great alternative is the class constant. Let’s check out some examples:
Well, my boss at #superdev - who can only be compared to a more energetic version of the squirrel from hoodwinked asked me to start putting together some thoughts here and there on some proper PHP coding. I thought I’d start out the series with this article, Programming without E_NOTICE
.
A big issue with PHP security had been the developers creating a php info page and not removing it from a production site. As you may know, phpinfo()
will dump a ton of useful information (for the developer - as well as the cracker) to the screen:
Sometimes we have static configuration options, such as the name of the company or the location of a particular partner’s website. Other times, there are more dynamic configuration options - such as the current location’s URL or database connection credentials.
I’m trying to figure out the best way to do configuration options for my newest PHP scripts that I’m working on. My requirements are simple:
The other day I was experimenting with some PHP plugin scripts and trying to develop my own robust plugin system. I started thinking: how can I guarantee that a 3rd party developer sticks to my plugin standards?
XDebug and Eclipse PDT on Windows - From Start to Finish
So, I admit it - I’ve become lazy. Well, in all fairness, the programmer before me at “the triangle” was also lazy. And after messing with XDebug and setting output_buffering
to off and implicit flush to on… I was reminded of our laziness.
The 102 Degrees Timeclock software package is a very simple interface for keeping track of time. Instead of purchasing a timeclock, you could resurrect an old laptop and run this software on it. With a very simple clean interface, even beginning computer users will feel comfortable. The timeclock has .csv generation for reporting - which can easily be opened in Microsoft Excel. The entire interface is web based.
PHP stores its session information into flat files unencrypted by default.
There are a very small amount of really easy to implement PHP mailer scripts in the wild. They usually try to pump so many features into them that it becomes difficult to implement or too large of a file. For those looking for just a quick drop-in solution - that you DON’T need to know PHP to use - SimplePHPMailer was developed.
I was working on writing a shutdown function for a PHP 4 script and noticed some odd behavior when I was getting errors (no way! I program and get errors? Who knew!?) At any rate, when I would handle my error with my custom function, I noticed the shutdown function was still executing after the error function. (Or when it was a Fatal error, the error was shown to the screen but the shutdown function was still ran…)
So I wrote some code the other day. It sat in my code repository and I never tested it. I was pretty certain it was going to be some good code, though.
So much of my time is spent worrying over the src or href tags on images and links - that I sometimes forget about the other attributes.
Working in a shop that has approximately 15 times more System-I as/400 iSeries (whatever you want to call it) programmers, I’ve been immersed into their culture, standards and mindset.
A while ago, I discovered the ‘joys’ of APD… and then more so, the ‘joys’ of not being able to make heads or tails out of the output script. After digging deeper, I saw that the original directory already had some PHP scripts to parse the output. I ran those and wasn’t very impressed. Even more important, my boss wouldn’t be impressed. I needed to be able to make something that could be useful to integrate into a table (I finally used dojo to create a table…)
So I’m sick of myspace… or so I say to myself. So now I log in about half the time as I did before… and this is because I’ve made the following script. It logs in and grabs each bulletin from your top bulletins. Then, it creates an RSS feed from them.
I found an interesting article about the parameters of the advanced search URL for google. Just for fun, I tested out their concepts and they were all true. I figured maybe there was a reason to do this as a PHP class (I think I was just bored…).
Lately, I’ve been trying to find ways to reduce the amount of time I spend on stupid sites like myspace (nevermind the fact that the time it took to reduce this amount took me enough time to visit myspace 1x a day for another month – heh). At any rate, I’ve been using Google Reader a lot more (I’m up to 180 or so feeds) and I thought: Why don’t I make an RSS feed o my comments – then I don’t have to go back to the site when someone sends me a comment.
I was working on a script that opened up a new connection to the same server with fsockopen
to process a php script. It passed the variables needed through GET and then gathered the output. Finally, it displayed the output on the screen under the current context.
I was reading on a forum the other day about some benchmarks for PHP. The guy had posted some results in ms measurements, and was getting upset about his erratic results. There were some things that he was forgetting, however.
In our current setup at (“the triangle”), we have to use odbc connections to access our db2-udb database - and I don’t like it. But we have to stick with it - and that’s the way life is. The main reason I don’t like it is the immense overhead and time it takes to execute queries. Well, I did some research and found out some interesting things. The most important of which was a cursor setting that allowed me to gain up to 400% performance. Find out how:
After listening to a javascript internals optimization talk, I wanted to see how these concepts could relate to PHP. The biggest thing that stuck out to me was the order of the for loops in javascript.
A lot of weird things have been happening ever since we introduced a new error handler at (“the triangle”). First of all, it took down our whole site for a good portion of time (oops!), then it created a large project for us to review our code. Turns out a lot of the errors were just weird little things that we ignored.
I was looking at some code I had written about 3 years ago - how sad! I was creating a PDF of my resume using PHP to grab my qualifications out of a database. Unfortunately, I never researched into the header
php command, so I made my job harder. Instead of writing it with a php file, I made a php file, and renamed it as a .pdf
file. I modified my .htaccess
file to process that one particular file as a php script. This way, the file executed as php but was mime/typed as the pdf.
I had a function in some of my code that I wanted to trigger a notice error on certain occasions. Unfortunately, it kept halting my script with a Warning instead. Unfortunately, the error handler at that particular block of code was not properly capturing the error string. It runs out that I was triggering an E_NOTICE
instead of an E_USER_NOTICE
error… (if I would have reviewed the trigger_error
manual page, I wouldn’t have made this mistake… silly, lazy developer). Just to make sure that I fully understood this issue and hopefully wouldn’t make the same mistake again, I made a quick proof of concept:
When researching for my live error reporting posting, I tried running some exec
and passthru
command tests by starting up calc.exe. While they executed the command correctly, I got some weird results in my script … which I suppose now make sense. Let’s see how we can start programs in Windows, and not run into the same issues that I did.
Most of my development in Eclipse PDT with the results tested outside of it - using firefox. PDT has a few options in the Run… menu:
PHP developers, raise your hand if you run an explain on each MySQL statement you write and use in your apps! Anyone? Ok… 1… 2… that’s it? Yah, I tend to forget that too, but luckily PHP allows us to cheat. Thanks PHP!
Arrays, return variables, expressions, OH MY! I recently learned a lesson about array functions in PHP not returning what I thought they would. I had a function that returned the value of array_shift()
… and then used it in another function. Unfortunately, this generated a strict error and was causing some issues… As usual, I put together a proof of concept. Let’s check out the code example, the error, and then why:
While working on a website for (“the triangle”), I came to a page running locally that just stopped - blank. This particular website was not using output buffering - so there is no excuse for a blank page.
Today, Todd (one of the consultants that (“the triangle”) uses) called me up to share a bit of a reminder and also tell me about an issue in the code that was in one of our older modules. There was an issue with the strtotime function converting a year to a timestamp.
Round 2, and the final round, is complete! The previous article here talked about my initial findings. Well, I was able to try some proofs of concepts on my javascript finding, and I put together our top level recommendations for (”the triangle”). Let’s see:
Perl, Java and xml people are very aware of what a namespace is… even wikipedia tells us they are. But, certain languages, such as PHP, don’t support namespaces yet. (However, thank you Dmitry for your proposal.) But are namespaces really important? PHP has made it this far without them, so why should you be concerned? Well, let’s see:
A couple weeks ago I was reading a blog posting about PHP Script installing. I don’t remember the exact context of the article (or where it was for that matter - otherwise I’d link to it!), but I had suggested someone make a php script packager - an all in one file to install a php project.
A couple months ago, I was out in Rochester MN at IBM for a multi-day meeting about communication between the iSeries(system-i, i5, as400, whatever its called now a days) and PHP/Apache. One of the things we talked about was our use of ODBC at (“the triangle”) currently to which they asked a good question - Are we using prepared statements over odbc? Well, right now, we’re not, but I think we should. As always, its up to me to show why we should be doing this. Let’s explore:
While working on some code at (“the triangle”), I run into some issues with the mail()
function. On our linux qa and production servers, we can use the mail()
function no problem - but on my development platform, windowsxp, I cannot with our current configuration.
Well, maybe that’s a little bit misleading - actually you’re running PHPdocumentor as an external tool.
I’ve found the need to do some installs from some PEAR channels, so I jumped into my command line on PHP 5.2.0 and windows xp sp2. I ran c:\php5.2\go-pear
- which would launch the go-pear.bat
file. I executed with standard permissions, and the unthinkable happened - a PEAR FAILURE. OH NO! But I was able to get around it. Let’s look at the details of the error, and my lazy man’s way of solving it:
Having been a shell, perl and batch scripter before I started PHP, I’ve always enjoyed the CLI life. I actually created an interactive or script-able interface for creating all of my projects at (“the triangle”) - hopefully I’ll link to it here when I write it up.
As you can probably remember, lately I’ve been writing about PHP’s object handling, patterns, etc. - but I lightly glossed over the whole forced typing of variables - and how that relates to PHP. While looking for solutions to this, I came across a great blog entry that solves this issue - but I’ve gotta bring up some counter points… Finally, I’m also wondering: what are the real important needs for a strongly typed object?
(“the triangle”) wants to keep implementing more and more AJAX based systems - but no one ever took time to research into the security issues with this.
Today, Big Boy sent me an e-mail at work talking about emulation of collections in his .net programming. He included a code sample (after the break). This got me thinking about how I am planning on handling data going forward.
I just finished reading a snippet of a book about design patterns - of which Strategy, Adapter, Decorator and others were discussed. It got me to thinking about my design patterns that I used in JEMDiary - and what I’ll be using in this project.
I was recently reading an article (while researching for my website monitoring project), and there was a comment about PHP5’s lack of flexibility in its Object Oriented usage. Some people were arguing for it - and some against, the typical ranting that goes on in blog comments, etc. Instead of joining the argument, I wanted to do my proof of concepts myself. I’m going to explore (well I already know some of the answers - but it’ll be exploration to YOU reader ;)) public/private constructors, magic methods, and maybe a few extras (we’ll see when we get to the end!)
As I was looking through some old code from Big Boy, I noticed a block of his code at the top of his initial control file and noticed a way he was using his configuration. He was defining his from an INI file and setting constants in the code with a prefix identifier. I then took a minute to look at my most recent framework to see how I was using my config - a static class instance with an internally held singleton pattern. It got me starting to think of which was best… I have a new open source project coming up and I’d like to do the right thing.
In this posting, I’m going to share the steps to making a slimmed down, cleaner, nicer layout for MySpace to help showcase your personal interests, your band, or your business.