php posts page 3

Quick regex to strip html tags

Recently, I needed to strip some HTML tags from some data. The goal was to make a field in a database that was a WYSIWYG text area into plain text content that could go inside a link. I did it using a simple regex of /<\/?[^>]+>/ to find the tags so I could replace them with an empty string. In PHP, this looked like:

$string = preg_replace('/<\/?[^>]+>/', '', $string);

This is perhaps a naïve implementation, but it served my purposes fine. Of course, I had totally forgotten about PHP’s built in strip_tags() function, but on comparing it, it also seems to not do exactly what I want. For instance, it seems to get rid of the content of <a> tags.


Sending email attachments with PHP `mail`

I recently had to set up a PHP script to send an email with an attachment. With the current version of our CMS, we have swiftmailer available, which would make this easy, but for this site, I didn’t have it easily available. I considered bringing it in, but since this was just a simple script, I decided to give a go at doing it directly with PHP’s built in mail() function. I found an answer on StackOverflow to guide me. Many respondents to that question recommended just using a library, but the answers that didn’t seemed reasonable.

It took me a number of failed attempts to get the headers and line-breaks just right so that both the email message and attachment sent properly, but I got it working. The code of my solution was fairly specific to the application, so I’ve modified it to make it more generically applicable for this post. The (untested but generic) variant of the solution looks like:

Continue reading post "Sending email attachments with PHP `mail`"

Globbing files including dot-files

Normally globbing for the wildcard * will find all files in a directory except for ones beginning with a .. Sometimes I need to get all files including the dot-files. The pattern .* will find these hidden files, but will also include . and .., referring to the directory and its parent. As I’ve learned in the past, this can be dangerous with commands like rm, (i.e. you running rm -rf .* to remove dot-files will remove more than expected). Today, needing to get all files in a particular path in PHP, I sought a solution. A post on a Perl forum gave me a solution using curly braces: {.??*,.[!.],*}. Braces basically allow multiple comma-separated patterns to be evaluated. The three patterns are:

  1. .??* matches a dot followed by two characters followed by any number of characters.
  2. .[!.] matches a dot followed by a single character that isn’t a dot. This is needed since the previous pattern doesn’t match this case.
  3. * is the normal wildcard glob, matching all non-dot-files.

In PHP, the glob() function requires the GLOB_BRACE flag to use braces. An example might look like: $files = glob($path . '/{.??*,.[!.],*}', GLOB_BRACE);. This did exactly what I wanted.


I got PHP 7 working locally finally. It worked for CLI just fine when I first installed it soon after its initial release, but it wasn’t working with Apache. I’ve been upgrading every once in a while and finally, today, it worked. Now I just have to wait until Dreamhost supports it until I can start playing with it for my own site. At work, though, I’m still stuck back in PHP 5.3 land because of needing to support some old sites.


Load Balancers and HTTPS

Until recently, I had no experience working with sites behind load balancers. Cogneato has been moving its sites to Rackspace virtual servers for flexibility, among other things. One of their recommendations that we took was to put our web server behind a load balancer. Even though we haven’t needed multiple nodes behind it yet, it makes it easier to upgrade the server behind it without needing to change IPs in DNS and will allow us to easily pop up another node when it is needed.

This arrangement has gone relatively smoothly except a few issues. The biggest ones have had to do with our HTTPS sites. We run both HTTP and HTTPS sites on the same server. We put the certificates on the load balancer, so traffic goes from the load balancer to the web server over HTTP. Both Apache and code see the request as HTTP as standard methods are concerned. I will discuss some of the problems we had and solutions I found.

Continue reading post "Load Balancers and HTTPS"

Notes on Using PHP Class With Statics for Configuration

I will be talking about using namespaced PHP classes with static properties for configuration. Since my use was in relation to Symfony, it is important to note that the Config component should be used for everything possible, but that it can’t be used before it is instantiated.

Reasons to use namespaced static class properties for configuration:

  • A class can be defined in a file. When that file is included from elsewhere, the class is defined.
  • Once a class is defined, it is accessible anywhere after that point, regardless of scope. Like a superglobal.
  • Statics are variables set on a class rather than on an instance and can be accessed directly from the class. This means no variables outside of the class need to be set to work with the variables. Like a superglobal singleton.
  • Statics are not static and can be modified just like any other variables.
  • Static methods can control access and provide other behaviors you may want for working with your configuration.
  • Namespaces help prevent collisions of class names by essentially adding characters to a class name that make it less likely to be used elsewhere. With psr-0 / psr-4 autoloaders, the namespaces should be well controlled.
  • Variables can’t be namespaced, so classes (or constants or functions) are the only way to take advantage of their benefits.
  • Using constants and functions inside of a namespace is similar to static properties and methods of a class, except the constants are immutable and have limited data types, and there aren’t the niceties like self for the functions.
  • Being in PHP (as opposed to some config file format) allows use of __DIR__ (my primary need was for storing paths, and it wouldn’t be ideal to have to put in the full filesystem paths to things), string concatenation and other operations, and any other PHP behavior or values desired.
Continue reading post "Notes on Using PHP Class With Statics for Configuration"

PHP Output Buffer Manager

With rebuilding my website with WordPress, I have made progress on the WordPress starter theme I’ve been working on. One thing I used for it was PHP’s output buffering to control output and allow me to define “blocks” of content, then render them at a later point in their proper location. To this end, I created some helper methods to manage this for me and allow easy creating of named buffers. I got the idea for this from the slots of Symfony’s PHP templating engine.

I have since broken this out of my WordPress theme helper classes into its own class and created a github repo, PHP-BufferManager to allow its use for generic purposes. This is a very simple repo and class. The most common way to use it would be to use $instance->start('name'); to start a buffer named ‘name’ and $instance->end(); to end it, then $instance->get('name'); at a later point to get the string value of the buffer for output or other purposes. A simple example:

Continue reading post "PHP Output Buffer Manager"

Symfony: PHP Templating Engine and Global Variables

At Cogneato, we are using Symfony’s PHP templating engine to render our views for compatibility with our existing system and for allowing our developers to continue using the same language they’re used to. I was looking for a way to make various services and other “variables” globally available in all view files, like can be done for Twig as mentioned in this cookbook. I asked on Stack Overflow, but didn’t get what I was looking for. We came up with our own solutions. I provided some as my own answer to that question. I will discuss the ones I can think of in this post.

Container

The one answer to my Stackoverflow question pointed out that the $view object has a container member object that has services available, and you can also access parameters set in your configuration file. Services would be accessed like (I believe):

Continue reading post "Symfony: PHP Templating Engine and Global Variables"

Using Symfony alongside an existing system

At Cogneato we’ve had a CMS that has been built up over more than a decade. We started working on a completely new system a while back to have a new and more powerful interface, add new features, and get rid of a lot of the cruft that the old system had from being developed over such a long period by many developers with different styles. We decided to use Doctrine as an ORM and Symfony as a framework for our back end.

We have maybe 200 sites running on various versions of our old system though, and we need to be able to add the new system’s features without having to completely redo them. We needed a way to be able to leave all the current stuff in place and pull in the Symfony stuff to the existing files with a simple include.

Continue reading post "Using Symfony alongside an existing system"