PHP – Simple GitHub Login (OAuth)

If your codebase is in PHP and you would like user’s to be able to login to your site using GitHub (single sign-on) you can use the following as a good starting point:

Next you will need to setup an OAuth application within GitHub by doing the following:

  1. Login to GitHub.com.
  2. Go to your settings by clicking on your avatar image in the top-right corner of any GitHub page and then clicking on Settings in the drop-down menu.
  3. Scroll down to the Developer settings menu on the left and click OAuth Applications.
  4. Click the Register a new application button.
  5. Enter all of the necessary information to register your new OAuth application and then click Register application when you’re done.
  6. Take the Client ID and the Client Secret and place them in the constants defined in your PHP code from the beginning of this post.

That should be it. Now when you run this code you should be prompted to authorize your application to read your public information and private email addresses. You can remove the scope if you don’t need to be able to read any private information such as email addresses or you can change the scope after reviewing this page. If you want more information about OAuth apps for GitHub you can check out this page.

Happy coding! 😎

PHP Snippet – array_splice_assoc(…)

Recently I was working on something that required inserting key-value pairs into an array after a specific key in PHP. As I was looking through stackoverflow answers I realized that there was no awesome answer that really jumped out at me. Therefore I decided to take a few minutes to just write my own array_splice_assoc() function to get the job done:

As you can see this function takes the same parameters that array_splice() does but the difference is that the offset can be a string in this key which refers to the key after which the new array elements should be inserted.

One important thing to note is that if you try to insert a key-value pair in which the key exists before or at the offset, your key-value pair will not be inserted. On the other hand if you try to insert a key-value pair in which the key exists after offset, your value will replace the previous one.

Have fun! 😎

PHP – Re-indexing 2D Array By A Specific Key

Today I was working on a personal project and wanted to be able to use a native PHP function to re-index a 2D array so that the key for each sub-array was pulled from a value in that sub-array. Unfortunately I wasn’t able to find a way to simply do it natively although it may exist. Therefore I wrote this array_by_column() function:

To use it you can simply supply the 2D array as the first argument and the key (or column name) as the second parameter.