The Guide To M16 History That You Never Knew You Needed

The M16 has a fascinating history in many ways. Its appearance is iconic, and has certainly become part of American culture. It is also a symbol, a microcosm, representing both American ingenuity, blunders…but also triumph.

The M16 design and development process itself was a brutal slog, resulting in a number of wrongheaded missteps, and ultimately in the tragic deaths of service members due to bureaucratic idiocy. Eventually, however, it became, in many ways, a superior rifle to the ones it replaced and led to the current service rifle of our armed forces, the M4 carbine.

It began with a comedy of errors, but ended in success. I’m going to skip a few details here and there to keep this a reasonable length. If someone wanted to commission me to do a book-length feature on this topic (if you’ve got the money, honey, I’ve got the time), get with me after this.

The history of M16 starts, of course, with the

M1 Garand

. The Korean War impressed upon the armed forces that while the M1 was accurate, powerful and reliable (when maintained) the poor carrying capacity and relatively heavy recoil made it ill-suited to attacks by massive waves of enemy troops which requires lots of rounds being shot at them.

The M1 Carbine fared no better; while the greater capacity was in its favor, the rather limp 110-grain .30 caliber bullet (less powerful than a .30-30) didn’t have the necessary wallop.

Since most killing in combat took place at rather close range (within 150 yards) they also decided that there were too many weapons systems in service. Why bother issuing the M1 Garand, M1 Carbine, Thompson submachine gun AND the BAR when you could replace them with a single gun that fired the same cartridge?

The government wanted a .30 rifle caliber cartridge, since that’s what they were used to. Additionally, the new .308 Winchester round offered a lot compared to .30-06. With the shorter case length, slightly flatter trajectory and roughly equivalent power, the soldier loses no firepower, but more ammunition can be shipped in the same size of cargo container.

So, they started taking submissions for a new rifle.

Armalite, a division of Fairchild, and their design wiz

Eugene Stoner

, created a semi-auto rifle that handled a .30 caliber cartridge (the then-new .308 Winchester) with a simpler semi-automatic design and lightweight construction. That rifle, the AR-10, used a direct gas impingement system to cycle the bolt.

The design was ingenious at the time. The AR-10 cycles exhaust gases directly back into the receiver, blowing the bolt backward and ejecting the spent round. The buffer spring in the stock compresses and then sends the bolt forward, cocking the gun and cycling the next round into the chamber.

The AR-10, was fitted with furniture made of Bakelite (a hardy, somewhat heat-resistant resinous plastic notable for being the first totally synthetic plastic) and an alloy receiver, weighed less than 7 pounds unloaded.

It had most of the features you’re familiar with. There was a carrying handle, rear aperture sight and front blade sight, polymer stock, pistol grip and forend, the charging handle in the carrying handle rather than on the receiver, flash suppressor, an adjustable gas compensator and the hinged takedown design.

The T-47, an early prototype of the M14 rifle. Credit: Springfield Armory National Historic Site [Public domain], via Wikimedia Commons

Despite very favorable impressions in testing, the T44 rifle submitted by the Springfield Armory (the actual one; not the gun company) was chosen instead,

designated the M14

. The M14 was an improved M1 Garand design; the firing mechanism was almost unchanged, operation and maintenance were almost unchanged except that the M14 chambered .308 (later standardized by NATO as the 7.62mm NATO) ammunition, was magazine-fed with a 20-round box magazine instead of en bloc clips and was select fire-capable.

However, some folks in the armed forces felt almost right away that a smaller cartridge would solve several inherent problems. The .308/7.62mm round is effective, no doubt, but its recoil is rather stout when firing rapidly in semi-auto, and darn tough in full-auto. If a smaller cartridge could be created that had killing power out to, say, 500 yards, with lighter recoil, it would increase the effective lethality of the soldier wielding it.

That was exactly the thinking of General Willard Wyman, who put out a proposal in 1957 for a lightweight infantry rifle that chambered a .223-caliber bullet, effective to 500 yards and with more velocity than M1 Carbine ammunition. Since such a rifle would be easier to fire in close-quarters combat, it would replace the M1 Carbine, M1 Garand and Thompson as well.

Eugene Stoner set to work, scaling his rifle down for the new cartridge (commercialized as the .223 Remington) and had working prototypes in testing by 1958. The new rifle, then-designated the AR-15, actually worked very well.

The receiver, made of stamped alloy, was easy to make at scale since it didn’t require machining. The receiver and barrel, chrome-lined for durability, made it very reliable. The cyclic rate of 600 to 700 rounds per minute was very good and the rifle was quite controllable in full-auto firing. The barrel – with a fast 1:12 twist – made it quite accurate.

Now, by 1958, the M14 wasn’t Facebook official quite yet. Armalite, which was made into a going concern by Fairchild’s investment, had yet to sell any guns beyond the AR-7 (which was only sold in limited numbers to the Air Force) and was tired of having nothing to show for all its hard work. When General Maxwell Taylor ix-nayed the AR-15 in favor of the M14, Armalite decided it had had enough and sold the AR-15 and all rights to Colt.

Colt realized the potential of the AR-15 (and thus the M16) and decided to hang in there. Army trials demonstrated the easier operation but also the efficacy of the rifle, leading to General Curtis LeMay of the US Air Force ordering more than 8,000 of them and declaring it the standard service rifle of the Air Force in 1960.

Curtis LeMay. Credit: US Air Force Link

Around that same time, the conflict in Vietnam was heating up. M14s in the hands of US “advisors” were already showing some weaknesses. Full-auto operation was all but untenable and semi-auto operation and the heavy rifle wasn’t much better when you’re confronted by a close-range ambush or mass charge. The M1 Carbine lacked stopping power, so that was clearly a non-starter.

As a field test, a few thousand AR-15s in their early configuration were put in the hands of South Vietnamese troops for testing under fire. The results were overwhelmingly positive, and reports of the M16’s performance continued to make their way back to Washington.

However, a series of tests conducted by the US Army continued to favor the M14 despite reports from the field indicating the opposite. Secretary of Defense Robert S. McNamara ordered Cyrus Vance – then-Secretary of the Army – to look into why that was happening, and he discovered that the Army was (purposefully) testing match-grade M14s against off-the-rack M16 rifles.

Robert S. McNamara. Credit: Cecil Stoughton, White House photographer [Public domain], via Wikimedia Commons

McNamara called BS, and after having a look at the supply chain for the M14 (McNamara, prior to his service as SecDef, was a rising star at the Ford Motor Company, briefly serving as the company’s president) concluded that it wasn’t sustainable. So he told Taylor, et al., that their goose was cooked and ordered a whole lot of M16 rifles.

However, the old guard wasn’t done. They insisted on the installation of a forward assist in case of jams, which the M1 Garand and M14 had. Everyone who developed the rifle responded, “What are you doing forcing a round in that doesn’t want to go…just eject the thing!” but they would have none of it. The Air Force, however, went ahead; Air Force M16s lacked the forward assist. However, the Army version – the XM16E1 – were equipped with a forward assist. At that point, it was basically done.

By 1963, the M16 was adopted as the standard service rifle for the armed forces. Colt even started selling Colt Armalite Rifles and Colt Sporter Rifles to civilians, which were semi-auto versions for sport shooting. However, at this point, a few key revisions had been made to the M16 that severely compromised its use in the field.

The chrome lining of the receiver had been omitted, to save cost in manufacturing. And by 1964, DuPont informed the government that it couldn’t keep up with demand for propellant.

The .223 Remington cartridge was devised by seating a 55-grain .223-caliber bullet over IMR 4475, a stick powder. Olin came up with an alternative, WC 846, a ball powder. While WC 486 did the job of propelling a 55-grain projectile at 3,300 feet per second, it burned dirty and produced a lot more fouling. Colt also decided it was good idea to bill the rifle as “self-cleaning” and therefore, soldiers didn’t need a cleaning kit.

Early editions of the rifle, had a storage compartment in the stock which contained a cleaning kit. In the first few years of its service history in Vietnam, there was no cleaning kit in there, nor did many infantrymen receive one.

Prior to that, the rifle was known to function reliably. It was accurate at ranges up to 500 yards and lethal. It had few stoppages. Bureaucratic in-fighting and corner-cutting would end up costing many US Army soldiers and US Marines their lives.

By 1965, all troops in-country were issued M16 rifles. Reports started coming in of frequent stoppages, usually failures to eject caused by constant fouling; dead soldiers were found clutching a cleaning rod. Keeping the rifles in working order required constant cleaning, often more than was feasible.

PFC John Henson of the 101st Airborne cleans his M16 rifle. Credit: US Army Post-Work: User:W.wolny [Public domain], via Wikimedia Commons

This led those who had the option to reach for BARs, Stoner rifles and M14s issued to South Vietnamese forces, or picking up AK-47s from dead North Vietnamese and Viet Cong troops.

Eventually, the US Government decided to do something about it and started making some fixes. The chamber and bore were chromed to reduce fouling, cleaning kits were issued more liberally, and new lubricants and propellants were developed to make the gun run cleaner and more reliably.

They also added a birdcage flash suppressor and – in limited batches – created a variant that fired three-round burst instead of full auto.

The fixes worked, and the new variant with said improvements – the M16A1, which first entered service in 1967 – was immediately noted as a drastic improvement over the original.

By 1969, the M14 had been officially knocked off its perch, and the M16A1 remained the standard service rifle until the M16A2 was introduced in the 1980s.

During the Vietnam war, NATO was advised that they should switch to the 5.56mm round instead of the then-standard 7.62x51mm round. NATO pretty much agreed, creating the now-standard 5.56mm NATO round.

After the war, the new standard 5.56mm NATO round (and experience) required some updates, which the US Marines and the army started asking for by the end of the 70s. The Marines asked for a heavier end to the barrel, a flash suppressor with a closed bottom, and sights that could be adjusted for windage and elevation on the fly.

They also wanted a round handguard as opposed the triangular handguard that had been the standard for so long, and they wanted to be able to put a grenade launcher on it (because freedom). Additionally, the twist rate was to be changed to 1:7 to accommodate heavier NATO rounds, including 62-grain tracer ammunition.

M16A2 upper. Note the sight adjustment controls outside the carrying handle. Credit: Fourdee via Wikimedia Commons

The firing mechanism was also changed to three-shot bursts, as it was found the full-auto M16A1 lent itself to “spraying and praying” by inexperienced operators. Pretty much everyone agreed, and those changes were instituted by the mid-80s and the rifle re-designated the M16A2. This rifle served as the official rifle of the US armed forces from the 1980s through the first Gulf War.

A limited number of M16A3s, with full-auto capability instead of 3-round bursts, were made for Navy SEAL and other special operations groups. However, the M16A2 remained in service until…pretty much a few years ago when they were finally phased out of Marine Corps service.

Throughout the Vietnam war, a number of carbine-length versions of the M16 were created and used in various capacities, called the Colt Commando. It wasn’t much at long range but was well-liked for close-in work.

Colt set about tuning it up in the 1980s, eventually settling on a variant with a 14.5-inch barrel. This gave the rifle the optimum balance between accuracy and compact form, along with an adjustable stock which let it be compacted even more.

M4 Carbines in a live-fire exercise. Credit: US Marine Corps Sgt. Devin Nichols [Public domain], via Wikimedia Commons

The then-XM4 was dubbed the M4, and saw its first real deployment in Kosovo. It performed so well that the Army started issuing more and more of them, even ordering officers up to Lt. Colonel in rank to stop carrying pistols and carry an M4 instead. It also replaced submachine guns for most uses. It became so common that the US Army had phased the M16 almost entirely out of front-line service by the early 2000s.

The US Marines also made some revisions in recent years to create the M16A4 variant. The M16A4 eliminated the round handguard in favor of a quad-rail handgaurd by Knight’s Armament. The carry handle and sights were eliminated in favor of a Picatinny rail running the entire length of the receiver to the end of the handguard, and combat optics (red dot sights) added in lieu of iron sights.

M16A4 in combat with the US Marine Corps. Note the optic and quad-rail handguard. Credit: U.S. Marine Corps photo by Cpl. James L. Yarboro [Public domain], via Wikimedia Commons

The M16A4 also added a muzzle compensator instead of a flash suppressor, installed a heavier barrel and free-floated it for greater accuracy. Bolt-catch releases and charging handles were changed to allow ambidextrous operation, and the trigger was improved for an easier pull. The M16A4 was also issued in semi-auto only in addition to the burst mode. Limited numbers of rifles with adjustable stocks were also issued by the Marines.

However, these improvements came a little late in the game. M16A4 rifles were issued in limited numbers starting in 2014 and 2015, which happened to coincide with the announcement that the Marine Corps was switching entirely to the M4 Carbine.

Some other changes occurred along the way. No longer entirely satisfied with Colt’s products, the Army and the Marines have both changed providers to FN. FN had already been making M16A4s for the USMC, but is now also producing M4s for the US Army and the Marines…though the Marine Corps is also in the process of phasing out the M4 in favor of the M27 IAR, an improved AR design by Heckler and Koch.

A member of Marine Force Recon firing the M27 IAR, an H&K-designed rifle based heavily on the M16. Credit: Staff Sgt. Ezekiel Kitandwe [Public domain], via Wikimedia Commons

Today, the M16 has been all but completely phased out except for some select examples that are still in service in front line and reserve units. The M4 has pretty much replaced it, which itself

is due to be replaced

soon. But, as we all know, nothing lasts.

Feel like I missed any important details? Need to tell us you’re vegan…again? Sound off in the comments!

via The Truth About Guns
The Guide To M16 History That You Never Knew You Needed

Here’s the Best USB-C Hub Deal…Ever?

Best Tech DealsThe best tech deals from around the web, updated daily.   

Turns out, having a laptop with only USB-C ports means you need to carry a dongle with you from time to time. Who knew? Luckily, these $15 hubs from VAVA ($15 clippable coupon + promo code KINJAVAHUB) are designed to perfectly match your MacBook, and turn one USB-C port into an ethernet port, an SD card reader, an HDMI output, and three USB 3.0 ports. There’s even pass-through USB-C charging, so you’re not even really using up one of your precious ports.

For comparison, the best previous deal we’ve seen on this hub was $27, which itself was pretty noteworthy. These things aren’t cheap! So if you have a USB-C-powered laptop (or even a phone or a tablet), and don’t already own something like this, I’d order it quickly before the deal goes kaput.

via Lifehacker
Here’s the Best USB-C Hub Deal…Ever?

Pelican 22-Ounce Traveler Stainless Steel Tumbler Review

Working and playing in the great outdoors isn’t always about camouflage and chainsaws. We gotta stay hydrated while we’re out there! And to that end, Pelican sent me one of their stainless steel vacuum tumblers to try out. After more than a year of regular use, it’s time to talk about it here.

Specifically, it’s the Pelican 22-Ounce “Traveler” tumbler. Here are some specs:

Manufacturer Specs

  • Double-wall vacuum insulation
  • 18/8 BPA-free stainless steel
  • Copper plated inner wall
  • Extreme cold & heat retention
  • Guaranteed for life (“You break it, we replace it… Forever”)
  • Spill-resistant lid with sliding cover
  • Generous “lip” on lid keeps your lips off of the stainless steel
  • Available colors: Black, OD Green, Seafoam, Stainless

It Works

I ordered my Pelican tumbler in OD Green, which is a really attractive color in my opinion. And even though my wife doesn’t usually love green, she commandeered my Pelican tumbler almost immediately. One reason is that when she drives somewhere with her sisters, this Pelican fits in cup holders where her other stainless tumbler just won’t.

Pelican claims it “fits in up to 99% of all car and truck cup holders,” and so far they’ve been correct.

The smaller portion at the base which allows it to fit so many cup holders also makes it easier to hold in your hand, and the shoulder helps prevent it from slipping down in wet (or weaker) hands.

As for ice retention, the Pelican Traveler is certainly up to snuff. Even after sitting in a closed vehicle in the hot Florida sun for hours, the Traveler still has ice inside. In fact, we had to stop filling it all the way with ice before adding water, because after drinking all the water, the ice would never melt! Being thirsty with a tumbler full of ice is no fun.

Pelican 22-Ounce Traveler stainless steel tumbler

Pelican 22-Ounce Traveler stainless steel tumbler
(Photo © Russ Chastain)

We Like the Lid

The Traveler’s lid is the best I’ve ever seen for one of these stainless vacuum tumblers. Instead of cramming it down into the tumbler and later fighting with a tight rubber seal to remove it, you just screw it on and off. Not only is it easier to put on and off — my sweetie says it doesn’t hurt her hands like other lids — but this also means the lid is not going to come flying off if you drop your Traveler.

The Pelican Traveler lid screws on securely and easily.

The Pelican Traveler lid screws on securely and easily.
(Photo © Russ Chastain)

The sliding cover is also a nice touch. This is great for dusty conditions like when you’re mowing the lawn or trail riding, and it helps prevent your drink from splashing out too.

The Traveler's lid has a sliding closure to prevent splashout or dust intrusion.

The Traveler’s lid has a sliding closure to prevent splashout or dust intrusion.
(Photo © Russ Chastain)

The cover is easily removed so you can thoroughly wash it and the lid.

The sliding cover can be easily removed for washing.

The sliding cover can be easily removed for washing.
(Photo © Russ Chastain)

Our other favorite feature of the Traveler’s lid is that your mouth doesn’t touch the tumbler when you drink. The lid has a large lip or spout area, which makes it easier and more pleasant to drink from than most stainless steel tumblers.

Pelican 22-Ounce Traveler stainless steel tumbler in OD Green

Pelican 22-Ounce Traveler stainless steel tumbler in OD Green
(Photo © Russ Chastain)

It’s Well-Made

The Traveler is a quality product, as is every Pelican product I’ve ever tried. It’s well-made, and the powder-coat finish has held up well.

Interior of Pelican 22-Ounce Traveler stainless steel tumbler

Interior of Pelican 22-Ounce Traveler stainless steel tumbler
(Photo © Russ Chastain)

Of course, the Pelican Traveler has the same recommendations as other vacuum-insulated stainless steel vessels: Don’t freeze it, don’t microwave it, and hand-wash instead of using the dishwasher.

Your Pelican tumbler should stay OUT of the microwave, freezer, and dishwasher.

Your Pelican tumbler should stay OUT of the microwave, freezer, and dishwasher.
(Photo © Russ Chastain)


The Pelican 22-Ounce Traveler stainless steel tumbler is a well-made drinking vessel that should last for a heck of a long time. It’s well-designed and durable, easy to hold, fits in most cup holders, won’t sweat, and has the best lid around.

We sure like ours, and my wife is certain to keep her claim on this one. And that’s okay, because I’d rather have the 32-ounce model anyhow…

As I write this, the 22-ounce Pelican Traveler is available for about $20 shipped ($21 if you want green).

The post Pelican 22-Ounce Traveler Stainless Steel Tumbler Review appeared first on

via All Outdoor
Pelican 22-Ounce Traveler Stainless Steel Tumbler Review

Build Your Own Glock Part 1. The Embryo

Welcome to TFB’s series on building your own Glock. In this series, we will take an 80% frame and a pile of parts, and assemble a safe and consistent G19. Believe it or not, it is very easy, and perfectly legal. You will see that with a bit of patience and minimal equipment you CAN build your own Glock. If you go with the standard parts and look, you may not save too much. If you want to go the custom route or are interested in having a pistol you created, AKA a “ghost gun”, this is the way to go.


Is this even legal? According to the ATF, yes, though state and local laws may be different. After my research, I was able to find an ATF agent kind enough to sit down with me. A great guy who was willing to go over all points with me. As with everything, it seems, it comes down to intent. If you intend on building a Glock for yourself you are fine. If you intend on building a firearm to sell or trade you need a firearms manufacturer license.  Build it, keep it and you are fine. Again, check your local laws.

The Build

Your Glock 80% receiver will ship all ready inside the jig. The jig is there to guide your cutting and drilling. Although it is counterintuitive, your building labor is actually removing material. The pin holes are not present, and there is extra material on the top of the receiver, as well the center.  That material should be removed to bring the receiver to “100%”

The jig arrives with the receiver in place. The drill holes are obvious here


The jig is clearly marked what material to remove


The jig is set up to guide you in removing the material. Here is some of the extra material to remove.

I found a video that gives some great advice on how to do it. It is done on an older (or at least different) 80% frame then I received, but the same ideas apply. You can see it here.

My frame came with a link to a PDF of the instructions. Find it here.


Initially, the drill press was my plan to remove the excess material. I had some problems with the jig getting bucked, so I stopped and went to the Dremel. A Dremel is a great tool, just do not go angry beaver and remove too much and destroy your frame. If you go with the Dremel I strongly recommend you remove about 75% of what you want to remove, then remove material by hand. I finished the work up with files and then sandpaper. As with anything like this, TAKE YOUR TIME.

When you have removed the material, finish with some fine sandpaper. Sanding it with oil will help you get a finer finish.

I still used the drill press for drilling the holes. I was told it was easy to not make the holes even by using a hand drill. Once you remove material, there is no putting it back.

On the 80% frame, you need to drill from the outside in. So you drill each side of the jig to the center, not all the way through.

Drill both sides, outside to center only

After the Dremel, I used files. A little tape allows me to know when I have taken off enough material

Close-up of where the material was removed, before finishing with sandpaper.


The area of the barrel block was easy to Dremel but challenging to finish up. This is just after the Dremel.


Bringing the 80% up to 100% was pretty easy. Just take your time. The more time you put into it, the better the completed product becomes. All it is removing 4 strips of material, and drilling 6 holes. Not too much, but plenty of opportunities to make a mistake. Spend more time with sandpaper then with the Dremel. I spent about 20 minutes on the Dremel and about 2 hours with sandpaper, and am very happy with the outcome.

A HUGE thanks to Lonewolf for coming thru with this, when others did not. Although they did not give me all this merchandise, they gave me a good discount. I ask that you consider them if you are going to build your own Glock.

Great company with good people. Check them out here.

A shout out to “Mr. J” who reached out to me and gave some great advice. He has built a number of these and gave some great insight. I very much appreciate it. His input has a lot of influence on the next article in the series.

We are committed to finding, researching, and recommending the best products. We earn commissions from purchases you make using the retail links in our product reviews.

Learn more about how this works


via The Firearm Blog
Build Your Own Glock Part 1. The Embryo

PHP JWT Authentication Tutorial

In this tutorial, we’ll learn how to add JWT authentication to our REST API PHP application.
We’ll see what JWT is and how it works. We’ll also see how to get the authorization header in PHP. What is JWT
JWT stands for JSON Web Token and comprised of user encrypted information that can be used to authenticate users and exchange information between clients and servers. When building REST API, instead of server sessions commonly used in PHP apps we tokens which are sent with HTTP headers from the server to clients where they are persisted (usually using local storage) then attached to every outgoing request originating from the client to the server. The server checks the token and allow or deny access to the request resource. RESTful APIs are stateless. This means that requests from clients should contain all the necessary information required to process the request. If you are building a REST API application using PHP, you are not going to use the $_SESSION variable to save data about the client’s session. This means, we can not access the state of a client (such as login state). In order to solve the issue, the client is responsible for perisiting the state locally and send it to the sever with each request. Since these important information are now persisted in the client local storage we need to protect it from eyes dropping. Enter JWTs. A JWT token is simply a JSON object that has information about the user. For example:
"user": "bob",
"email": "",
"access_token": "at145451sd451sd4e5r4",
"expire_at"; "11245454"
Since thos token can be tampered with to get access to protected resources. For example, a malicious user can change the previous token as follows to access admin only resources on the server:
"user": "administrator",
"email": ""
To prevent this situation, we JWTs need to be signed by the server. If the token is changed on the client side, the token’s signature will no longer be valid and the server will deny access to the requested resource.
How JWT Works
JWT tokens are simply encrypted user’s information like identifier, username, email and password. When users are successfully logged in the server, the latter will produce and send a JWT token back to the client. This JWT token will be persisted by the client using the browser’s local storage or cookies and attached with every outgoing request so if the user requests access to certain protected resources, the token needs to be checked first by the server to allow or deny access. What is PHP-JWT
php-jwt is a PHP library that allows you to encode and decode JSON Web Tokens (JWT) in PHP, conforming to RFC 7519.
You must have the following prerequsites to be able to follow this tutorial from scratch:
You need PHP 7, Composer and MySQL database system installed on your development environment,
You need to have basic knowledge of PHP and SQL.
Creating the MySQL Database and Table(s)
If you have the prerequisites, let’s get started by creating the MySQL database. We’ll be using the MySQL client installed with the server. Open a terminal and run the following command to invoke the client:
$ mysql -u root -p
You need to enter your MySQL password when prompted.
Next, let’s create a database using the following SQL instruction:
mysql> create database db;
Note: Here we assume you have a MySQL user called root. You need to change that to the name of an existing MySQL user.
You can also use phpMyAdmin or any MySQL client you are comfortable with to create the database and SQL tables.
Let’s now select the db database and create a users table that will hold the users of our application:
mysql> use db;
`first_name` VARCHAR(150) NOT NULL ,
`last_name` VARCHAR(150) NOT NULL ,
`email` VARCHAR(255),
`password` VARCHAR(255),
PRIMARY KEY (`id`) );
Creating the Project Directory Structure
Let’s create a simple directory strucutre for our project. In your terminal, navigate to your working directory and create a folder for our project:
$ mkdir php-jwt-example
$ cd php-jwt-example
$ mkdir api && cd api
$ mkdir config
We first created the project’s directory. Next, we created an api folder. Inside it, we created a config folder. Connecting to your MySQL Database in PHP
Navigate to the config folder and create a database.php file with the following code:
// used to get mysql database connection
class DatabaseService{
private $db_host = "localhost";
private $db_name = "mydb";
private $db_user = "root";
private $db_password = "";
private $connection;
public function getConnection(){
$this->connection = null;
$this->connection = new PDO("mysql:host=" . $this->db_host . ";dbname=" . $this->db_name, $this->db_user, $this->db_password);
}catch(PDOException $exception){
echo "Connection failed: " . $exception->getMessage();
return $this->connection;
Installing php-jwt
Let’s now proceed to install the php-jwt library using Composer. In your terminal, run the following command from the root of your project’s directory:
$ composer require firebase/php-jwt
This will donwload the php-jwt library into a vendor folder.
You can require the php-jwt library to encode and decode JWT tokens using the following code:
<?php require "vendor/autoload.php";
use \Firebase\JWT\JWT;
Adding the User Registration API Endpoint
Inside the api folder, create a register.php file and add the following code to create a new user in the MySQL database:
include_once ‘./config/database.php’;
header("Access-Control-Allow-Origin: * ");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$firstName = ”;
$lastName = ”;
$email = ”;
$password = ”;
$conn = null;
$databaseService = new DatabaseService();
$conn = $databaseService->getConnection();
$data = json_decode(file_get_contents("php://input"));
$firstName = $data->first_name;
$lastName = $data->last_name;
$email = $data->email;
$password = $data->password;
$table_name = ‘Users’;
$query = "INSERT INTO " . $table_name . "
SET first_name = :firstname,
last_name = :lastname,
email = :email,
password = :password";
$stmt = $conn->prepare($query);
$stmt->bindParam(‘:firstname’, $firstName);
$stmt->bindParam(‘:lastname’, $lastName);
$stmt->bindParam(‘:email’, $email);
$password_hash = password_hash($password, PASSWORD_BCRYPT);
$stmt->bindParam(‘:password’, $password_hash);
echo json_encode(array("message" => "User was successfully registered."));
echo json_encode(array("message" => "Unable to register the user."));
Adding the User Login API Endpoint
Inside the api folder, create a login.php file and add the following code to check the user credentials and return a JWT token to the client:
include_once ‘./config/database.php’;
require "../vendor/autoload.php";
use \Firebase\JWT\JWT;
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$email = ”;
$password = ”;
$databaseService = new DatabaseService();
$conn = $databaseService->getConnection();
$data = json_decode(file_get_contents("php://input"));
$email = $data->email;
$password = $data->password;
$table_name = ‘Users’;
$query = "SELECT id, first_name, last_name, password FROM " . $table_name . " WHERE email = ? LIMIT 0,1";
$stmt = $conn->prepare( $query );
$stmt->bindParam(1, $email);
$num = $stmt->rowCount();
if($num > 0){
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$id = $row[‘id’];
$firstname = $row[‘first_name’];
$lastname = $row[‘last_name’];
$password2 = $row[‘password’];
if(password_verify($password, $password2))
$secret_key = "YOUR_SECRET_KEY";
$issuer_claim = "THE_ISSUER";
$audience_claim = "THE_AUDIENCE";
$issuedat_claim = TIME_IN_SECONDS; // issued at
$notbefore_claim = TIME_IN_SECONDS; //not before
$token = array(
"iss" => $issuer_claim,
"aud" => $audience_claim,
"iat" => $issuedat_claim,
"nbf" => $notbefore_claim,
"data" => array(
"id" => $id,
"firstname" => $firstname,
"lastname" => $lastname,
"email" => $email
$jwt = JWT::encode($token, $secret_key);
echo json_encode(
"message" => "Successful login.",
"jwt" => $jwt
echo json_encode(array("message" => "Login failed.", "password" => $password, "password2" => $password2));
We now have two restful endpoints for registering and log users in. At this point, you can use a REST client like Postman to intercat with the API.
First, start your PHP server using the following command:
$ php -S
A development server will be running from the address.
Let’s now, create a user in the database by sending a POST request to the api/register.php endpoint with a JSON body that contains the first_name, last_name, email and password:
You should get an 200 HTTP response with a User was successfully registered. message.
Next, you need to send a POST request to the /api/login.php endpoint with a JSON body that contains the email and password used for registering the user:
You should get a Successful login message with a JWT token.
The JWT token needs to be persisted in your browser’s local storage or cookies using JavaScript then attached to each send HTTP request to access a protected resource on your PHP server.
Protecting an API Endpoint Using JWT
Let’s now see how we can protected our server endpoints using JWT tokens. Before accessing an endpoint a JWT token is sent with every request from the client. The server needs to decode the JWT and check if it’s valid before allowing access to the endpoint.
Inside the api folder, create a protected.php file and add the following code:
include_once ‘./config/database.php’;
require "../vendor/autoload.php";
use \Firebase\JWT\JWT;
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
$secret_key = "YOUR_SECRET_KEY";
$jwt = null;
$databaseService = new DatabaseService();
$conn = $databaseService->getConnection();
$data = json_decode(file_get_contents("php://input"));
$arr = explode(" ", $authHeader);
/*echo json_encode(array(
"message" => "sd" .$arr[1]
$jwt = $arr[1];
try {
$decoded = JWT::decode($jwt, $secret_key, array(‘HS256’));
// Access is granted. Add code of the operation here echo json_encode(array(
"message" => "Access granted:",
"error" => $e->getMessage()
}catch (Exception $e){
echo json_encode(array(
"message" => "Access denied.",
"error" => $e->getMessage()
You can now send a POST request with an Authorization header in the following formats:
JWT <YOUR_JWT_TOKEN_HERE> Or also using the bearer format:
In this tutorial, we’ve seen how to implement JWT authentication in PHP and MySQL.
via Planet MySQL
PHP JWT Authentication Tutorial

The Best Under-Sink Water Filter

The Best Under-Sink Water Filter

Anyone who goes through more than a couple of gallons of drinking water a day will probably be happiest with an under-sink filtration system like the Aquasana AQ-5200. If you prefer (or need) filtered water, this provides a continuous supply of it on demand from a separate tap. We recommend the Aquasana AQ-5200 because its certifications are among the best of any system we’ve found.

via Wirecutter: Reviews for the Real World
The Best Under-Sink Water Filter

Laravel Money

Laravel Money

Laravel Money is a composer package by Ricardo Gobbo de Souza for working with and formatting money in Laravel projects.

Laravel money uses the moneyphp/money PHP package under the hood and gives you a bunch of helpers:

use Cknow\Money\Money; echo Money::USD(500); // $5.00 

This package includes a ton of advanced features for doing money operations, comparisons, aggregations, formatting, and parsing:

// Basic operations Money::USD(500)->add(Money::USD(500)); // $10.00 Money::USD(500)->subtract(Money::USD(400)); // $1.00 // Aggregation Money::min(Money::USD(100), Money::USD(200), Money::USD(300)); // Money::USD(100) // Formatters Money::USD(500)->format(); // $5.00 // Parsers Money::parse('$1.00'); // Money::USD(100) 

You can also create a custom formatter for your specific use-case:

Money::USD(500)->formatByFormatter(new MyFormatter()); 

Be sure to check out the advanced usage and included helper functions in the project’s README file. Also, check out the Money PHP documentation for complete details of what this package is capable of doing.

You can learn more about this package and check out the source code on GitHub at cknow/laravel-money.

Filed in: News / packages

Enjoy this? Get Laravel News delivered straight to your inbox every Sunday.

No Spam, ever. We’ll never share your email address and you can opt out at any time.

via Laravel News
Laravel Money

Westworld Welcomes Lena Waithe to Season Three

Lena Waithe at he 2019 Winter Television Critics Association Press Tour.
Photo: Frederick M. Brown (Getty)

Westworld’s last season ended with the power dynamics between the titular park’s human guests and cybernetic hosts shifting in a radical way as the inorganic beings moved forward on their path to wrestling freedom from their creators. But for the show’s next season, the cast is getting larger in order to tell even more stories about new characters.

According to The Hollywood Reporter, Master of None’s Lena Waithe is set to join Westworld’s third season in a role that, like Aaron Paul’s, is being kept secret ahead of the show’s 2020 premiere. It’s anyone’s guess whether Waithe will be portraying a human, a host, or, perhaps both.

[The Hollywood Reporter]

For more, make sure you’re following us on our new Instagram @io9dotcom.

via Gizmodo
Westworld Welcomes Lena Waithe to Season Three