Author: Levi

AMP Contributor Summit Day One

AMP Contributor Summit Day One

My journey to the AMP Contributor Summit began at 5:45 am, Monday, September 24th, 2018. My flight was at 7:33 am, so I got to the airport early, checked my luggage, made it through TSA, and then on the plane. I put my backpack under the seat in front of me and buckled up. A few minutes go by, and then they ask us to get off the plane due to it being overweight.

As we walk back into the terminal I am the first to volunteer since I am traveling alone. I waited around until they found two other people to volunteer, and then waited some more. Eventually and fortunately, they fixed me up with a ticket later this afternoon.

I took this opportunity to go home and nap. I like getting up early, but that was a little too early for me. Frank (my dog) is staying at my mom’s while I’m away, so I’m going to see him again before I leave.

Last year, I went to AMP Conf and had a blast! Since then I’ve learned a good bit more and I hope I learn even more over the next two days!

AMPbin v2.0(18) for AMP HTML

AMPbin v2.0(18) for AMP HTML

TL;DR visit the new AMPbin website at https://ampb.in/ 

Last year I posted about AMPbin v1.0.0 (link), and I’m posting about it again this year! It had been a while since I checked on the website, but when I did, it wasn’t working very well. That gave me the opportunity to rewrite it from scratch.

Sloth starting from scratch.

Over the years I’ve learned it is better to take more time planning than to start coding without a plan. When I rewrite some code, I still find ways to improve it. Perhaps I don’t always need to start from scratch, but sometimes it is easier than refactoring.

I’m still using the same repo, but I have added some more information about contributing. One major goal is getting people to contribute. So please visit the Github repo and start helping! (please)

What’s new with AMPbin

AMPbin

I am using more icons since they generally don’t need to be translated. There is an icon to create a new bin, another icon to save the bin, a copy AMP HTML button, and a copy bin URL button. Validation is displayed using green with a thumbs up when it validates and red with a thumbs down when it doesn’t validate.

Roadmap

Right now users are logged in anonymously and automatically. In the future, I would like for users to have the option to login and list their saved bins. I could also find ways to improve the overall speed of the site. If you have any ideas or suggestions, please let me know, they are all welcome.

Next month is the AMP Contributor Summit! It’s Google, Mountain View, California and I will be attending. I hope to share this project with the people there and maybe find some help.

3 Things You Should Know About The Apache HTTP htaccess file – 2018

3 Things You Should Know About The Apache HTTP htaccess file – 2018

I have been using the Apache HTTP Server since early 2000’s, and it only continues to get better. While most people don’t need to know how to set it up from scratch and configure it, you should know how to use the htaccess file. If you create a file named “.htaccess” in the “public_html” folder of your website, you can do some really neat things. I’ll cover three things everyone using Apache should know.

Block Users With htaccess

You may find yourself wanting to block a certain visit from your site, and that’s okay, but how do you do it?

allow from all
deny from 1.2.3.4 # blocks one IP address
deny from 1.3 # blocks every IP beginning with 1.3

SEO Friendly URLs With htaccess

If you’re tired of having “index.php” in your URLs, I don’t blame you. Below is a snippet you can add to your htaccess file to easily rewrite your URLs to remove it. Doing it this way, you don’t have to change any of your code, just add the snippet below.

RewriteEngine On
RewriteBase /

# Removes index.php
RewriteCond $1 !\.(gif|jpe?g|png)$ [NC]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]

# If 404s, "No Input File" or every URL returns the same thing
# make it /index.php?/$1 above (add the question mark)

Forcing HTTPS With htaccess

If your site has an SSL certificate, then I recommend you force your users to use it. That green “Secure” text in the address bar makes everyone feel a little safer, and it helps with SEO.

RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

Conclusion

While nginx gets all the attention lately, we can’t forget about Apache HTTP Server because it’s going to be around for quite awhile. Be sure to check out the Apache docs or leave a question below.

If you are familiar with Apache but would like to try nginx, you could always use nginx as a reverse proxy.

How to secure your PHP Web App with a simple Firewall

How to secure your PHP Web App with a simple Firewall

I was trying to find a simple way to secure my PHP Web App when I realized how difficult it could be. Securing it the easy way cost more money than I’m willing to spend, so I decided to build my own solution.

old school firewall

What are your options?

Compiling nginx with ModSecurity isn’t easy, and I don’t think your WAF (Web Application Firewall) should be tied into your web server. If you want to simplify things, you could use Cloudflare or Sucuri, but that can be expensive. While Cloudflare works great and is fast, shouldn’t you have your own WAF? These services do offer more than just a WAF, so be sure to do your own research before committing to any one solution.

Elite Hacker desktop

PHP Web App Firewall

I’m writing my PHP WAF in Go. The criteria I set for this project is fairly simple.

Criteria

  • It needs to be uber fast
  • Handle XSS and SQL Injections
  • Work with Docker

The Journey

Two weeks ago I sketched the idea out on the back of an envelope. If nginx could talk to my Go service, and my Go service could talk to PHP-FPM, then this might be a pretty easy solution. I know that nginx has the proxy_pass config option and that Go can handle HTTP traffic. But how can Go talk to PHP-FPM? I did some research and tried out a few different FastCGI client packages for Go until I found one that suited my needs. Now I have two ends of the stick figured out, but I’ve yet to even think about what happens in the middle.

I ended up finding a Go package that does an excellent job at filtering XSS. I then wrote some middleware for HTTP and used that Go package to filter any requests that contain an XSS attempt.

But what about SQL injection? Well, I found some regular expressions that match common SQL injection and implemented those into my HTTP Request analyzer. If any SQL injection is detected, it kills the request and your PHP Web App never sees it. At the time of writing this, I still need to implement more security measures.

I’ve also built a Docker container that runs this Go app as a service and is pretty easy to set up. While I haven’t used this for anything in production, I have tested it and it was able to handle several thousand requests a second.

Conclusion

This code should actually work with any language that can use FastCGI as a means of communication, but I haven’t tested it. I’m looking for people to help me finish this project since I’m just now learning Go. Please feel free to fork my repo if you can contribute in any way.

github.com/levidurfee/gowafp

Reflection tips for 2018

Reflection tips for 2018

Each new year gives us an opportunity for reflection on the previous. Our accomplishments, failures, and life overall. We often find ourselves making lists of items on which we can improve. How do we determine what is best for us to improve?

I would often find myself making plans to get better at a specific programming language, learn a new one, master design patterns, or a particular algorithm. While I could improve at all of those things is it really what I should spend my time on? I enjoy those things and will do them anyway, so in my opinion, this is a lazy way of planning to get better.

If you’re familiar with the computer science term “reflection,” then you probably understand introspection or self-reflection. Introspection is the examination of one’s thoughts and feelings. This review can help you become a better person, be happier, become more efficient, and many more things.

You can be a brilliant developer, but if you’re an asshole, no one will want to work with you. We should welcome any new ideas with words of encouragement. A crazy idea, in our opinion, could turn out to be a brilliant idea. We should have patience and be less quick to judge or shoot down thoughts. We need to listen to each other carefully. We are rarely put in a life or death situation where a decision has to be made in minutes. Take the time to plan, brainstorm, and think about the problem. Utilize your team if you have one.

Our lives are short, so let’s find ways to enjoy them, and help others enjoy theirs.

Docker Explained for PHP Developers in 2018

Docker Explained for PHP Developers in 2018

This post assumes you have a basic understanding of Docker. But what is a basic knowledge? If you aren’t sure, I suggest you read the Get Started docs, and then you will have a basic understanding of Docker.

I’ve read a few posts on Docker for PHP developers. However, it was the same tutorial on different sites, so I’m not going to copy what they did. I’ll explain the concepts that I struggled with learning.

My objective with Docker is to develop locally and deploy to a Swarm. I hope to have a fast site with high-availability that can be updated and deployed quickly.

Developing Locally

I was recently working on a project that uses SOAP hosted on a slow connection. Instead of hitting that API each page load, I decided to store the results in Redis, and load them from there. This helped speed up the pages that needed to access the data from the remote API. Installing Redis on my local system wasn’t what I wanted to do, so I simply added a Redis service to my “docker-compose.yml” file, and it worked great. You can easily add new services to your stack while developing locally with Docker.

Being able to edit your code, with all the services running, and see the changes immediately is very valuable. I like to develop on Windows, OSX, and Linux, so my environment is drastically different on each machine. It would be very time consuming if I had to have Redis running on each of my dev environments. Having Docker running the same services locally on my dev machines as what is running in production is priceless.

Priceless

The Docker Compose file

You will need two use two “docker-compose” files, one for local development, and one for deploying to your swarm. The main file, “docker-compose.yml,” will be used when deploying to your production environment. And “docker-compose.override.yml” will be used when developing locally. You want to copy your PHP code into the container when you are deploying to production. When you’re developing locally, you want your code outside of the container, so we mount it with volumes in the override file.

Docker Swarm explained in a drawing

You can use Volumes in production, but you will need to copy the files to the node where the container will live. That can be complicated and in my opinion, isn’t ideal. It does work well when developing locally and your computer is the node since the files are already on it.

Docker Services and etc

All of these terms can become confusing, at least they were to me, but I hope to explain them shortly. We used to refer to a “web server” as a server that ran everything a website needed. Even though it was a server running daemons like Apache’s httpd.

Now we have stacks, containers, node, swarms, services, and a lot more words to describe things. Communication is important when speaking with others about the approach you wish to use when solving problems. Understanding what you’re saying is even more important. I’m going to try and define these terms myself.

A service is a piece of software written that we will use to help us accomplish our goals. MySQL, nginx, Apache, PHP, node, and etc are all services we can use with Docker.

Your stack is essentially a list of the services being used for the app. For this example, I’m using haproxy, nginx, and PHP-FPM.

A container is a way to virtualize the service(s) on the computer. FreeBSD has had this ability for a long time with Jails, but Docker has made it much easier. Containers can’t access other resources running on the server.

A node is a single instance of an Operating System. Your computer could be a node, as well as a Virtual Private Server or a Virtual Machine or an entire bare metal server. Node’s run an Operating System that runs the containers.

Swarms are really awesome! They are a collection of nodes and can distribute the containers across them as needed. They can have their own private network and do load balancing.

Swarm

Conclusion

This app is using haproxy, nginx, and PHP-FPM. I’m passing SSL through haproxy so nginx can handle SSL termination because I’m not sure how to do it with haproxy. The load balancer, haproxy, passes the request off to one of the web services. One of the web services, nginx, then connects to a PHP-FPM service to process the PHP.

Be sure to check out the levilol/php-docker repo on Github.

Docker is an excellent tool that I hope to learn more about this year. Other’s have predicted it will get much more attention in 2018 and I agree. I’m going to end this post with my simplified description of Docker.

Imagine if you could compile your app with all the required services and end up with one binary file that contains everything – that is Docker.

Please leave any feedback below in the comments section.

Discover 3 Tips Every Developer Should Know in 2018

Discover 3 Tips Every Developer Should Know in 2018

In this post, I will help you discover 3 tips every developer should know. For the people reading this post who are hoping to learn how to program, no one is perfect, and we all make mistakes, so have fun while you learn. Everyone else, leave a comment below if you can relate or have any other tips!

Debugging

I think it is rare when code works as expected the first time you try it. Sometimes error messages seem very cryptic and are hard to understand, but if you read it carefully, it may give you some context as to what is wrong. Usually, you forgot a semicolon, and you’ll become very familiar with that error message, I am at least.

While you can Google your error messages all day long and find millions of results, they won’t always be helpful, so you need some tools to figure it out on your own. You are expecting your variables to contain specific values, so I usually check to see what is in those variables. Using console.log or var_dump can help you figure out where your code went wrong.

Sometimes you will have to dig a little deeper. So I encourage you to reduce the complexity of the error-prone code until the error goes away. You may want to make a copy of the files current state before you start removing lines of code.

Rick and Morty looking for something

Just remain calm, don’t stress, and use your brain. It may help if you step away from the computer for awhile. Maybe go for a walk or pet your dog.

Trial and Error

If at first, you do not succeed, don’t immediately ask for help, but do try it a different way. Your code may be getting too complicated, and it could be best for you to refactor it. Again, I suggest you step away and pet your dog if you get stuck.

I like to keep a log of what I’ve tried and when I tried it, why I thought it would work, and what happened. Doing this helps me keep track of where I was going with my thoughts. You don’t want to get a hunch and forget it; that’s a waste of your time.

You may need to go back to the planning phase and see if you still think this is the best way to approach the problem. I use pen and paper a lot when I’m working on larger projects. Our minds are incredible, but being organized helps me a lot.

Asking For Help

We all make mistakes. Sometimes, we think the error is not our fault, when in fact it is. Don’t be fearful of asking for help, but also, don’t let it be the first thing you do. Asking for help should be your last resort.

When you do ask for help, give enough information for people to understand the context of your situation, but don’t overload them with garbage. I often find myself typing up a question on StackOverflow when I realize what I did wrong. Even talking out the problem with a co-worker can help you understand what you did wrong. If you don’t have a co-worker, you can always tell your dog. They’re good listeners.

Conclusion

The title, Discover 3 Tips Every Developer Should Know, hopefully, encompasses the content of this post. Should you ever need any help, please feel free to leave a comment, or send me an email.

Advanced PHP is Actually Simple – Learn How Today

Advanced PHP is Actually Simple – Learn How Today

Advanced PHP methods, practices, processes, and everything else can be a bit daunting. If you find it hard to understand some of the documentation or tutorials out there, don’t worry, I can help! I struggled to learn some of the core concepts, but eventually figured it out, I hope I can help you learn with less of a struggle. Having a good development environment is a huge step in the right direction. For work, I use a Windows machine and a MacBook Pro. At home, I have a desktop running FreeBSD. Use whatever you are most familiar.

Packages

You don’t have to do everything yourself; this was a hard lesson for me to learn. There are groups of people who focus on a single PHP package. That package is going to be well written, tested, and hopefully documented. I suggest you use PHP packages when you can. You can browse the available packages on packagist. You will need to have composer installed on your dev machine. If you have an idea for a package, then read my post on creating a PHP package.

Autoloader

The autoloader isn’t magic, but it is very helpful when writing advanced PHP. It will conditionally include the needed PHP files based on the code being run. No longer will you need to have dozens of includes as the autoloader will handle most of them for you. Packages have a registered namespace that tells the autoloader where their files so it can load them. This allows you to easily instantiate a new object without having to include the needed files.

PHP Design Patterns

You’re only making it harder for yourself if you aren’t using design patterns. There are plenty of definitions of design patterns, and none of them make sense. When a definition is defined with other complicated words, I find it confusing. Below is a simple explanation of design patterns.

A design pattern is a way of structuring your code so it can easily be extended, enhanced, or fixed. Most advanced PHP applications will use a couple of design patterns. They’ll help keep your code organized and understandable.

I have written a few posts on different design patterns, such as the adapter pattern, dependency injection, and the factory design pattern. “Design Patterns: Elements of Reusable Object-Oriented Software” by Erich Gamma is an amazing book if you want to learn even more.

Security

There have been a lot of very public data breaches in the last couple months, so I will also cover some basic security tips. Whether your application is used by a couple of people or hundreds, you should always practice safe security. If your app uses a database, an API, or some other type of service, it could be vulnerable.

When you are writing information to your database, please use PDO. PDO is faster and more secure. PDO Tutorial does an excellent job of explaining everything clearly and concisely. Feel free to ask any questions in the comments below.

Another important aspect of application security is protecting against CSRF (Cross-Site Request Forgery). If I were to create an HTML form on my website and set the POST parameter to your website, how would your website know where the post came from? It’s a very difficult thing to do unless you use a CSRF token with your forms. When a user sees a form, you also generate a CSRF token. You add the CSRF token to a session variable and to a hidden input field that is part of the form. Then when the user submits the form, you can check the hidden input field data against the session variable. If they match, then you know they submitted the form from your site.

Visit the OWASP website if you would like to learn more about security.

Advanced PHP Conclusion

Programming is all about solving problems. We take a big problem, break it into smaller problems, solve the smaller ones first, and then we’ve solved the big problem. Keep trying to make your code smaller, simple, and elegant. Programming is art for logical people like yourself. Keep being curious. Let me know in the comments below if you have any questions. I would love to help.

DigitalOcean Spaces – Learn how to use Spaces with PHP

DigitalOcean Spaces – Learn how to use Spaces with PHP

Using DigitalOcean Spaces with your next PHP project is a beautiful idea. Spaces will give you all the hard drive space that you could ever need. This post can help you build your next PHP project with DigitalOcean Spaces. Building out an infrastructure can be a difficult job for anyone, but DigitalOcean’s services make it a bit easier.

Mounting Object Storage

You could upload directly to S3 compatible storage using a PHP package, but it is easier to mount a bucket and let the file system handle the rest. Read my post on Mounting Object Storage if you need help getting started.

By mounting your bucket to your local file system, it will allow you to have nearly unlimited storage space for your app. In addition to storing uploaded files to object storage, you could also save backups, log files, and anything else you could imagine.

PHP Uploading to DigitalOcean Spaces

Your code will probably be a lot more complicated than the example below. However, I think the code below will suffice for this blog post.


<?php
$message = '';
if(!empty($_FILES['uploaded_file'])) {
  $path = 'uploads/';
  $path = $path . uniqid('u', true) . '-' . basename($_FILES['uploaded_file']['name']);

  if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $path)) {
    $message = 'The file ' . basename( $_FILES['uploaded_file']['name']) . ' has been uploaded';
  } else {
    $message = 'There was an error uploading the file, please try again!';
    $message .= $_FILES['uploaded_file']['error'];
  }
}
?>
<!DOCTYPE html>
<html>
<head>
  <title>Upload your files</title>
</head>
<body>
  <?php echo $message; ?>
  <form enctype="multipart/form-data" action="upload.php" method="POST">
    <p>Upload your file</p>
    <input type="file" name="uploaded_file"></input><br />
    <input type="submit" value="Upload"></input>
  </form>
</body>
</html>

The code in the example above shows you how to upload a file to a folder. You will need to change the path to where you mounted your bucket. Of course, you will need to make sure you validate the file type and restrict it to users who are logged in.

Conclusion

Digitalocean Spaces is the best object storage service currently available. While they might not have as much space available as AWS, it is compatible with S3, easy to use, and has a better UI.

Please don’t store any sensitive or confidential information in your buckets. If you must, then please make sure you have the proper settings and those files aren’t publicly exposed.


Image Credit DigitalOcean.

Skeleton Repo for PHP, JavaScript, and SCSS

Skeleton Repo for PHP, JavaScript, and SCSS

I work on a lot of different projects, and each one is unique in its own way. I often find myself installing packages manually and then configuring them. It seems like I repeat myself quite a bit, but the requirements of each project vary ever so slightly. In an attempt to prevent myself from repeating the same tasks over and over, I’ve started working on a skeleton repo that contains nearly everything I would need.

What I was doing

Most of my projects are built in PHP and augmented with JavaScript and SCSS. Occasionally I’ll make a project solely with JavaScript. So I would have to run the following commands:

  1. composer init
  2. composer require silex\silex illuminate\database
  3. npm init
  4. yarn add webpack babel-core … and many more

Then I would have to do the following:

  • Configure my composer.json to use PSR-4 autoload for my namespace
  • Create my folder structure
  • Create some interfaces, classes, and models
  • Configure webpack to use my folder structure
  • Import my SCSS

Doing all of this over and over is a waste of time.

Creating a skeleton repo

My decision to create a light skeleton repo has saved me time. Since it is light, it is very easy to scale it back to what I need. However, if I need to add more, I can do so easily. It turns out that I’m quite good at creating a skeleton repo since I’ve done it so many times. By carefully planning and using the steps above, I had one created in about a day. I’ve continued to refine it and add more features.

Conclusion

I’m sure there are some very elegant solutions on there that do what I need, but I enjoy creating these solutions for myself. Perhaps I’ll end up using something someone else created, but I hope that I’ll have a greater understanding of what they’ve done.