Tag: programming

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.

New website for a new year

New website for a new year

Keeping a website up-to-date and fresh can be time-consuming, but they need love. I like to give mine an overhaul about once a year, but sometimes I do it twice a year. Today is the day I decided to give my site a refresh.

I’ve had several posts this year, and they’ve ranged from Creating a Game to the Factory Design pattern. The day I run out of things to write about is the day I have learned everything. Needless to say, this day will never come, and there will always be something to write about.

Each year I look back at the things I’ve learned and accomplished. It always amazes me how much I’ve learned and makes me wonder how I ever got this far. Reflection is good for us, and we should all take a moment to inspect our progress.

I need to make a plan for what I hope to learn this year, what I should write about, and repositories I can contribute. Some programming concepts can be difficult for people (including me) to wrap their minds around. I would like to get a better grasp on some ideas so I can write about them on here and help others learn. I’ve noticed several repositories could use some better documentation, so maybe I can help with that. Writing docs isn’t always the most fun task, but you can’t measure the worth of proper documentation.

OWASP

I’m hoping to start the Huntington chapter of OWASP. In my eyes, security has always been critical, but lately, it’s become even more so in the eyes of the many. If I can help our community practice better coding standards, then it is definitely worth my time and energy. We would meet four times a year to discuss best practices for development and ideas we have.

Silex

Silex

This year I’ve continued to try different PHP frameworks. The ones I’ve tried are well written and have a fantastic community. I can see how some people may need to rely on a framework that does everything, but I like having control. And I prefer to add things instead of removing them.

Silex has been enjoyable to use while building web applications. I have a skeleton repo that has everything I need. This repo has webpack for SCSS, JS, and injecting assets into HTML. The folder structure is organized and easy to understand. The organized code is easier to maintain and debug.

iframe, localStorage, postMessage

iframe, localStorage, postMessage

I recently needed to pass some data from one domain to the other. Using a server-side language, like PHP, wasn’t an option. The site that needed the data was built using Angular and communicated with an API service. I thought about it for a day or two and considered doing it a few ways.

I decided to put an iframe on the source page and pass the data to the target page using JavaScript. Doing it this way only requires me to change a little bit of the code for the Angular site. Below is some sample code that hasn’t been tested.

Parent page


<iframe src="http://localstorage.fishknee.com" frameborder="0" id="iframe"></iframe>
<button id="send">send data!</button>
<script>
var send = document.getElementById('send');
send.onclick = function() {
	var win = document.getElementById('iframe').contentWindow;
	win.postMessage(JSON.stringify({key: 'levi'}), "*");
}
</script>

Recipient page


<script>
window.onmessage = function(event) {
    console.log('received a message!');
    if(event.origin !== 'http://example.com') {
        console.error('origin is bad');
        return;
    }
    console.log('origin is good!');

    var payload = JSON.parse(event.data);
    localstorage.setItem(payload.key, JSON.stringify(payload.data));
}
</script>

Feel free to email me with any questions you may have.

Short Post

Short Post

It’s been a little while since I’ve posted anything, so here is a quick update.

Website

I finally pulled the trigger and implemented AMP. All the pages are now Accelerated Mobile Pages. I didn’t have to sacrifice anything, but I also didn’t spend very much time on the design or presentation. I’ll pretend that I was going for a “less is more” approach. Most visitors come from mobile, so they didn’t get to see any of the fancy stuff that was only for the desktops. I hope to post more often, they’ll be a lot shorter, so come back soon.

Programming

I continue to write stuff in PHP, C, JavaScript, and TypeScript. I’ve been slowly learning Angular and I like it. I’ve also been toying around with Firebase a bit more lately. Firebase is great for anyone who doesn’t want to deal with servers. Cloud Functions are really neat and I hope I get some more time to write something cool.

Primes

I might start finding primes again. The math behind it is interesting and educational.

Creating a Game

Creating a Game

Making a basic browser-based game may not be as hard as you think. I suggest that you solve one problem at a time. If you take an object-oriented approach, you combine all of your solutions into a complete game. Taking this approach will make it easier for you to add features later. I started writing this in TypeScript, which was fine, but I switched to writing ES6.

Making the map

I first got the idea from EJS, so I decided to create the map from the graphic on that site. It has some land, some lava, some coins, the sky, and a player. I wrote some HTML/CSS, and it looked okay (which means it was terrible) but fine for what I needed. I ended up redoing the HTML/CSS later, and now it looks good. I was able to redo the HTML since I was using the same concept from the first attempt. If the player is over a coin, he earns a point. If the player is over the lava, he gets hurt.

Playa’s gotta play

I bound the keydown event to a method in my class. This gives it access to all the properties and methods in the class. If the player moves up, it gets his current position and moves it up a little bit. Left, move player left, and so on. The Element.getBoundingClientRect() method is what helped me the most. It allows me to tell if one element sharing the same space as another element. Now the player can earn some coins to take out his girlfriend. The player does need to be careful because there is lava which will take away all the coins.

Sometimes the person controlling the player might intentionally try and go off the screen. We can’t let that happen so we need some checks in place to prevent it. Relying on our friend, Element.getBoundingClientRect(), allows us to prevent the player from going places we don’t see fit. Imagine the player is wearing a shock collar like one a dog may wear. It prevents unexpected moves.

Gravity

At first I thought this was going to be really difficult to accomplish. I haven’t implemented this at the time of writing this post. Here is how it will work:

  • I’ll create a setInterval if the gravity property is true
  • Every X seconds it’ll check if the user is in the air
  • If the user is in the air, the user will be moved down
  • This will repeat while the game is active

I’m pretty sure real life gravity works in a similar way, but I’m not a physics expert.

Conclusion

Some tasks may seem impossible, but they might not be. They might just take more time than you think it’s worth. The more you practice the impossible or difficult, the better you’ll get, and those tasks won’t seem as impossible anymore.

AMP Gist Component

AMP Gist Component

Erwin Mombay wrote an excellent article on creating your first AMP Component.

AMP is a way to build pages for static content that render fast. AMP extensions use the power of custom elements and allows us to create new components to enhance AMP HTML pages.

While at the AMP Conference Eriwin showed us how to create one and that is what we did. We created the usual “Hello World” that was first featured in “The C Programming Language” by Kernighan and Ritchie (K&R). Admittedly it is a pretty boring thing to do, but it helps you grasp the structure and the logic of the app or language. In Erwin’s guide, he shows us how to write tests and validation.

The AMP HTML repo has hundreds of issues open. They are nice enough to label some as GFI (Great First Issues) for people who want to start helping. One of those issues was to create a new component to display GitHub Gist so I asked if I could write it and they graciously accepted.

By writing this component, while it may be very basic, I have become more familiar with how AMP works. I believe that I’ve finished the amp-gist component yesterday. Next, I created my pull request earlier this week and I got some good feedback. And then finally I had to make some changes, but they weren’t very difficult, and I made them. Then when it was reviewed, I had some more changes to make and some were more difficult. They offered to accept my pull request if I made some of the easier changes, but I wanted to try and make the more difficult changes. The way I was creating the iframe wasn’t optimal for performance and gave me some suggestions. So I’ve done some digging, looking, researching, thinking, and a little bit of trial/error. I believe I’ve got the more difficult changes licked. This component no longer qualifies as a GFI, according to the person who reviewed my PR.

It is my opinion, as well as others, that AMP HTML is the future of the mobile web. It could also be the future of a new desktop web. No one, not even Google, knows where this will end up. Even if the piece I’m working on is small; I am still excited to be part of this. I’ve always wanted to contribute to something that people may use on a global scale.

Node.js Package

Node.js Package

Encryption has interested me for as long as I can remember. I’ve been writing a decent amount of JavaScript lately, so I decided to try ricmoo/aes-js. It works really well and does everything I was hoping it would do. Since it does so much, the interface requires a little more knowledge than the average person may have. This is why I decided to write a wrapper for it.

Wrapper

My wrapper, disguise, provides a simpler interface to the aes-js library. I wrote my code in TypeScript and compiled it into JavaScript. It provides two simple methods that accept all the needed parameters to encrypt/decrypt messages. You must pass a password, IV, and a message; these are required to encrypt/decrypt a message.

There are also two static methods that instantiate the class and encrypt/decrypt the message. It currently uses the same IV for every call, but I’ll eventually fix that. So don’t use this for anything important.

Advanced Encryption Standard

The U.S. government uses AES for TOP SECRET information. Or at least they did at one time, I don’t think anyone really knows what they do. There have been side-channel attacks on AES, but in my opinion, those don’t count. An example of a side-channel attack would be watching someone type in their password.

Tests with Mocha

You should always test your code, well maybe not always, but if you want anyone else to use it then you should. I like looking at tests that other people write, because it gives me insight into their thought process. I don’t have much experience writing tests for JavaScript, so I did some peeking at other repositories. So I wrote some basic tests and it passes!

Conclusion

My wrapper simplifies the aes-js library. I can see why people like using JavaScript for the backend and frontend. If I decide to put this package on npm then I’ll link it on the resources page.