Currently looking at building my first PHP function that will do exactly what the title says.
Step 1) Open the first img file in a directory
Step 2) Run an image optimisation API from an external server or local git copy
Step 3) Over write the current file
Step 4) Repeat until all files have been checked
Step 5) Exit the function and display all the results on the front end
Now this sounds really simple when I lay it out in 5 steps, but being a total beginner I’m not sure where to start.
Should I be looking for snippets of code in a PHP Cookbook and trying to combine these all together. Is an objective method the way to go?
You’ve successfully broken down the process into it’s component steps.
Now take each step, and convert it into code.
The hardest part will be the external API; as i presume you’re going to have to POST the image data to it. [cURL is your buzzword here]
Step 4 is to wrap steps 1-3 in a while. Step 5 is to add data collection to the whole thing for returning. [Generally, functions dont write to the screen directly]
Okay if the API does external fetching instead of requiring you to upload the file, you wont need cURL at all - file get contents would suffice.
So based on your example, and what you’ve said, here’s the revised set of steps your program should take.
Create Blank Output Array
Start While On Different Directories (Step 4a)
Get Current Directory Listing [Either a scandir or a glob]
Start Foreach on list of filenames (Step 4b)
Manufacture external URL (“$s” in your example) of current file (Step 1)
Send created URL to external API (Step 2)
Get Contents of post-API image from URL contained in JSON returned and save it (Step 3)
Generate output message and store to array (Step 5)
EndForeach
EndWhile
Return Ouput Array