I built Cloudflare Images in PHP (to scale & compress images)
In this video I built a very basic version of Cloudflare's image proxy that we use on our various sites, like highperformancesqlite.com. It's a single controller in our Laravel application!
Everything I said
This is what we wanna recreate in Laravel, transforming via URL from Cloudflare Images. So if you're not familiar with Cloudflare Images, it is a great product, um, and it allows you to do all kinds of stuff like change the width and the quality and flip it and change the format and change the gamma. So it's kinda like one of those image manipulation proxies, and we're gonna rebuild it in Laravel, just, just a little bit.
We're not gonna rebuild the whole thing. But what I really want to be able to do is, um, change the size of images. So we've got a couple of different websites, including highperformancesqlite.com, and if you go to /images/aaron, you'll see, hey, who is that guy? Big image. Big old image. And so I wanna make a way in Laravel...
We gotta get him out of here. I- uh, w- I wanna make a way in Laravel to where we can do this work on our server, and then it's cached forever on your CDN. And in our case, that is on Cloudflare, but that might not be Cloudflare for you. So let's look at how we can implement this in Laravel. First thing we're gonna do is I'm here in, uh, my routes folder, and I'm just gonna write route get.
And then, um, we're gonna kinda copy the style from over here, so transform via URL. How do they do theirs? It looks like they do, um, they throw the options right here in the middle, and then they have the path here at the end. So we're gonna get rid of this cdn-cgi, and we're just gonna do options and then path. Now, we could append, uh, we could do it via query strings at the end, but I do know that some CDNs don't, uh, they don't play nicely with query strings when it comes to
caching. And you know what? I trust Cloudflare, so we're just gonna go with whatever Cloudflare says. So we're gonna set, uh, options here in the middle, and then we're gonna set path here at the end. So, meh, that's off to a pretty good start. Now, we need to put, uh, we need to put a few constraints on this, so we're gonna say where, uh, where options, and then we're gonna pass in a regex, and then we're gonna say, uh, where path, and we're gonna pass in a regex as well.
Now, this one, we need to be able to match, uh, forward slashes because this path, of course, might end up being, you know, a, b, c /aaron.jpg, something like that. So this wild card down here will match those forward slashes. I wanna add one more thing, which is, um, I want to add...
I want to make sure that there is a period there, and then we can add, uh, we can add any extension. I don't really care what the extension is, but this just scopes it down to make sure that this route ends in a dot something, and that is gonna, uh, prevent false positives. Now, what do we wanna put in here? We have to put something in here, and it's gonna be a little bit tricky.
The good news is all of our transformations contain an equals sign, so it's always key equals value. So quality equals 100 or quality equals 10 or something like that. So we're just gonna make sure that there is an equal sign in this options part of the path. Let's see if we can hand write this. We're gonna say a to z, a to z, equals, um, and that can be multiple times.
So this is going to match foo equals, and then we need a to z. Uh, that is actually right except for that. So, uh, foo equals bar. That should match that. Foo equals bar 1-2-3. Foo equals 123. It should match all of those, including uppercase, which shouldn't super matter.
Now, we can have multiple options here, so as we saw in the Cloudflare docs, we can have comma baz equals 123. So we need to add a comma that is optional and then say that all of this can happen more than one time. Um, so I think we have...
Yeah, that looks right to me. So we've got the key part is right here, so this is the key, a to z, a to z, uh, multiple times equals, and then this is the value part, a to z, a to z, 0 to 9, multiple times, and then an optional comma. And then all of this can happen multiple times, which is that plus sign right there.
Kind of amazing that I still remember all of this. All right. Let's go make a controller. We're gonna say artisan make, uh, and we're just gonna make an image controller, and then we can hop over here and say that imageController, imageController class, and then show seems... That seems fine to me. So if we pop over and create public function show.
Nice. That got it right. Options and path. So we'll say DD options. Let's take a look and see if we got our regexes correct. Um, okay, so coming out over here, we can say quality... Oh, looks like I've already been testing. There we go. So, uh, this should be the options.
Yep, that looks correct. That should be the path. That looks correct. So if we drop, uh, that still looks correct. And if we change this to just one parameter, that looks correct. And then if we say foobar, that looks correct. And if we change this to all caps, that looks correct. All right. We got our regexes right, which is not always guaranteed, but we did get them right in this case.
Now let's actually start, uh, processing these images. Under the hood, I have installed, uh, the excellent image manipulation library for Laravel called Intervention because I don't wanna write all that code myself, and it's a very rock-solid library. So first thing we're gonna do is we're going to take the path and change it to public path of the path, and so then we can DD that and see if, uh...
Yep, there you go. Tryhard platform, public, Aaron. So that image actually doesn't exist, which is important. So we want to say, um, let's do abort if- Um, no, we can do abort unless, that's cleaner. Ab- abort unless file exists path with a 404, um, otherwise DD yes.
So this should give us a 404, which it does, but if we change it to images, Erin, it should come back as, um... I wonder... Oh, that's because I messed that up. There we go. So yes, we did pass. That file does exist. So this is good so far. This is the exact behavior that we want. Uh, if the file isn't publicly available, we're just going to abort with a 404.
Okay. Now, we're going to use image read. Um, I think this is supposed to be the facade. So let's say image, and we want that one, and we'll say read path. So this becomes our image. Now, what are we gonna do with this image? First, I think we need to parse out these options. Let's come back up here, and let's see what these options are right now.
So right now they're just strings. We'll change this back to one we actually want to support, and we'll put a comma in here, which is weird to me, but that is how Cloudflare does it, and we'll say that. All right. Now, let's come down here, and once we're sure that the image exists, let's say that options equal this parse options, and we'll say options there.
Now, we can do a protected function parse options, and we'll come down here. Now what do we wanna do? Um, let's just return a collection of explode on the comma. So we're gonna explode on the comma, and we can just DD these out as we're working.
Okay, so we now have two. That is close. That's very good. Now, we are going to... uh, we're gonna use map with keys, um, and once we get in here, we've got a singular option. So that should be option. There we go. Quality equals one, two, three. Perfect. Now, hmm, we'll say that parsed equals explode, and we are going to explode on the equal, and that should give us,
that should give us... Yep, that's good. And then what I'm gonna do... What do I do if somebody doesn't pass a value? Actually, that should get caught by the regex at the route level. So we should be safe to just do... Yeah, if we can spell return right, we should be safe to just do it like this.
And that will give us, uh, we can, uh... Yeah, we'll to array that, and boom. There we go. So now we have an associative array of keys and values, and I think, like I said, if somebody doesn't pass that in, yeah, you're just gonna get a 404 'cause that actually doesn't match the routing regex at the top.
So yeah, w- we're in a pretty good spot now. Okay, now we have our requests being routed to the correct controller. Our options are being parsed. We know that the file exists, otherwise we're just aborting with a 404. Now, let's actually scale and manipulate this image. So coming back up here, we've got our options that have been fully parsed, and now we're gonna do this.
Um, we're gonna say if width or height exist, then let's go ahead and scale the image. Um, yes, that is correct, and yes, that is correct. And wow, I'm not doing anything here. Um, okay. So we're going to scale down. And now there is a, uh, there is a scale, but I'm gonna scale down only, one, because we, we just personally, like for our platform, we don't need to scale up.
But I also don't want someone scaling up to like ten thousand pixels just to hammer my server just because they're being hysterical. So I don't wanna do any of that. Now, what are the other ones I wanna support? I want to support format without the E, and I want to support quality. So let's do this. Let's do, um, format equals file extension.
I don't think that's right. Um, actually, that could be right. Let's see what the, um, let's see what the Cloudflare docs say for format. Um, great. So yeah, extension, extension would be just fine. Uh, we're not gonna do JSON. That doesn't make any sense to me. So we're gonna do, uh... Yeah, we'll do some of those.
So file extension path is a good start. Um, we can also do... Let's do it like this. We'll do, not request. Um, we'll do R get. From the options, we'll get the format, and if the format doesn't exist, then that gives us the default as whatever the, uh, file type is.
So format is JPG. Now, if I were to change, if I were to change format equals PNG... Great, now it changed to PM- PNG. Okay, so we're off to a good start. Let's do quality as well. We'll do, um, from the options, get quality, otherwise let's do one hundred, and we're gonna throw, uh, an int on that at the front.
Um, I don't know that that will end up mattering, but those are gonna come in as strings. So we could do that up here, scale down. Um, those will just get cast, but yeah, I don't wanna cast. Yeah, we're gonna leave that alone for now. All right, so we have format and quality, and now we can do, we can do a switch statement on format, and we gotta figure out, let's see, case PNG, um, we gotta figure out how are we going to encode
this as, uh, a different format now. So we're gonna go look at the intervention docs to see how that actually works, and then we'll come back into our controller and write all of that in. Looking at the intervention docs, uh, we are... So we're doing this. We're doing the read from the path to get an instance of the image. This is what we're after. We want to encode the image, and in our case, we're going to pass through an encoder with a quality setting.
So let's come back over here, and instead of doing this, let's do a, uh, match on format, and we'll say encoder equals match on format, and PNG is going to be, I think, PNG encoder. Yeah, that looks good. Let's do, um, make a new instance, new PNG encoder, and it does not take a quality, so we're gonna leave that alone.
So now we should have, uh, we should have an encoder down here if it is still PNG. Boom. There we go. We've got our PNG encoder. All right, let's do a few more. I think default is going to be JPEG. Yep, that's right. There we go. That's what I'm after. Quality is set to quality. Um, so that's probably good enough for now.
I mean, if you want WebP, I guess we could do WebP encoder. Does this accept a quality? It does accept a quality. We do love that. So we'll go ahead and add a WebP encoder as well. All right, so now we have our encoder. Can we just call image encode? Does it take an encoder?
Heck yeah, it does. So now we have our encoder. So by default, it's gonna be JPEG. If you, uh, request PNG or WebP, you'll get that. Now we need to return the image to the browser. That's not gonna be quite right, but that may be close. Um, PNG, yeah, that's not quite right, so we gotta figure out how do we return this thing out to the browser.
So we need to return the contents of the image, but we also need to pass along, uh, the MIME type to tell the browser what type of image it is, and then here in a second, we're gonna add some cache control headers as well so that your CDN, um, in my case, Cloudflare, your CDN will cache this image for a super long time, so you're not constantly transforming this image on every request.
All right, the first thing we're gonna do is get this image out to the browser. So we're gonna return a response. We're just gonna wrap it up, and we'll say encoded equals encoded and 200. This is not... I mean, it's gonna kinda work, but it's not really gonna work. Um, so there we go. We get all of the image data, uh, and the PNG, but because we didn't return the MIME type, it's not going to be right.
So content type is not actually format. We're actually gonna pull this... We're gonna pull that off of the encoded image. So we're just gonna leverage the encoder to tell us, and if we take a look here, you'll see image PNG. Good. That's what we're after. Now we should... Hey, there we go. We got, uh, we got an image for PNG.
What about JPG? Uh, nope, and that is because the quality is too high. Now, uh, do I care about this? I don't think I care about this, um, because we're just using this internally. If you are exposing this as an API, you might wanna add some verification, but you can see that the quality does in fact work.
So that's off to a pretty good start. What else did we add? I think we did add height. So we can now say comma, we'll say width equals 100. There we go. There is a little terrible quality thumbnail. We can bump that up to 90. Well, it's so small. Let's just bump it up to 100. There you go. All right, we have two more things to do.
One is making sure that the caching actually works 'cause I only wanna perform this on my server basically one time, and then I want Cloudflare to hang on to it forever. The second thing we need to add is some sort of rate limit. So I don't want somebody to write a for loop and resize these images over and over and over just 'cause they don't like me.
So we need to add rate limiting and cache control. Let's start with caching. For caching, we need to do a couple of things. The first is we need to add this header. So what I'm doing here, I just pasted it in 'cause it's a lot of typing, is I'm setting the cache control header, and I'm saying that this asset is public. This is public. It is fine to be cached. The max age is 30 days, and then the shared max age is 30 days as well.
I don't know that we need both of these in this case, but this just tells the intermediate CDN how long it can hang on to it for, and because, uh, I want it to hang on to it for a long time, I put it at 30 days. Honestly, we could go up to a year if we wanted. Um, and then I said it's immutable, and what this means is this is, um, this is telling the CDN, "You never have to check back with me.
This is never, ever, ever, ever going to change." Now, that is perfect for our use case. That might not be perfect for your use case because there's no way to purge this from the cache with, like, an ETag or anything like that 'cause I said it is immutable. What you could do if you absolutely have to, I would recommend just renaming the file, but what you could do is you could throw a V equals two, three, four, five right there in the middle, and that option will be ignored, but that is a fundamentally discrete
URL. And so Bunny, CDN, Cloudflare, whoever is gonna look at that and say, "No, it's a brand-new URL. Let me go back to the origin server, do the computation, and then I'll cache whatever I get back." So you kinda have to decide if you want to do immutable or you want to do an ETag or whatever you want. I like immutable. If we change the image, we'll change the name.
That's fine with me. Now, this is actually not all we need to do. Um, so if we look, because of the way we have this route set up here, um, let's take a look at the network, and we'll say image, and we'll refresh this here. Uh, let's just do all. We see scrolling down the response headers, we did get our, uh, cache control immutable.
That's the stuff we wrote. But look, we also got the Laravel cookies. So we got the session cookie down here and the, uh, CSRF token. In this case, it's encoded, so it's XSRF, hard to say. Um, this is gonna cause Cloudflare to not cache this image. When these cookies come along, Cloudflare looks at it and says, "Ah, I'm not gonna cache that.
That feels like..." Even though I told it it is a public asset, Cloudflare looks at this and says, "Hmm, that feels like a private asset to me. There are cookies attached to it. I'm not caching that." So you have a couple of different options here. One is you could declare your route outside of Laravel's web, um, middleware, which adds the start session cookies.
So you could declare it out in a totally separate place. What I'm gonna do is I'm just gonna add a middleware that strips all cookies off of this particular route. First thing, um, we need to do here is I'm gonna give this a name of image.show. So by naming this route, I can now address it in this middleware. This middleware is very simple.
So this is called stripCookies, and what it does is it just checks to see if the route is image.show, and if it is, it removes all set cookie headers. So you might not be totally familiar with this part. What we're doing is we're actually, um, sending it all the way through the middleware and routing pipeline and then getting the response, and then after it's all been handled, then we will check the response, or we'll check the request and see if the response
has that header. We will remove it, and then we will return the response. Now, why did we not just add it here, um, instead of, uh, having to check the name? Because we need this to run absolutely last, and if you put it here, um, it's going to run within the web stack of the middleware. So if we come to app.php, you'll see we put this guy, we put this guy absolutely first.
So we prepended it to the web middleware group, and we put it absolutely first, which means, um, in a weird turn of events, it's going to run absolutely last because we're running it through everything, and then we're gonna strip the headers off of it. So let's come back to the browser, and we will refresh this page, and we will see, look, no set cookie header whatsoever.
And if we comment that out just to prove it, you'll see set cookie comes back, and now there you go. Set cookie is gone. All right. So we have added our cache control headers, and we've removed the cookies that would cause Cloudflare not to cache this. The final thing that we have to do is add just a tiny bit of rate limiting.
We're gonna come up here and just throw a rate limit here at the top, and we need to pass through request and path. Yes, that looks correct. Now we can hop down here and say protected function rate limit with the request and the path, and we're not actually gonna return anything because we are going to throw an exception.
So, uh, we're gonna use Laravel's built-in rate limiter, and we're gonna say allowed equals rate limiter attempt. Now, this attempt takes a key, and we're gonna say, um, let's just say transform. Transform, and we're gonna do request IP. Now, to get the actual user's IP, you do need to make sure that your trusted proxies are set up, 'cause otherwise you'll just get Cloudflare's IP over and over and over, or your CDN
of choice, or your load balancer, or whatever. So those are all of the Cloudflare proxies, and that ensures that this gets the user's IP. So then we're going to say path after that. And the max attempts per minute, it's gonna be two, pretty low. And the callback is just we're going to return true. So two feels really low, but you have to remember, um, most people will never, ever, ever hit the server because it should be cached for 30 days on Cloudflare.
So one unlucky user is going to have to transform this image for us, but after that, everyone gets it served directly from Cloudflare. And because we dropped out, um, from this key, because we dropped out the options, you can only transform, like you can only transform Aaron.jpg twice per minute, which is more than enough.
That's way more than enough, 'cause you only really need it once. Um, 'cause we're not gonna put two of the same image on the same page resized differently, and we're definitely not gonna put three on there. So if we come down here and we see if allowed passes, we can check over here, and allowed did pass. And I'll just show you, we'll burn up our rate limit here one more time, and now it fails.
Even if you change the, uh, quality, it still fails, which is what we want. That is the goal. This is what we're trying to protect against. So we will throw, unless allowed, we're gonna throw not a rate limit. We're actually gonna throw a new HTTP response exception, which accepts a response.
So we're down here deep in the stack somewhere, and we're just gonna throw a redirect to the image. So even in the failure case, you're still gonna get the image back, ideally served from cache from Cloudflare as well. So there we go. You'll see it redirected back to the main image without any, uh, without any transformations.
We'll change the key just a little bit to see if we can get it to load again, and there we go. Now we have not hit the rate limit. We've not hit the rate limit. We have hit the rate limit. Hey, pretty good. Not bad, right? All right, this is exactly what I'm after. I know that it's not fully Cloudflare Images, but it's the parts that I need, and if I need to implement any more transformations, I can come to that single controller and throw it in there.
So we've got caching, we've got rate limiting, we've got image transformation, and all of this stuff is going to be cached by my CDN, which in fact is Cloudflare. Um, but this is a very easy way for us to handle all of this locally. I hope that you enjoyed this. I will leave a link to the blog post, uh, where I have all of this code down below. So if you wanna go copy and paste the code, you can.
Until the next time, see ya.