Hướng dẫn create a rest api using basic php with token authentication download - tạo một api còn lại bằng php cơ bản với tải xuống xác thực mã thông báo

Transcripts

1. Introduction: Hello and welcome to my course. I am Michael Spinks, and in this course I will be sure knew how to create rest full Web services. With PHP no third party free works appeared software is needed. We'll be covering the basics of what rest is and how table Amend the beer six years in pure vanilla PHP. At the end of this course, you should be able to create a basic rest ful Web service that you can allow other people to use. The course will follow a scenario that we have been given. It is to implement a Web service which can record a list of tasks. Basically, a to do list will be implemented, each requirement one at a time. Then we will add on the ability for this E p I to become a multi user service. So each user can security have their own tests first. To do this, we'll be implementing an authentication concept called Talk and Beer Store Syndication, and we will be exploring this further within the course. Talking baseball syndication is a lot more secure than just basic password authentication and is now the best practice among the industry. We'll be starting at the beginning and building is weak or as long as you know the basics of PHP, such as variables. If statements loops in arrears, you should be able to follow this call through to the end. We'll also be using my SQL for the date appears to stall the tasks they were building and changing the database as we go. And again, you don't need to be an expert in my SQL, but you just need to know the fundamentals such as basic select, updated delete statement and concepts such as primary keys and foreign keys. Okay, let's get started. 2. Course Contents and Project Scenario: Okay, This is what we're going to cover throughout this calls. I will try and keep the Syria through minimum to get under the practical tasks quicker because no one really likes the born theory part. However, the theory I've added is necessary just working grasp of fundamentals. We'll be starting by giving you a brief overview of our given scenario so you can start thinking about the requirements and actually to give you an idea of what we're actually going to produce, where they're going to run through the basics of rest and how it is implemented. Then before we can start, I'll show you what software we're going to use. This is all free and downloadable off the Internet. We will then download and install the software together. Although this is basic, it is good to do this together because they were all starting from the same point. Well, then, throw specific requirements for the FBI. This is the actual de deal on what the FBI needs to do well, then get on and actually start the Rembrandt Asian by first creating the deer dubious and setting up the tables be used appeared to be my admin for that and will be guiding you through, basically, step by step. The next is where the largest amount of workers don't. This is the actual implementation of the PHP court. This includes testing at every stage to make sure it first all works, and second, it'll fulfills the requirements from of scenario. Then we'll move on to the talkin baseball's indication. This can be a little dry, although it's really good to understand how it works. I'll explain the basics of this and talk you through how and why. This is now an industry best practice. We will build the authentication module, which will then be used to security, authenticate users Well, then go back to our A p i court and not in the authentication requirement and re factor the court where needed. Although this should be kept to the minimum. This is where we'll fulfill the requirements to only allow users to view, update and delete that one tasks, and then finally, we'll run through. The FBI from Started finished demonstrating the A P I and two went, including authentication. Then there's a bit of a bonus material. I'll show you a quick sort of client application and I've developed, although really sort of thrown together to show you how this a P I can be used with an iPhone up, for example. So this is a story, a way of being given. We need a build a task list system that will allow users to log in and create updated and delete tasks. Each user's task will be private of them, and other users will not be able to view or modify them. Were responsible for the database back end the Web services on the authentication module. However, we're not responsible for the front end. All the service set up this is beyond the scope of this course. 3. What is REST?: So what is arrest? Really? A P I rest stands for representational steer transfer rest api Eisen interferes. That is stainless. So if each requests the receiving system doesn't know anything about any previous requests . He uses a client server model by your request to response architecture utilises the standard http verbs and status courts such as get posed patch and delete. This allows you to create read update until the theater this is also known as crude is important or that rest is not a standard. It is a set of principles that, if any p I was to follow would make a rest ful. Rest is generally preferred over sort. Dude would simply implementation, and Morsi uses Jason for the response output. Jason is simpler and less for Boston XML, which is what syllabuses. We'll be using Jason exclusively in this course. Examples of what an e. P. I can be used for our Lord and update their to use neckline application. This may be mobile or desktop application. So, for example, if you use Facebook on a smartphone when you request your friend list that calls a Facebook G p I to retrieve the friend list or It could be the fact that your blood in image from your smartphone to share with your friends on the social networks such as Facebook the FBI usage is hidden from the user is a client application carries out the necessary actions using the API eyes on the uses behalf. Example. Usage of arrest. Feli api I to get user details of a user with an idea of one is get slash users slash one the slash one is the user i. D. So how was it implemented? The rest Filippi eyes implemented using the CPI verbs that is sent with a request post is used to create. Get is used to retrieve patches. Usedto idiot Put is used to replace and delete has used for delete the most common verbs that a used deer, the deer get and paused when using a Web roses such as Google crawl and you click a link toe open appeared. This is a get request, as you were getting or retrieving the data that is on the peered from the server. If you ever filled out a form on a website and press the submit button, then you reviews paused as you have posted the form theater to the server. The post request will usually have a request body, as you were supplying some deer did to the server for the service of process. The survey takes requests and process it and then replies with a response. This includes any output as well as the HDP Response Court. So for the request, get uses slash one to get the user with i d. One That would reply, for example, with a status court of 200 which basically means walk here. That was received and it worked, and then it respond back with the body in the request. So, for example, we have an I d hear of Want the name of the user in an age of the user. The http status cords, the common ones listed here. But there's many more. There's a good website and put it on screen. Now for http. Steelers courts have a look at this website and you'll be able to see a lot more detail about what each theater's called means. So 200 is used for or care. If you were creating a user by using the post create, then that should respond back if it was successful with 21 response. Accord 400 is basically used for if something is not formatted correctly on the request, so see it had mandatory fields for creating a user such as name, and you sort of forgot to put that in or missed it out on purpose. What should reply back with is a 41 record, which is about request because you've missed out of military data. The 41 court is for unauthorized. So, basically, if you if you go to an end point and you haven't logged in or you don't have access furniture before warn unauthorized. Basically telling you that you need to authenticate 43 sort of goes hand in hand with for a one. If you have authenticated Butch, you don't have access. So, for example, if you are a general user and only administrative users can perform in action such as reset someone's password or something like that. So if you're a general user and you try to be set someone's past bridge, it should be a 43 forbidden because you are not allowed to do that on your administrator is four or four. You're probably seeing generally browse and using a Web browser anywhere. It's where you click on the link and the links dead, so the end point is not available. So if we go to sees, get slash users slash five. In a user with the idea of five doesn't exist, you should get a full for her four or five. Is method not allowed? Saw apart from these methods? Down this left hand side here, there's this many more, but these are the general ones are used in a rest API I. If we try and delete all users using the route, delete slash users that shouldn't be allowed because generally utility uses one of the time . Whereas if you paused, which is create slash users that should lower you to create one user. If you were deleting the user, you would delete did the beginning the verb slash users slash i D. So you delete that one user now. Obviously, if you try and delete all users using delete slash users, you should get a four or five method not allowed. The conflict of four or nine error is if you try and create a duplicate. So say you create user that has a duplicate years and am, for example, that should return a four relying conflict Error 500 error is usually the processing on the server has field, and usually what will happen is you'll get a 500 arrow with the generic response or depending how you call this. It might actually respond with an appropriate error message. So to call the FBI's will use you are Ln points thes air known as roots or out, depending where you come from. In the beginning you have the verb, so that's the get or the post or the delete, and then you have the Web address, and then the road itself is slash, and on this occasion it's slash product, so slash products route would return a list of all products. If we specify a product idea at the end of the roots or slash products slash i d. If we just go over here, the right hand side slash products slash one that would return the product details of one product with an idea of war north that of root can carry out different actions depending on what http verb is used. So, for example, if we use the same route as we did before. So the slash products route and was want to get to opposed, so that should mean create a product. So there's the U R L in point, and they're obviously the route is slash product. You would pose that, but you would have to include Jason Body. This law makes sense once with sort of demo and go through building the FBI so they should create the product and then also return. It is part of the response for its it's advisable to use knowns. So, for example, slash users or slash products or slash jobs, it's best practice. Also have in point is pure ALS. Since it doesn't matter if you're retrieving, warn user or many users, the endpoint would be consistent. For example, slash users. If you re just returned one, you wouldn't have slash user slash one. You would have slash users slash one. So also a good rule is never used. Routes like get user, create user or delete user. These don't follow the rest principles as your mix and verbs with knowns. For example, get use a keep the verbs for use in the http request, such as get paused delete patch and the now and is part of the route, so slash users. So in theory, if you wanted to get users, you just get slash uses. 4. Software Set up: Okay, that's enough theory for the time being, will now get on to install and setting up the software. The software we use and throw this course is mumps, which is the Development Web application server. This is PHP Apache and my sequel, All Building. As part of that, you'll get a Web application called PHP. My admin. This is used for administrating the my sequel. The obvious Moving On will install Adam. This is a chord editor. It's free, open source, and it's very good. Next following that will install a program called Postman. This allows you to test out the AP ice. Okay, we'll start by installing bump. So if you fire up Google crop, it's typing month. Good is anything usually the first hit Mom taught in four Click and then you'll have mumps on my improve. We're just going to install a month because it's freak, although I do recommend proof you have different websites that you got a horse and develop click free downloads and what we want is month and mom pro or 5.2. I'm obviously on a Mac, but if you're on wooden doors, you can follow along on this one instead starts downloading. Okay, that's no downloaded. So the bottom click on it once I should ask you to install it. Just follow the with the three. Continue. Continue. Continue. Obviously read and accept the user license. I'm just gonna click install. I've got a touch. I d on my Macs. I'll just use me. Fingerprint installs use. It just takes a few seconds. Not too long. Okay, That's installed. Click clause moved to trash cause we'll be using the installer again. Okay, the next thing we're going to install is Adam. So just in your address bar, just go to Google. And I'm just going to type Adam editor in the Google. Do you do the first? It It's Adam. Don't, Are you? If you want to go straight to it, click. Adam. I thought about detected. I'm on a Mac. So this Quick down Lord, this year's it takes just a few seconds to download. It's not very big at all. Click on the download of the bottom left. Whom does it full up. There you go. All we're gonna do is drug that to my applications on the left hand side. Let's it installed. We're going to know to leave the install a zip file close. Okay, the last thing we're going to get is the program called Postman. So of course, Google again. Just type in post mine here p I and it's usually the top hit. Click the Link. I don't know the up cheesy platform like to say where on a map, So I'll click the Mac want. But if you're on Windows, flick the Windows one. Okay, that should have started to down Lord Out, kid. That's no. Don't click on the download A file on the left hand side. It unzips it. And all the do is just drag and drop that in applications exactly the same as we did for Adam. Okay, that's applications installed. So first of all, we'll fire up Adam just to make sure works assassinates because it's don't order from the Internet. Wish you wanna continue press a woman. Okay? He is our court after that. So the next thing will check is to make sure Postman's installed it is post month. Exactly the same to double check that you want to open it because it's downloaded from the Internet. Click open. Okay, There's Postman, and we're going to the detail of this leader, que the next thing. This is the big Warren and it's called Bump. And what we want to find is it's a factory of folder within the applications for Let Cold Month double click on that and a bit of a sort of brief guide here. We're going to be put in the files into HT docks. That's where we're developed. Court files will be put. That is sort of the route, or of the Web site that would develop it. Okay, so the first thing I want to do is open month and then click start service. This is not your Apache Web server on my SQL server. You get this page. So basically that means mumps all installed, all working now, going back to what was said before there was another bit of software, it was actually Web app called PHP my admin. And this slows you too sort of developed or implemented it obvious access that you go to tools on this pitch. Then you got PHP my admin click that takes its page p my outman from the fund size up a little bit just so you can see you see here less. The databases on the left tops across the top will get into this further afterwards. Started developing the database. Okay, that's the software. All installed will move on to the next video. 5. Task API Requirements: now one of the requirements. The deal of actually what we're going to be building. So the requirements for the FBI itself are in most returning Jason Response for all routes . This is so there's a consistent former returned. So client applications, in order, expect it should have been a concussion where appropriate caution allows the FBI to return results from cash if it is called within a certain amount of time. This lightens the Lord on the service, and it can deliver a response from its own cash, meaning it doesn't have to send the request back to the server. You need to use this with caution door as if you update the task. You will always want to get the latest version from the server and not the cash version. Next, the task itself needs an i. D. The title, a description the deadline did in a completion status. So after make sure we implement these fields within the deer dubious and also return them on the FBI is part of the response. Now there are a few different routes that are needing to be implemented. Remember, a route is Justin endpoint that you call e g forward slash tasks or forward slash tasks. Forward slash one to get task one. So the 1st 1 to return is a list of all tasks within the system. Remember, eventually this will be per user. The ruble for this will be slashed. Tusks next depend on how many tasks you store. It's a good idea to allow pigeon of results. For example, if this was being used as a shop e a p I. That returns all the list of products instead of tasks the stock enough thousands of products, it wouldn't be good practice or a good user experience to return thousands of products of once. This can be slow and take up a lot of server resources. Feature request. So what we do is below a certain amount to be returned. Perpich, for example, 20 per page. We then create a route to call the next page, which will then return the next set of results. The root for this will be slashed tasks slash page slash wall or slash tasks. Slash paid slash to for pH, too. We will then need to return the details of just one task isn't task. I d. The root for this will be slashed. Tasks slash one To get task I d want the A P. I must also be able to return either just incomplete or complete tasks only. And as previously mentioned, this will repair user as well. The root for this will either be slashed tasks slash complete or slash tasks slashing complete. So that is all of the return task route. Now we need to be able to delete a task for a given i d. And for this the route will be slashed. Tasks slash worn, for example. For task I d. One or slash tasks slashed to next, we need to allow away for a test to be updated. We won't be updated in the task i d. Is. This is a system generated identify, so we'll just allow for the title description. Deadline did and completion status to be updated, although you might know one rubbed it all of the details at once, so it should allow just, for example, a title to be updated and leave all the other details. The With ER. Once the task has been updated, it should return the updated task in the response. The root for this will be slash tasks slash warn where one is a task i d Finally, we need to allow a new test we created. Once the task is being created, it should return the newly created task in the response, the root for this will be slashed tasks. Okay, that's the end of these FBI requirements. Next will move on to the authentication requirements. 6. Authentication API Requirements: the next center requirements off for the authentication. E p i. The authentication, your P I will allow users to log in and log out. This will be needed to allow our task list the FBI to function on a per user basis, just like our task list FBI. All the responses should be in Jason Former The details recorded for use There are an internal i. D. Full name unique using him the hashed password. So not playing text because if the database is compromised and anyone could see the user's password, and we all know that uses mostly have to see him password for multiple systems. Along with that, there should be an active status, which can be used to make the user non current. So if a user leaves or he just wanted disable their account for some reason, there's also a field recall the amount of incorrect log in attempts. This will help implement a lockout system. For example, if it user attempts to log in incorrectly three times, the account can be locked out. The Tesla's system should allow a user to be logged in on multiple devices at once. E g. This smartphone tablet or the desktop local into a new device should not love them out of the other devices. We will need to use a concept known recessions for this, and we'll go into the details of this leader. This should be a retrial. Our new user to be created so user can use a client application to sign up. For example, the root for this will be slash users. We need to allow a user to create a new session by authentic in. This is known as logging in the roof, For this will be slashed sessions. We should always allow using lock out of their system. Know that they are. The sessions will be unaffected, and the root for this will be slash sessions slash session I. D. So, for example, slash lesson slash five and has mentioned early on in the course will be used in access talking, which happened living her life spot. So you must create a route that would allow the users to refresh the access Talking wonders expired, although this will be hidden from the user and the client application will deal with this. Behind the scenes, the root for this will be slashed sessions slash session I d, for example, slash sessions slash five. Okay, so now we have a list of requirements for the task for STP I, as well as the authentication FBI we can now move on to implement in a my SQL database, which will be used to store the tasks the users in the sessions. 7. Demo of Completed API - What we will be building within this course: Now that we have ran throw requirements, it is a good time to show you what we will be producing. So you can understand how our solution will work. This is a whistle stop tour of the FBI. But don't worry. We'll be going into much more detail. As we implement each requirement, we're going to start at the beginning where we will sign up. A new user log in Is that user create a couple of tasks, retrieve them tasks in a list? Oh, dear. The task and then delete the tasks we've created. Well, then finally log out the user. This will demonstrate the use of each TDP verbs as well as the response status Causeway of previously run through to Demo. This were used postman to call the FBI. It's the 1st 4 will open four smile. So I got postman here. This is what we used to test the a p I. So you can see you get the verb on the left hand side of see the ones that we spoke about. What's get posed. Patch delete. The first example I'm gonna show you is what happens when we try enlist the tasks. But we're not logged in as a user. So first of all, um, we type in the local web address for our development server, which is month, if you remember correctly. And that is local host party. Did it slash? Now the route that we're going to use if you remember going back to our FBI requirements Waas to get a list of all tasks, it was slashed tasks. So you see here slash tusks and I'm just going to send that request so you can see here that this is the body that we get returned in the response. So you see there will have a status court of four or one Now, this is not in the http header. This is what we've put in the wrapper for the response. The real status quarters over here, just to the right slate and see steered us for a one. Authorization required basically means we're not locked in as a user. We've got a message is a real here, which is basically a list of all messages. So you see here the access talking is missing from the header and access talking cannot be blank. And you can see here that our data is no, basically is not because they're not locked in. So the first thing we need to do is create a user because this is a fresh system. There's nothing exists. Saw to demo that we want to create a new tab at the top. Just leave here cause will be returning to this shortly to create new top. No, if you remember going back to our requirements to create a new user, what we use for create is paused. So we'll select post taping over development server again. Local Horst poor dated it, and then it's slash uses. Remember, it's plural. And what we're doing is creating a user to post slash users. No, what we need for this if we go to we need a body because we're sending theater to the server. So the click body and what it accepts is GSR. Remember in this course were dealing exclusively with Jason. So if you click raw with a plain text here, select Jason and what would do we have to create the Jason body and we've got 33 mandatory fields for this one. So the 1st 1 is full name, so we just created obviously the body. So we're going to send this to the server to create our user. So full near. I'm just going to see Michael s the next monetary field is that using him? So using them on, we'll just call that Michael and the next warnings password. So obviously, this is where the user can create the wrong password, so it's not very secure, but we'll just see if password one So that's the body set up. So in theory, this should create the user. So what I'm gonna do, make sure that's on post is send this. You can see here if I just increase this. We gotta stay this court of two or one which, if you remember, rightly was created. And you can see this over here, just to the right. You got the HDP had a here to one created Success is true because it carried out the task that we wanted to do successfully. We'll get a message user created. And then what happens is it's good practice to then return the user. So it's user I d warn full name of what we put in Michael s using here. Michael would never, ever return the password in plain text ever. You wouldn't even return the hashed password, To be honest, wanted stored in the database that should never then be exposed anyway. So now that we've got a user we need a log in Is that user? So what we're gonna do is create a new tab it across the top here, Andi, remember, from our requirements, it hard creates a session. So that was slash sessions. So when you log in as a user, you are creating a session. So what we're gonna do with doing to create So it's opposed again. And then we'll type in our local Horst Weps address slash sessions. So obviously, this is a create, so there's a body for this as well. So if I click on body, click raw again and then change text to Jason, create the GS on body and what you need here is toe log in as a user. Normally, what you send is a user name and password. So using him, Andi, I was waas michael and password. Look, if remember rightly that waas password war. Like I say, that's not a very secure password put good for demo purposes. So What should happen now is it should create the session. Just as a vivid example. I'm just gonna miss Take the password. I'm just going to see a password, even though the correct password is password one and what you should find. If I then submit this post request, I should get a forewarn authorization required. So basically, I have type in the past. Waiting correctly on Peerless obviously is just demo purposes. So status called for a war, and then a message using your or password is incorrect. Would never really explores whether it was the using him or the password. It's just to hide, basically. You know what? Watch could be wrong just to stop people from trying to guess. Actually, I've got the right use name, but it's the wrong password. So just to proceed to a bit further will just take in the correct classroom, which was Password one and what we'll do. We'll just resubmit this and this time it should log in. So send that. We should get back There you go steered us to one. Remember too Well, one is created, so it's created a session for us. It's successfully logged. Two Sim So what? We get back and these are important. We'll talk a lot about access, tokens and refresh tokens in a later video. But just for this purpose, I'll just show you what here forgot session ideas worn. So that's our session. We could have multiple sessions, Remember if we log in a different device on different devices, But what we need is this access talking. You see, it's just a random long string that's, you know you would you would probably never guess this to be fair and remember that it changes quite frequently, so it will expire. So you can see here the access talking expires in, and that's in seconds. It is stage. We're not too bothered about that because I'm just de morninto go into more detail once we implement these requirements. So now that we've got the access talk and this is what you need to provide on every request for the tasks that were going to be coming out, so I'm just gonna take a copy of that a copy. Okay, Now what we'll do is you can see I will been top across the top here for the get request. Remember the first time we try to log in. So the first time we try to retrieve a task we weren't locked in, so it's easy access. Talking is missing, except so we're gonna do now is actually hopefully get a list of tasks now at that At this stage, it will be blank because we haven't actually create any tasks yet. So what you dio is you send the access talking that we've just copied as part of a header for the http request. So in the key here, these are sort of the head of parameters that we're going to send. The one that you need to put this in is the authorization headed. So you see the authorization and then the value. All we're going to do is right, click pieced, and that's our access talk. And remember, that's that's kind of the temporal password that were given for a limited amount of time. So now I've got that. What we should do is be able to send this request now in an should return, get retrieve a list of tasks like I see it should be blank. So click send. So you see, this time it was successful. 200 isn't OK, that's fine. Success is true. No messages and in the data, we have rules return zero. And then what this would be would be a list of tasks at the moment. Obviously this non So now what we'll do, We'll actually create one. So I'm just gonna leave these tops open because we may need them later. What we're going to do now is just create a new task for every request that we send to do with create the leader of deer tasks or retrieve. We need this access talking. So I'm just gonna make sure that's copied. I'm gonna need it, go to create a new top, and remember, Post is used to create. That's what we'll do is we'll type in our and local Web developments ever, which is obviously a local Horst using month. That's what non party did it remember to create a new task. It's slash tasks because we haven't got any I d. We're not. We're not making an idea up to create a task that is system generate. That's what we do is we send opposed request to just slash tasks. Obviously, with post, you have to provide a body. So go on the body. Click on raw changes to Jason. Start the Jason body now. A task hard man, three fields. But we're going to do is we're just going to supply all of the fields that's required. Now what? Is he going back to? The requirements we hade the task title Tusk description, Test deadline. Andi completed status. So if we start with title, Andi will give this. I don't know. Just in example, could grass That's an easy one. That on a to do list. And then what we'll do is we'll give it a scripture description. Um, well, just make a brief. So, um, could the grasp on bond We'd the past a good example. So next it was a deadline. So will write deadline. November rightly. This was actually a no optional field with not every task has it deadline, but will specify it. Just assure you how to build up all the fields that were going toe resend and in the request. So deadline, um, on this wasa dead formats saw, um, I'll just put 10 or warn slash 2019 a minimal putsch. Five oclock in the afternoon. So I'm here in the UK So this is the 10th of January 2019 at 5 p.m. So the next field waas completion status or completed and at the moment we're going to see this is no, it is not completed. So what should happen here is that you create a task for us on return the task in the response. So if we send and there you go basically forgot to add the access talking. So that was a good example there off someone just trying to send tasks or create tasks and not having a valid session. So if remember rightly, you should always send the access talking in the header off the request. So in here, remember, it was authorization. Paste it in there. So that's our access talkin now. What should happen is for just go back to body just to show you it should now create this task for me. You can see there. The task has now created stairs to warn that it created success. It's true message Tusk created. Now what you'll see here in the theater is the list of tasks bs agree, and there's only one is obviously only created one rules returned one. And now in the tasks, we actually have the task that we submitted, obviously the ideas generated from the system. So we don't provide that title description deadline and then a completion status. So what we'll do is we'll just quickly create another Tusk will just write something like, um, clean friends spell clean the windows and then description what I'm gonna do, I'm gonna miss description out on this one because you don't have to have a description is quite self explanatory, and this one doesn't have a deadline. So what I'm gonna do, I'm going to get rid of deadline as well. So the monetary fields are title and completed. Now, what happens is for if I don't supply the completed status, so I'm just gonna get rid of this temporarily and then just submit this request. Remember, our access talkin is already in the header from this request, so we'll send and you can see there to 400 error, which is basically you haven't created the request correctly. You're missing some some mandatory data, and obviously the messages completed field is mandatory and must be supplied because we're only supplied title. So just put out back in. So I've got the title in the completion status. So for send that you'll now see we've created a second task. So rules returned. One task I d to clean the windows. See, There's nor description. It's no and it hasn't got a deadline. That's also know completed is no. People haven't completed then yet. So now if we go back to tasks so we'll ignore that's the creation. So now we should have some tasks to return. So if you go back to our original request, we've got the slash tasks which should list them all for obviously I will user remember, our authorization key is already in. There were access talk and I've already got that stored in there. And you see, on the last time before we created any tasks, there was nothing returned. This time, we should have two tasks. Will create a two for this use. So now if you click, send So there you go up to 200 status, just like before. Success is true, nor messages. The data, however, now has the list of tasks or or he's turned this to. You have got tasks so you can see here that we've got task one and then Tusk to So there you go and say that we're locked in. We've now got our list of tasks, So the next one, the demo, would be to update a task. Now, what we're gonna do is we're gonna up their task to, and we're going to give it a description. Basically, that's all we're going to do. So I'm going to create a new tab across the top because it's a total different request. Create a new top. Now, remember that an update is a patch. We're actually updated in the tasks or patch on for just taping. I were local for service again and then slash tasks. Now, remember what didn't task with an i d for go back with an idea of two world did in this task. So we need to supply this I d difficult backdrop, a new request, So tasks slash too. So look, Deon, task to I remember we need to supply. I were access talking in our request header. So if we type in, remember its authorization, remember and then paste our access talking in there. So now obviously with a patchwork did and something. So we need to supply a body. So we'll click on body again exactly like we did with the post rule and then Jason Data. So now what we need to do we need to supply the list of field with the values that you warned Opiate for task to remember Tusk to. So, like I say, we're going Teoh, Just give it a description because it doesn't have one so description, and then we'll have something. Like which one was this one again? Nothing was clean. The windows? Yeah. Clean the windows. Okay. We'll give a description off clean windows on the frames. Okay. Like a C. You could supply multiple fields like we did before so you could update the title on the completion status if you want. You just put a comma and then completed and then changed to a why. But we don't have to look interest up that one field at a time if you want, so I'll actually remove that. We just want up their description. So you see, there were supplied our access talking in the header, which is there. We have also provided the field of Rwanda of debt and obviously the value here. So if we send this, what should get is a 200 which is okay, so that's actually updated the task. We've got a message. I see his task updated and it actually returns the updated task. So rules returned one tasks and see here now that I d to title clean the windows. But now it has a description. Also, we didn't update the deadline and we didn't update the completion status. So now if we go back to the slash tasks request which gets all tasks, remember, for a user, this is the response from our last request that was sent. So now if we just basically refresh up by just sending it again, you can see i d to clean the windows. And now we've obviously got our description. So that's a deer that that task fight. So next. What want to do is just demonstrate the delish in. So we're going to delete number two first. So if I create a new request here and remember, the verb this time is delete. That's what we're going to be doing on the route for this. Is it GDP local? Horst it it it slash tasks exactly the same as the updating request is supply Which task you want to delete? So I could see this is tasked to we're going to delete this time on, Remember, for any sort of action on these tasks, you have to supply your access talking in the authorization. That's all for Pierce that in there and what should happen now, This should delete this task. So send that. So you see, they had stairs to 200. Success was true in the task being deleted. Obviously there's nothing to return because we believe that that task So for quickly just go back to Howard slash tasks again just to refresh the list of tasks that we have is a user. Send that Now we've only got one task. So what we'll do is we'll quickly delete this task as well. So recorded the delish in requested this top right again on a you see here in the u R l hear the route. Remember, it was slashed tusks slash i d. So that's slash war now, because it's task I d one remember, we've already got authorisation access talking key in there, so we'll do send so you see now that task with an idea one has also been deleted. So now if you go back tro list of tasks, requests and then just refresh that you see, Now we're still look, didn't still find, but we just don't have any tasks to return. So now that we're doing that, what you would do is a good user is then log out if you finished with it. Um, a lot of people don't like out of applications now, but I just wanted them all this to show you that we will look out, so create a new request and remember anything to do with log in, log out is a session. So just like we did with the tasks before, we're action you to delete the session. So if you change the verb to delete and then type in our you are l, which was local Horst 40. Idiot. Idiot. Remember, it's a session sort slash sessions. But now we're actually deleting a session. So now we need the i d. I remember when we created the session, I we logged in. We did get a session, I d returned. So if I could just find the tab across the top. No, that was the use of one next one. So this one was a creation of section being, say, our session I d was worn like I say, obviously, the more people log in, look out that section I d Number will rise. So now we've got the session ideas. One will go back to our delete, give it an idea. So slash sessions slash one. Now, obviously, what you do, you still need to provide your authorisation access talking because otherwise anyone will be able to log anyone else out. So there you go of peace. That our access talking in there. See, this hasn't expired yet. So what we'll do is we'll click send. So you see now, status cord is 200 which is an orc. A success was true and the debtor returned back. Basically what session we've logged out off. I deleted. So now if we just try and go back to our slash tasks which originally listed the list of tasks for a user with our access talking, we should in theory, not get anything back. We should get an error. So there you go. We get a 41 ever, which is invalid access talking Because, remember, even though we've just being using this, we've now just logged out of that session. So hopefully that gives you a bit of an overview of actually what we're going to be doing in this course. I just thought it would be a good sort of I wouldn't I wouldn't say a quick video because actually stayed in a little bit longer than expected to Demel this. But I just wanted to make sure we hit all the deals. Just so you understand what we're actually going to be creating and why we make certain decisions throughout the course. So with that being said, you've had the demo will now get onto some of the practical work. 8. Tasks Database and Task Table Creation: So now we move on to momentum, my sequel databases. So first of all, we need to going applications on your computer, and then we'll open the month applications were going to bump and then open the month up. What we need to do is click start service. This may well be already be running from your previous session. If not, just click it. So from the man home pitch, we need to go to tools. And as we spoke about before the manage of my sequel databases, you open an application called PHP. My admin. So we take that. So we'll have Here is tops across the top databases down the left. Now, ever see our new dear Dubious doesn't exist yet, so we need to create it. So click on the databases top from here on you to create the database. So give the database a near So I was will be tasks DB Neither coalition at its default is utf e. It's general case insensitive. That's fine for what we need could create. Okay, so now we need to create the table. I was create the table based on what I'm going to store in it. So Well, pretty Fix it with tbl on because we're storing tusks in this, it's tbl tasks. Now the number of columns is how many fields or what information we're gonna store against each task. So going back around requirements, it basically said that we need to store an internal i d. The title, the description, the deadline and a completed status. So that's five altogether. So changes defaults to five there, and then we'll click Go. So this is the table structure that we're designing. So these would be the names of the fields down the left. And then, obviously you're types what we'll do. We'll just start filling this out based on our requirements. So the 1st 1 was an identify a soldier's call that I d. Now it defaults to end. Now, if I just leave the you have a text to appear. You can say that ranges roughly about 2,000,000,002 0.1 billion, which is a lot. But because this is gonna be a multi user system, then tasks are deleted, created sort of all the time now, two billion. It is a lot, but it can get used up pretty quickly. So what? We'll do is we'll use something big bigger than that. So what? We'll chooses a big UNT, and if I leave the Harbor text to appear on that, he will see their. That's why. Well, that's a big number. It's about nine quintillion. Nothing that is so that that's plenty enough for us. So it's like begins, and then what we'll do is we're gonna set. It is a primary key, cause an intern like identifier for a task click Go on this thought of index creation screen because that's fine. We'll just leave it at the default called Primary like okay and then won't want to do is auto increment, so we'll turn that on. So basically what that means is that the task each task will get its own unique reference number starting at 1234 except for one of their normally like to do is give each field a comment. It's helpful for me if I come back to this, so I know what each feel actually refers to. So what we'll do here is call this task i D. And we'll just say it was the primary second spell thing. Go. Okay, so that's that road done. The next rule is for the test title. Sorry, I'm just racking me, bringing their just forgot for a second. So test title. So we'll give this title. The default isn't, but what we need to do is change that two of our char. So I was text and numbers will default that to turn in 55 characters in length. The test title really shouldn't be any bigger than that. To be fair, you don't want to store a lot of detail on that. That's what the test descriptions for. So the test title. If we school all the way over to the right onside at a comment task title, and just to make you know that what we're doing here, this null column basically says, if you can allow Newell's or not so blank values, basically. So when in an I D. We don't want to, because it system generated. Every task must have an i D. So we'll also follow that with this. With the title, every task must have a title, so we'll leave. That is not know, basically moving on the next one. Walls description spell again, so this one would be bigger than 205 characters because a lot of the time this is the details of the task and maybe step by step instructions and might be a history of what's already being carried out on the task. So it will do well changes to something bigger. And what we want for that is something like medium text. That should be big enough. A task might not have a description. To be fair, the title might just be no, if it's a simple task. So what we're gonna do on this one is allow a know little value so this one can be blank. Not every task must have a description will also give it a comment. So this is task plus description. Okay, Next, It was the deadline day it wasn't it. So we'll call this one deadline on for the type. We will give it a day, a time. The reason we don't give it a D. It is because the task might actually have a deadline of See tomorrow, five. PM So one actually specify the time and that as well. So we'll choose dear time. Now go back to know again the task, Max, you might not have a deadline. They might just be known gone thing or something that can be doing at any time. So what we'll do, we'll actually allowing no value for the deadline. So it can't just be blank and it won't have it. Won't have a deadline. Did we'll give it a comment? So task deadline Did it can't moving on the next one. Was the completed status sore completed? Now what we're gonna do for this because it only stores either yes or no? Why? Or an end? When you gonna allow them values to be selected? No, for the type. For this, we will choose its called enumeration. And you know, so you click that you'll then see, we get to edit the values so select edit, and then because we're only storing two values were going to delete these two rules in the bottom. I'm going into the values in here. So the 1st 1 is why for guests this is completed or the next one is in for nor not completed. We'll click go on that to see of them. So this one, actually what we want to do is default this to know. So if someone specifies a task but doesn't give a completed value. We want always default that to know so in the default will select us to find. And then we'll select end for that. We'll also give it a comment Tusk completion status. And then what we'll do is because we've put because we've already sort of set a default. It's not gonna be no anyway, so we'll just leave that as not know and finally will give the table some comments. So tasks table and then we'll click. See that? The bottom right hand side. What they should do is then create the table as we've specified in this requirement. Okay, so now you can see that the tables actually created based on exactly what we said. So what we're gonna do here just so I've got some test data in here is actually just populated it using this system because the first tax tasks were actually going to implement are to retrieve tasks using the A P I. But because we haven't got fantastic sin, it'll just end up blank. So we're just gonna put some test theater in here. So it would do is across the top. We've got insert you click that and what we're gonna do is just literally write anything you want in here just so you can see that's different. So we're gonna do is probably died round about five or so this or you've got something to see. So we've got a title. So I'm just gonna make this really simple. I'm just gonna call a task warn and then just go up through that. And then for this I'm just going right description worn, and we'll just do it that way. We'll do some with the deadline some without, so we won't give this one. A deadline will leave a blank and then completion. Obviously even see it defaults to end, which is what we specified. So you can see underneath they it's got Ignore what won't take that. Basically, this allows us to create a new rule or a new task. So we'll call this task to description to, and we'll give this one a deadline. So if you click the little calendar right beside it, we'll pick it. Did, which is in the future will pick the 15th of January for me and their mobile do is we'll just give it the time. So 13 30 After you've selected that, just click off. You can see that it steered in there, completed the default of, Nor will just leave after the time being. We'll click Gore. You see, that's inserted two rules. So what we need to do is just do exactly the same. Another sort of twice us or so we're gonna insert again at the top, creating New Once or Task three and then call this description. Three. We'll give this one a deadline. Let's do some random times. We're going to say this one is completed just so we're going, obviously test out their completed an incomplete ones we'll take. Ignore again and they will create a new task. And that's task for Give it a description. We'll give this one a deadline to see him. You could say I'm just picking random values here and we'll leave that one not completed. Booklet. Go on that I will do another another pay A basically will go to insert title. So this is test five description. Five. I believe this would believe this deadline Blank would also say yes to complete on this. One can take ignore. Got title will give this one task six and then description six. Good job order cracks working there because I'm up to useless a typing, and then we'll select another tight deadline. We'll leave. That one is completed. No. So click on that. And then what we should have is. And if we go to browse at this top left sand side, this tab at the top should now see all the tasks that we've created. So I can say that we've got the ideas which is also incremental the wheel. We don't have to specify that it does it itself. So I've got a title that could be things like Cut the grass will take the rubbish out description. Like I say, you don't always need that. So actually could have excluded it on one of them actually made a title there. So what I can do is just double click and then just take them before they're things here that's actually updated that. No, a deadline. You can see there that we've actually specified to without a deadline. And the others with the deadline didn't see here that two out of our six tasks are actually complete. Okay, Now, let's don't will move on to the next part 9. Set Up API Folder Structure: now that the database is being created, will now move on to set up the folder structure for our court files. So the full destruction looks a bit like this. You can design the full of structure how you want, but I recommend this following the M V C model. However, because of an E p I, there's not necessarily a view. There's only in output from the controller, so anyway will start from the top. So we ht docks. That is the 1,000,000 root folder that serves to the Web. So your Web several have a fruitful that home folder, and anything in here will be accessible over the Internet. We won't really put any files in here. A search will actually build a structure below that. So within that HT Docks folder will actually have another fuller. Now you'll see here I've got a fuller called V one. That means version one a little bit about version with the A P eyes Over time, the A P. I will change now because more and more people will be using ups that connect your air P I or you have APS that need to be supported on older versions of devices and things like that . What would do was actually version the FBI. So any new changes will go into a version to version three, etcetera. We're normally what we do is set. It's sort of a beer slain for version one, and that's it. Nor changes will then happen after that's publicized, because I could, you know, you even went to change. And that could cause an issue with the client that someone else has developed that uses your way. P I So any new changes will go into aversion to folder or version three, etcetera. So within the version, one will take this one this example cause this is our first version that we're building. We have a control of folder on a model faller, so Legacy will follow in the M V C cordoned style. For this or model view controller, the view is things like a web in the fierce or something like that that the user uses like a nap. Obviously, we're not doing anything like that. We are just focus and directly on the FBI, so we would necessarily have a view. The controller is where the logic stored so within the control of file. You basically have any logic in there that handled any errors or process, and that needs to happen within the model. We'll have to. Models at the end of this will have a tasks model Onda response model. The task model will. How's TheStreet landed structure for what a task should look like. So it will provide methods like said, a title or set a description and within their methods within that model, you'll have the logic that dictate what a valid value is for title. So that can control things like length of text passed into the title or valid characters. Or, if it has to be a number, only that sort of thing. So you build your model up to store the details of a task, and that provides the validation for the task. Like I say when we implement the task, I'll sort of go through and discuss the model with you. The other one that will be building is the response model. Who actually doing that next? The response is going back to our demo that assured here the response is the standard output that comes out of the FBI now. It's always good to keep a standard output across the board because then it's predictable when people try to use it. You know what each field is. The standard status cords that will be using people will then understand them. You create some documentation if it is a complex AP, I. So what we'll do is we'll go and create these full of struck this full destruction now. So if we go into our applications folder on obviously I'm on a Mac, so you normally do that fire. I mean, I've got a shocker applications, but you always drive applications. And because we're using month, we're going, UM, AMP. And I think I mentioned previously that HT Docks is our home route faller. Anything within here will get served out to the Internet. So going tht docks on the first full full that we're going to create is the version fuller so well, like I say, we're using version one, so we'll just tie very one. So now how the vision want fallen. So we'll go into that folder and then what we'll do. We'll create a new fuller, and we'll call this one Controller Andi. We'll create a new folder and call this one model. So now that we've got the full this structure created that will allow us to now implement our court files. 10. Create the Response Model: in this video, we're going to implement the response object model. The response object model is responsible for the return of the Jason response to the end, user or client. So let's get started. The first thing we need to do is to create an HT access file, and this is a bit of a configuration file for Apache. What I'm gonna use this four is to display any errors on the screen. Now, in a production environment, you wouldn't do this just for our development purposes. We are going to enable the display of errors just in case we make any along the way, it makes it easy to troubleshoot. So first things first open about him and what we need to do is at our project folder to Adam. Is it the minute it is just a blank editor. Now, the project folder is the full the structure that would create in the previous lesson. So to do that, go to file Art project folder Gordy application Fallar in the mumps HT docks, Invasion one. We're going to stay here in the root of version one, so make sure you click version one and click open since they on the left hand side with God , Version one, and then we've got our controller and model folders. Ignore these DS store full. Is there hidden files for the Mac operating system? These won't have any bearing on what we're doing. So in the roots of the version one folder, we need to create a new file called HT Access. And this is an Apache configuration file. So for right, click on V one new file. It asks for a name, and this is important. It is dot h t access. It's important that you have the dot percenter. See, Now we've got the HT access file on the left hand side. So the first thing we need to do is start in some configuration. No, for this, all we need to do is tie PHP on the school flag on it is display errors on. So what we're gonna do here is tell Apache two if he is a PHP era, just a short on the screen. Like I say, you wouldn't do this in a production environment. But for our development, it is very handy in case we'd make a typo or some sort of mistake. So if you see if that so control and s or command s if you're on a Mac and we'll just close that down because that's all we're going to use this file for at the moment. Okay, Now we move on to actually create the response object file sore in the model we need to create a new model to response model. It's going to be responsible for returning the standard consistent Jason response to the client. Right. Click on model. Got a new file. We'll call this response dot PHP. I was working. Spell it correctly. Response the PHP. Well, presenter. So I've got a blank PHP file. So what we need to do is create the initial tag, and because we're not having any HTML or anything in here, you don't have to at the end. PHP tag. You can if you want. For we're not going to. Okay, so the first thing we're going to do is create the class. The class is called response. Create some space here. Okay. As part of the response, we have some Deiter or items that we want to return to the user. So what we're gonna do is create some private variables to stall this data until we're ready to send the response back. So if you remember from our demo, the response returns items such as success flag, whether that's true or false. Http Status court, for example, a 44 or 200. Any messages such as you forgot to enter a mandatory field. The data, which is the things like the list of tasks or the user details So we're going to do is create these variables now. So the 1st 1 we need to do is the success favorable. So private success. And the next one is the status, courts or private and will call us http, steer discord. The next thing we're gonna do is messages. This is an Arria because you can have more than one message held. So we'll initialize the surreal just to be happy. Private will call this messages on like a C will initialize it to be a blank, empty area. The next thing we're going to do is the debt of variable on missile store. The deal ever returning. So a private data, um on the next two variables were going to implement are used for in our internal processes within this. So the first what we gotta do is private to cash in will set this initially to false. So the cash bearable. What we're gonna do, we can cash the response to a request. So, for example, if we or if a client requests to return all of their tasks, we can catch that response. So if then the client refreshes or requests their list of tasks within C 20 seconds or 30 seconds, we don't have to go back to the server, call the database and return the details. From there, we can just cash that response and return the cash response from the client. So that seems any sort of additional Lord on the server or anything like that. You don't want to cash every response. So that's why we initially set this to false. And what we'll do is as we generate the response. If we need a cash it, we will explicitly see it to cash it. The things that you wouldn't want to cash are credentials, access, talking's anything like that. You definitely don't want to do that. It's a security risk, and you don't want to do that. So, like I say, it will set this initially to false. And where we see appropriate, we will enable the cashed for that response Clear. The last variable we're going to implement is something called response data. So private response did A on this is an empty area. Now, what would do is after we've built all this off, we create an array which has the structure. And then PHP has a function called Jason and Cord, which converts Honoria to Jason Response. So just makes it easier to return a nice sort of response in Jason format and you'll see that as well, Obviously build it up. So now we're going to create some functions. Um, if you know anything about object oriented programming, you'll know that it's good practice to create public getters and set us rather than manipulating variables directly in the object. So what we're gonna do, we're going to run through a set of setters to enable us to set these variables or set values to these variables. So we'll just start at the top, will create the set success. So Pisa public functions and we'll call this set success and what we'll do here we will pass in its success value. Okay, so what we need to do is copy this value from here and put it into the object variable. Just next relation of watch. These underscores our This is just my court and practice anything that is instance variables to this object. Not any other variable within a method or function I always put underscores. It just allows me when I'm reading the cord to see actually which variable I am talking about, whether it's a local one to the function or whether it's ah ah, class or an object variable that I'm talking about just makes it easier to read and understand. Okay, so the first thing you need to do is this on success? Want to set this to success? So you see, here all we're doing is setting this or this object success. Sometimes it's important to note that you don't have a dollar sign here. Don't put the dollar symbol there. It's an easy mistake to make because actually, when you define the variables, you too. But when you use a number, you don't. So if you do get an error in records, just double check that you haven't got a dollar sign when you're using this. So what do we were signing this success that will pass into this function to the instance Variable. So that's that. Okay, So the next thing we need to do is http status Cort. So we'll just do exactly Sam public function set. You cheated, Pete, Steal this court. Exactly the same will pass in any http status court and excited Sam this and then underscore, http. Status court equals passed in one. If you still court. Okay, so lets them too. Don't. So the message is area. It's slightly different. Andi will create that one now for public function will call this our message because don't forget, it is injurious or not set in the message we actually adding to the area. So our message onda variable or and an argument for the message itself. So we're very similar. Saw this and then underscore messages. Don't forget it In a re a saw square brackets, that's all this means is upend toe what's already there? It's not replacing anything. It's not deleting anything. It is just adding to an Arria of messages. I want to send this to the past in message. Sorry. Message to see if that's so. The next thing we need to do is Theo. The data. So exactly the same before, Like, function set. Did, uh, on will passing in deer there. Andi. Exactly. The see of this on the school theater equals the past. Indeed up. So set the day I hold a school is down so I can see what we're doing. Andi. Sorry. School back up. The next thing is to cash care soaps. So public function sit. Actually will change that, because it reads better when we just see it. To cash or not to cash. That is the question. Sorry. That was a bit of a limb joke. So to cash on school, pass in a to cash variable key on which is setting exactly see him Saw this on the school to cash equals two cash. So she obviously changed that from set It just reads better care, right? So now that we've got that were no need to start building this response did, or because this is what we're going to return as a response. So what we'll do, we'll build. That is part of the send function. So the send will send whatever well you've created here is a response back to the client. So this is what will be called when you're ready to return the response from our control accord. Basically, after we build a response up. So that is public function was call it send send. We're not passing any arguments into this, cause it is just using the deer that in the instance that's being built abusing these set methods Que saw it was me the biggest. Just want to see what we do it. The first thing the North is we are always returning Aegis on response that mentioned in a previous video will be dealing with Jason response exclusively within this course. So we need to tell the client when this response comes back, what theater it is or what type of theatre it is. So how to do that? You use a PHP function called head up on Jing Single courts. This is an http response header off content dash type on the type is application hopes slash jasan, But what we need to do when you could see what type of character said it is always good practice to see what type of character said there is. So we will be using Shaw Set equals ut f dash it. So we were using utf e it character set. Let me call on. Okay, now that we've told the client what this type of data that we're going to return is, we then need to see whether they can cash the response or not. So it's been a logic here, So if and then we need to check that were available to cash variable is set. They said to true. So if and this hope Sorry, this on a school to cash equals true. I just know the double equals sign there because we're not a sign it at actually doing a comparative true then and what we need to do, We need to also return a new header. An http head us or Hedda. It was put a semicolon there just to make it easier, so I don't forget. And then this one is called cash Control. Andi, if it's true, we want to store it for a maximum time off 60 seconds. So Max age equals 60. This is seconds. So this does. It tells the clients that it can catch the response for a maximum of 60 seconds. So if the user was to request a certain type of data back and we allow that to be cashed, if they try and retrieve that within 60 seconds of initial request, they'll get the cash response rather than going back to the server to get the most of the deer response. Like I say, you wouldn't want to do this for every sort of response. But it is handed a have saves you as a developer. Andi. Potentially business order a lot of Lord on a server. So now that was sent that we need a handle if it's false or will dio else. And then it's obviously we need to tell the client that Kant at all cash this response. Now you think that you could just get away with just not setting this. However, sometimes clients have the wrong Kachin method in there, so we need to explicitly see that this this response cannot be cashed. So it's another head up and it's exactly the same sorts cash stash control and we want to see no dash up. Sorry. Cash Andi, no dash store. So this is surface were to do it so nor cash. And you can't store any of the response. It all on the client. It always has to come back to the server to get a response. Okay, so now that's that. Don't we need to move on to, um we need to see if the response that we're creating is valid before we send it back. Because if there's been a problem set in one of these, then we need to return like a standard response, so it doesn't get any data. It does just generate a standard 500 Steelers chord, which is a server error. So this is a bit basically a catchall of of of a never. So if we will do our checks here. So if, um so the first thing we need to do is we need to check to make sure this is a true or false. So we'll do that in here. So oops, sorry. Just overloaded that. So this'll on the score. Success on what we'll do here. We'll do an exception. So it will be if it's not true or false. Then we'll return the every message back to the client. Because if we said if it is true or false ended up with basically nested ifs. And you can have the Pyramid of Dumezich called. We just have lots and lots of logic. And then, in the end, when it satisfies that you then have you, you call that provides a successful response. So what we do is we return just from the if statement. If, if there's an error or if the deer is not valid, we return the response. You'll see once we start building this. So if success is not equal to false, um, on bond, it's not equal. The truce or this success is not equal to true. You can see there if the success is not false, aunt. Not true. So that means it's some other value, such as five or 10 or test store some text or whatever. Then we will generate the standard response. So Paige pay has a function to set the response. The http response accord. And that is, um, http, respond to court and because this is an error response, it's a server ever basically because there's something that happened that's caused the response not to be valid. Well, see, it's a 500 so the 500 quarters server. You serve era if remember rightly aan den. The next thing we need to do actually before before we start building this you can use this if statement to build up any other variables and need to be set for a successful response. So instead of having multiple ifs and multiple response like standard responses, will just have it all included in this. So if I just go back to the top, the other thing we wanted check is the stairs court. So if I haven't provided one than that, the response is not followed. Basically, we're not too bothered about messages because they optional theater is optional. We don't have to return any day if you don't want to. Cash has a standard value of false, injurious, electrifying and response data. Well, we build a not opus part of this send method anyway, So really, the only other thing we need to check is http status court. So if you just add in if we just had this into this if statement, it just makes it a bit more similar. So that is its own check. So what we need to do is encompasses in brackets because that is its own because there's two of them. So we'll just put this in brackets. I'll just get rid of that additional bracket there and put that in Brockett there. And then what we need to do is doing or to or to do, annoy your space. And then it's two pipes and then we need to check the mixture of the http Status Court is a number. Don't forget, we're checking to make sure that it is not a number. So we're handling the exception basis on this. Or if it's and if it's not is numeric and then will pass in the this underscores actually paid theaters court. So you see here that this statement here has to be either true or false, but we're checking to make sure that it's not false and not true or we're doing it all here or them all. The status court hopes are good. Double dollar sign there, delete that one or if is numeric sor. If it's not New America's, we've got the not then we're going to supply a standard http every response. So, like I say, this handles the errors because we're checking to make sure that if it contains Valentina, Sorry involved theater. Then we do this. We cover. These actions are so getting back to the standard response. So supply response Court of 500. Next thing we need to do is start building up in all the school up. This response did area so we can return it. How to do that is so because it's an instant variable saw this dash greed Adan And then we want Teoh Underscore Response ABS response data And because it's an area, we can give it a key. We need to return yet So we need to return the status court Now what I'm doing here, this state is called here returns that to the client It's mainly invisible to the user Unless you open the def def tools in cruel mawr in Explorer or something like that, you be able to see that. But generally this is hidden to the user. So just for readability, I'm also going to supply the status court in the GIs on output. Just saw an end user can see what today is called. Has been returned easily. You don't have to do this, but I just think it's it's handy for any trouble shooting nor quickly just seeing what response you got back. So we're gonna name this value, okay, that we're gonna return. It's just steer this court, and we're going to set that to 500. Because that's what was said here. No, generally, but wouldn't set any state is called here. Really? Because we're gonna pass them in from our control is when you start building them. But because this is the era response were seeing that this is a server error. So I returned to savor every response. So now that returned the status court, We need a return. The success on the corner see that up sort going to say And this on the score response did A on this one is success on. We'll just and will set this to false because we know if we're building this, it hasn't been successful, so we know that it's false. So the next thing we're going to do is out a message. Um, so this what would it was actually at the message to here first, and then we'll assign not to the GS on response or this art message. Well, passing a string response creation era. Make sure pretty cynical. In the end there, we're going to return back. There's been a response. Creation ever. So just by looking at it, if you if you open this response or try and request something using a browser, it should you should be able to see easily that what the ever was basically. So now we need to do is um saying the messages to this standard response data. So this, um, response did it on will call this messages because it contained multiple messages. Onda will equal this on the school messages. So we're just gonna return the messages Any message, because it would be more than one Honoria. So we're just gonna return that which should show any message so we could have done is out a second message just by calling the same function, for example, will show you this and just say, Well, this is another message test message. So you see here that response creation every would be returned as a message on test message would also be returned because we're allowed in messages to the area. Let's get rid of that. They're not using it. Kim just going to see if that right saw what we need to do now is the opposite of this Basically saw if it's successful, so we'll just get rid this white space just to tidy it up a bit. Case or know what need to do is the else statement saw else. So that's if there's an error with success or http Status court. Now we're going to do if they're satisfied. So it is a true or false on the stairs. Cordis numerical going to build a successful response. It's exactly the same as what we're doing here. But instead of sort of defined and cords and numbers were actually gonna pull them in from our instance variables up here just go back down. So the first thing you need to do is to set the response cord exactly the same sort. Http. Response cord. So what we need to do is pass in saw this. I am on its itchy dp steals court. We're passing that variable because that's what we're going to return. Obviously, we set these via the controller, which will get onto in a later video. Just build this down the response at this time, and then we'll do exactly the CME. Um, so we need to display or send the stairs chord in the Jason Response or this care And this is what building response data here. Response data and gonorrhea, Steelers Court And instead of Senator 500 acquitted before, we'll just use this Sam variable. So this and then it's underscore H e p. It's delis, cord. And then the next one was a successful acts or just doing exactly same before. But this time we actually creating the successful response, which will be used in the values stolen, the variables. So response did a success. I will set this to this to score success and then any messages? This It's got messages. We'll set this to this him messages. So that's that. That's that, because it's going to be a successful response. We're going to return the deer there. Um, we're gonna be 10. Any data if he is any in this successful response to do this, it's exactly Syrian. This story's wants. Did a McCall isjust theater equals this underscored Deanna. So you say here from the previous demo, you'll notice that we wrapped the data within a rapper. Now the rapper contended things like thes here. So a standard state is called success message messages. And then we had the data, which then contained things like number of rules and then a list of tasks. This is actually building up the rapper at the top here, and then within the rubber there's a data, and the deer can be tasks, users, whatever, whatever you want to be. It just means that for every response that we send back, we will always have stairs called Success Flag on potentially any messages. Messages can be empty, But that's good, because you can have your client check to see if there's any messages present. And if he is returned them to the client on the apple or something like that. So now that's the response, dear. This set up were no need to return this to the browser. I want to the user. So in order to do that, we echo it out, and the Jason and court function will automatically convert this area to approve you. Jason, you want me to do is just passing in the response to get us all this in the School Response theater. Now to see if that get rid of some of this white space just to tidy it up a bit. Okay. See you again. So, in theory, we should be good to go. Got a prior variables, got the functions to set it, and then we'll have the function called send to then provide the response back to the browser. We contest this because just to prove that works really, before we get into the controllers and all this stuff, well, just prove that this works by creating, like a test file that will call this response, and we'll just pass in some variables. Just a demo. What? Really? It is a file we're going to delete. So I'm just going to stick it in the model folder anyway, because we're going to delete it. So if you right click our model a new file and we'll call this response test dot PHP legacy . We're going to get rid of this. This is just a dem or what we built. We'll give it on the PHP start tag Onda, we need to require because we need a Polian this response PHP file here. So to do that require once because we're in the same fall. If you put it somewhere else, you will have to sort of into the path in here. But because we're in the same folder, I can just call a spawn start PHP This it's just required needs that file, which is our response class. Before we could do anything else with a court, what we need to do is initialized the object or initialize the response that we're going to send back so well to store it in a variable called response. So new. What's that? Spell it, right. Response. So you got that right. The first thing we need to do just quickly go back. It's set some of these up. Just a demo it. So what we'll do is we'll go to respond to tests file and then work or response because this the response objective will call the function set Success on will pass in a bullion value soul just their true for this one. The good test. And then the next thing we need to do is set the stairs court. So response set the ISS. So I think it's called said http steers Yes. I said http Status court So upset. Http Status cord and will pass in 200. That's a successful or key message, Um on. And we'll set a couple of messages in there just so you can see how it returned so response , and with that message and then passing a string value so we'll just see test message warn. And well, I didn't another message response message. We'll call this test a message to Okay, now that we've built the response up will return. It were not returned any data at the moment, but we'll just make sure that we haven't got any errors in our court. Andi would get something back on the client type of thing. So now we've built it when you descend it. Remember the send function that would create a previously sore on dollar response on. Just send to see if that you'll have to start ma'am BOPE if it's not running so because mind already running what I'll do, I'll open postman just assure yet so in my applications full, I have full an application called Postman. What we used to demo the A P I in a previous video Onda, we need to tape in our u R l on because we're using lamp on our local server. The u R l is http call on slash slash local Horst Now by default member runs on Port it, idiot it. And then it's our full, the structure from their sore. If I just quickly go back to Attlee, he can see that it's V one and we're in the model and its response tests or what we need to do is slash b one slash model slash response test or PHP. So slash B one member version one of our MP i slash model slash response test dot PHP Make sure to get request cause that's all we're doing at the minute. We're just This is just a test, just a demo that the response returns, So we'll send that. So you say there that this is the basis of out standard Jason response. You can see that state is called over. Here is a 200. That's what the each TTP Steelers court function does so quickly. Go back to Adam on the response. Some of the http response. Court function. That's what that returns. So because we build it abusing a 200 chord here, that's what we're returning. Let's quickly called back to postman. Success is a true because that's what we passed in and messages you can see that it's an Arria. Our first message. I was second message and at the moment of dealers know because we're not returned anything . But you can see here that this is our robber for every response that we will return now, the good thing about building a model for this if we needed to change the response, he literally just change one file the response dot PHP file and then we can add in new values in here on, they would be consistent on every read response that will you get back. So it's good having everything in one file You you should always sort of produce an object like that and return that object. It just allows you to stop court duplication and things like that. So just to show you that this is actually work and we'll just just the test again, Um, I will see false because the success wasn't false. We may have failed to delete something or create something, and we'll just change just to a 44 error, and we'll just will only return one messages time and we'll just change. It's something different. Era with value. For example, I'm just sort of make metal bicycle here. Make sure you save it. Go back. A postman. Just send the request again. You see there that now we've got a four for error in the response. Http. We'd sure the response status court within the Js on. Just so it's easily sable so easily viewable. Say we've changed the success to false on. You can see that, actually want to go one message now every with value. Okay, now that that's working, I'm just going to go back to Adam. I'm gonna close this response test, and I'm going to delete it. So I click delete because we don't actually need that anymore. Would you want to clutter up this? Because you'd be wondering what each file actually does. Want to get to the end of it. So the only thing that was done at the minute is generated The standard response class, which produces a standard Jason response 11. Set Up The Database Connection: in this video, we're going to implement the database connection class already in Adam. So I'm just gonna close down this response file because we're going to be creating a new file for the database class. So this new file is a controller because will be controlling how we connect to the database or on the controller for that. If we're right, click new file, and we'll just call it db dot PHP for did abuse start the PHP file or the PHP tag Andi it database class or it would start off with class. Do you bait create a space here? Okay, the first thing we want to do is create some instance variables private, and these are static variables. What this means is that you don't have to initiate the database class to use these variables. It's just a good were to sort of structure the file. So the 1st 1 is right. Devi connection on the next one is read Davey Connection spell. You're probably asking yourself why is ah read? So we wiser right? And why is the read connection to give you a bit of background? It's just so it becomes scalable or easily, or easier to scale in the future. So if you use my SQL or similar data bit, want to get a lot of users on your system One day to be a server can usually handle the Lord for all the connections. The model, usually followed by big businesses, is that they is a lot of read theater beer service. So database service that specifically used for reading data and then only one sort of right database or master database that is called. And what happens in in that model, the right database pushes out any updates to the reader basis or the sleeves as it's called . And then every time you want to read data, you be pointed to, ah, slave read only database. It just means actually, a lot of systems do a lot of reading rather than writing, so it just helps balance the servers out better on day. It is a very scalable model if you if you research on it, so what we'll do? We'll actually build this FBI to be scalable from the outset, so we'll create two connections, one toe are right database or master database, and then the other one to the read database cluster, so this could point to a DNS entry that contains lots of read only databases. And it'll just sort of round robin each one. Every time you try and read some data, it just sort of spreads the Lord. Really? So the next thing we need to do is create the functions to connect, and these will be static functions like you say. That just means you don't have to. Instance she ate the deer dubious object. You can just call the class functions or the class variables. So this one is, um, public static function. Connect right debate Don't pass any arguments in. Okay, The first thing we need to dio Thistle's kind of Watson owners is singleton once you've already and instead she added a connection, you don't want to keep creating connection. Do you just want to reuse the connection that's already created? So what will first do is if and because it's a static. We're talking about the class and not an instance off this class. So we use the word self, and then it's right db connection and with checking to see if it's no. So if it hasn't Bean initiated, then this if statement will perform the initiation. Otherwise, it would just sort of return. He already created connection. So if and then we need to do, um, so self, then it's right db Connection. And we need to create a new we'll be using PDO on this course. Pidio is very good because it's a little abstract sore because we use my sequel on this course. You don't necessarily have to use my sequel. You could point it to Microsoft Sequel Server or something like that. And instead of going through all the record and changing all of the different queries and stuff to incorporate the new drivers, the PD, or will allow you just to quickly swap out database connections, theosophy is some sort of exceptions to that. The way that you write the sequel and stuff like that might be a flavor off my sequel than M s equal. But generally it's a good practice to use using PDO So new. Sorry, PTO on and we create the connections drink. So it's my sequel, and then we define the horse, which ours is on our side on, sir. So this is local Horst. And then we specified the database name hours waas task d B Then we set the character set. Remember, from our previous video, we are using utf e it exclusively in this course as well the beauty if it no need to put it down on that one. So that's the connection. Next woman you to do is pass in some credentials like usually and password. So I was or just the standard month wants obviously this if this went into production, you wouldn't use these same passwords and user names. So 1st 1 to use the name route last one is the password and that's also route. Okay, now that we've done that will have to set some attributes on this new connection. I'll explain these as we go through so itself. Um, right TV connection. Lots of spots connected on there equals no sorry, it's not that. Sit attribute open brackets on. And now what would do with passing some constants, which is PDO a t t. Ah, you are moored on P. D or they are more score exception until explain these and a second will just get them at it in so right TV connection. Sit attribute. And this is PD your keep doing. PdF For some reason, P d or E T. R. Um, you really free It is, and that is false. To see if that's what this does, is create your database. Connection will pass in the horse, which is local, Horst hopes. Small mistake that local host passing the database name that's called Tusk DB in our case, passing the char search. Whoops, I forgot a question. Sure, set equals, and then we're passing the user name on the password. Then what would Dio is with set of attributes on the connection was set the era moored for the connection. To use exceptions, no exceptions is good because you can catch exceptions. You can deal with them. You can roll back certain things if something's not right. Exceptions is a good were toe era handle. In PHP. You can read over a bit more on exceptions. It's sort of out of the school with this course, but we're using the exceptions era moored for the database connections. The next after beach is emulate prepared statements. Now, not every database system can handle prepared statements or tries to emulate them. Prepared statements allows you to sort of create a sequel cord and then put in place holders. So then you can just a sign that the dealer to that rather than hard coordinate into the sequel steam and itself. And we'll show you that further on down the course when we're actually creating and some queries for the database. But because my sequel does actually allow you to use prepared stands, it does have it negatively. We set this to false we don't want to emulate, because actually, my sequel does handle prepared standards. So you see there that we've got the connect right database for that on, and we've done the check to make sure it's not know if it is no would create a new connection. Once we've got the connection, then we just return it. So return hopes, return self, and then it's right TV. Keep spelling it wrong connection. Okay, so we just return it. The re database is exactly the CMAs. This so what I'm going to do, I'm just gonna copy this court just to save us a bit time. I was gonna copy that, and just underneath, just quickly put it underneath, and then we'll change, right? What is right? We'll just change it to read just on all of these. Just quickly. Go through change. These wolves save us a bit time. Really? Um, they will return the read. Now, in this instance, you're probably thinking, Well, why Why are these the Siem? Well, because we don't have a multi server. My sequel sort of an Arria. We just have one sequel server because we're doing this on development just using month. So when you got one. But what you would do is where it's got local host. You just get the DNS. Name off your sequel, Kloster. Basically, you're my sequel, cluster. So, like I say, that would always be the master database the writers always master on. Do you read ones that would probably have a DNS name off something like my sequel sleeves or something like that on that would just round robin between all of the slave databases that sort about the school. But this course, if you want to read a bit more open on sort of scale on my sequel, please do. But just to show you sort of how we're gonna allow this to be skilled, really simply, um, we'll just start off with this course with having this in it. Only a slight tweak. It's easier to do now than to change all of your cord later on. Now the is these reasons why you would connect to the right database updates from the right database. All the master database to the read slaves is a synchronous, which means that once something's updated in this, it's not immediately orbited in this in the re database. So that could cause issues, for example, with authentication if someone changes a password or refreshes an access token, which will be talk about later if the authentication was reading from the redid abyss. But we have just refresh our talking, but to return it we're looking at this image. It may had not had time yet to move or to be pushed from the master database to the sleeves . So things like authentication, Um, when you are updated and CIA task in our kiss, you would do the York did and return it from the right database because it's immediately updated in this database. If you work dated it in there but then try to recall it from the Reed database, you might get another date task now, if you want just returned in tasks, there's no problem with just reading from the reed sleeves because, you know it is only split seconds. And it depends on the Lord how long it actually takes up, up up there, the slaves. But for certain things, we do want to guarantee that the value is the same as what we've updated it. So we'll be using a combination off the right database connection on the re database connections. We'll just see if that okay, a bit like what we've done before with the response we can test just to make sure it connects successfully and will create a test file. To do this will be deleting this legacy. It is just a test. So in controller on the controller for that is right, Click new file and we'll call this db test dot PHP and we'll start off with PHP talk. We'll just see if that first thing we need to do is to, um, pull in the dead obvious PHP file just like we did before. Cut. That's where recorders saw because we're we've created this test file in the same folder as where the DB PHP is we can just call that father would be otherwise. Just end of the path of weather without file is the debate or PHP. And then because we are using exceptions, will have to try on run something so we use the key would try. And then we will just set some values or variables here, right? Devi? And we'll just call this and we'll try and now call the functions that were created in the DB file. So we'll try and call connect right db and connect re db go back to the test files for the right db saw the way that utilize class functions and class variables is you call the name of the class or our class was called D B. So db two Coghlan's and then the function name. So connect right db, and then we'll just create another favorable for read connect read db Oops. So now that would try and run them. Like I say if he isn't ever with with trying to connect, what we need to do now is handle that error. So the way that you do that is he catch you're you catch an exception. You try and run something and then any exception, you catch the exception. So we try on catch now, so within the catch, um, we cannot put any era. Now, I tell you what we'll do with this. We will return a response using our response model. So actually, this is a good test to try and pull stuff together now, so we'll have to require that in. So just copy that piece that and I would need a Polian the response dot PHP file. But it's not in the same folder, so we'll have to go up a folder and then go into model and then the response. So how you go over folder is dot dots forward slash That takes me. You're before that. So I should now be in V one. So now we need to go in the model, so model and then forward slash on pope's response dot PHP. We'll just see if that so upon in the day be file. And also we're pulling in the response model because is a good sort of weird of polish together. Good demonstration. If he is an error, we will reply with in every response. So we need to be like, what we don't have a previous test. Create the response object. Buy new response, and then we need to set status codes. Um, till set. Um, sorry. Response set. Http. Steer discord on will give this of 500 causes it to serve Erica's. If if we can connect to the database, it's definitely serve era, and then we will set a success Flag, um, set successful. And we'll see this is false because this is where an error has occurred and then we'll add a message, that message, and we'll just see the obvious connection era. And then we will send, So that sends the response back. It always good practice to then exit the script itself. So sometimes, with exceptions, you can sort of move on. If you have like a is. It is an alternative which is finally close, which would ruin whether there has been an error or not. So it's a bit like a clean about something like that. I always like to call exit on here because I just want to send the response to the client and then exit the script totally so it doesn't do anything else. So there's no harm, you know, that there could be no potential harm caused. Always exit the response. Now, if if the connection was successful, we shouldn't get any sort of output. It should be Just blanket the time being like a C. This is just a test. But if he is in error, connect and we should have ah, never response returned. So now that we've got that, if we fire up postman mixture of Mom's running, of course, we'll all imports minding. See, my previous two requests here will just create a new one blank one here on will try and call this DB test file sores http. A global force, remember, Ported it here slash b one and this file was in our control of folder, wasn't it? So control this slash and it was called DB test or PHP. Click send. So, you see, they actually have made a mistake here somewhere. The value that we put in the H T access file at the beginning of the last video would allow this error to be sure. If we turn this off, we would just get a blank sort of response and we wouldn't know whether it past a field. So for development purposes. I'm pleased I've actually put in the HT access file the shore errors or display errors parameter. So we'll go back and fix this So you can see here that in the control A debate test online . 10. We've got a bit of a syntax era so will quickly go back at him. D b test line 10. So here we've got try and catch of actually haven't court. I haven't put in the catch Exception. Now, exceptions have different levels. Generally, the word exception is a class. Now everything's a subclass of exception. So things like PDO exception, which is what we're going to do. So you actually have to specify the exception that we are catching. You can catch multiple exceptions and handle them different, so but this one is a PDO exception, and we'll just give it a name off the X. This just allows you help put any error message. If you had multiple exceptions, you could have multiple try while sorry, multiple catch so you could cut this and just catch my exception and have something totally different so I can handle the errors in different Weir's, but for testing purposes and will be doing that later on in the course, and I'll show you that for just for my test here or we're just catching a PDO exception. So we'll see if that go back to Paul's mind on try and run it again. So you say here that we've actually received an error. So there's a problem with our database connection attempt. We can see that it's just using. I was standard response, which is the steer discord that mirrors the steps, called up their success on our message nor data. So now we need to figure out actually what we've done wrong. Go back to Adam. We're trying to create the database connections and has been a problem. Go back to the db on Have a look in here. So by quickly looking at this, I can actually see what the problem Waas We tried open task DB, but actually it's called tasks TB, if you remember, so we'll see if that and then what we'll do is we'll try and call that again. So send you see there. We've got a blank response. We can see that was 200 Onda. We get a blank response because we haven't actually created any successful response object or anything like that. It's just his test to show you that. Actually, if there was a problem connecting to the database and you can see there, we try to open a database called Task DB. And actually, it's called Tusks TV. You'll get a response or never response back. So that was good. We're just appall the database and the response back. And actually, it is a good test to show that we have a successful connection to the database. What we'll do now is we'll delete the database test file because we don't need it anymore, so we'll just delete that's all right. Click on delete and we look to trash. Okay, so that's the database connection created will just tidy up some white space yet and just see if that 12. Create The Task Model: In this video, we will be implementing the task model. The task model is used to stall the task theater When you retrieve it from the day it appears, or when you create a new task, we can have multiple task objects depend on how many tasks were returning. Each task will be in its own object. This model will handle the validation of a valid task, for example, monetary fields and validate values. Let's get started. First thing we need to do is create the task model file. So then Adam, on the left hand side, you got your model and Eufaula structure. So for right, click on Model New File and we call this one Tusk Tuscan PHP. Okay, so create page pate. The first thing we're gonna do is extend the exception class. Now what want to do is through a valid task exceptions. So we use this toe handle different types of errors or possible errors within the tusk. So, for example, mandatory fields. So if someone forgets to type a title, we can throw Tusk exception. And because it's a specific type of exception weakened catch. It was seen an example of this within the data Biest class that were created previously. So we're not gonna do anything exciting with this task Exception Class only. Define it. We just need to be able to handle it. So class, they will call a task exception on it'll extend because with self Klassen exception extend exception now, Like I say, it is just a NIMBY class so we can just leave it like that. So we need to create the tusk class. Let's create some space forage task. You have certain delighted store about the task. So this is what we're gonna do here. So we need to implement these variables to store this data. So the 1st 1 waas it every task has an i. D. So private I d on the next one was title private, um, title on it had a description. I have a description. I have a deadline and it had a completed status. So now that I've got places to stall this theater for the task were no need to create your normal getters and centers. So will quickly do that. Now, 1st 1 is to get the i d. So these air public hopes function get Hi day. We'll see together. So not passing any arguments in and all the doing is return. This'll school i d. So let's get i d. So we need to do the sea and forget title get description, get deadline and get completed so we'll just quickly run through these Get title return this title. Let's get title done the function Get description corpse, return this description. So that's that one. Done. The next one is deadline deadline Tail helps turn this'll headlight on. The last one is completed on the scroll down a little bit something we were are 10 this under school completed, killed still check So we'll get the idea return or school this I d public function get title pretend to title you turned on school title Get description this in the score description get deadline returned This underscore deadline aren't completed. Yep, that looks all or care. So now move on to the centers. So the 1st 1 is said I d. This will be taken on. I devalue. Now the centers are the ones that's going to contain the validation for the values to make sure things, they said as the showed like minded tree fields and dear the value types and things like that. So the first thing you need to do is check the values coming in. So if, um so the i d. We won't be setting it will be generated from the database but still need a valid able not just to make sure it's valid now. The violent values coming from the database. Our values greater than zero but less than nine Quinn trillion if remember, rightly nine. Quinn Trillion was thebe big into maximum value that you could store in the database of my sequel column. Eso We just need to make sure that it doesn't exceed that. Andi, I guess we need to make sure that we're not trying to overwrite than I devalue, because once it's set, it should never change. So we need to perform that checking in there. Um, he is certain, sings dances where the idea will be no. So the past in I d will be no. And that is where we created a new task because open tell our point, it won't have an I D. It's only when it gets inserted in the database that will. So we need to allow for that. So I guess the first thing needed to is to try and check to make sure the values not know to begin with them saw past in value for I. D is not know, but obviously kind being also, we need to put a differentiating factor in here. So for put this in brackets onda, we do a checks. Or if it's not know Aunt, then do you check on your dear? That's passed in. So if it's not, you know, we need to make sure it's numeric you numeric i de Onda Um what else do we need? A chick? Oh, if the I d is less than or equal to zero because an auto increment in the database started one sort one in a both, Um, all the max values or the i D. I am greeted a man on I've got the number Nordic down because it actually must've 922337 2036 It 5477 5847 So that's the nine control ian number, the max for the database column size. I'm also need to check. Like I said before that, we can change this idea if it's already set. So if we're trying to pass something in, um on and this I d is not No. So that looks fine. Um, I think I'm missing in Brockett the Yeah, but I'm so what we're doing here is if the past in value is not know because obviously it can be No if we don't have value at the moment because it's generated by the database, so only if it's not know, then it does the check on the data type that passed in. So we need to make sure that it is numeric butch going by the exception, it's not a numeric or it's less than or equal to zero, because ordering and started one or the I D is greater than the maximum size I come store in the database. And on the other check is to make sure that if it's not know, as in if the task already has an I d, we can't change it. So off we then what we do is throw Tusk Sorry through you Tusk exception. And then what we do is we pass in an error message here, task I d era because if you remember rightly we look up here? Task exception. We have this to catch our own exceptions. So we copy or sorry. So class exception. Sorry, that should be extends to make three changed out or extends made a bit of a table there. That extends exception to allow us to throw our own specific task exception So we can throw a new task exception and passing an error message that will then be able to display to the end user if we put it in our standard response messages going back. So throwing your test exception otherwise on we need to set this I d equals Heidi. Okay, Like I said, these ones a little bit complicated. I mean, you put your own logic in here. This is obviously just for my specific needs to, but you put your own logic in here. I'm just showing you how to if if he is an invalid value like you're putting in, this is how you would handle the era. I want to say that que the next Warren is function i d. So it's a title So public function set title, passing a title on the database. We have a maximum character size for the column of 255 characters. So we need to make sure that in there, but also what we need to do is to make sure that I wear because this is mandatory, titled Mandatory will have to make sure that it is set so we will do our if statement on will use a function call string length or str um Lynn and will pass in the past in title. So what we're saying here if string length is less than zero, So if it doesn't have a length, for example, it's blank. Then obviously, we'll throw the exception. Um, do you think when you check is during Len he passed in on title is greater than 255 characters, So if it's less than zero, or if it's great in 255 we need to throw an error message. So, um, through new task exception with an error message off task title era. Otherwise, if it's valid data, this'll title equals Dustin title case. That's a title next one's description. So set description passing a description description makes us follow right description. Onda, we need to check with this can be optional. So this to need a make sure handle that on the description. We had a maximum size, I think was said a medium text in my sequel, which has a maximum size of something like 16.7 million characters. So we need a handle. That's or if, um so what we need to see is if it's not. No, I guess, is the first thing we need to do. So we'll put this in brackets or description is not no Andi. So if the years passed in data, then yeah, so then we need to make sure that the size have been like the title. The size is correct. Sore on bond. What we'll do here is put this in brackets as well, because this is to compound sort of logic statement here. So string Len, Look, I always do that length. I am description. It's less than actually, it's optional. So need handle. That's or a maximum off 16 77 71 5 16.7 characters. It will cause that I think that's right. It's just think about the logic here, So if a person a description, we need a check because it can be optional sort. It might not be the case, and we need to check that the length is not griddle Ban. 16 777 que. That should be fine. We'll pass it in the air. A message. Task exception. Um, task description era. Otherwise, we'll set this description passed in description so they send the score description. Boston description. So that should be right. It's not know and greater than that. Dennis throws exception. Yep, that should be fine. Next one is through the deadline, but what will do well combined? Urlacher is a little bit mawr advanced. That one sold will move on to the completed warn him will come back to deadline in the seconds, or public function set completed. And the valets characters is y en end for this, if you remember, rightly so to check for that now we're not bothered whether they're open case or lower kiss . So what we'll do is we'll pass in any value and we'll convert that to another kiss. Just organ handle consistency Across the board saw TR two over. This is a stategy PHP from should not commit a string to other case, um completed and what we'll see is if it's not equal to why, Um, Andi, important on Dhere and exactly see him string to Oprah completed is not equal to know. So seeing here, if the value passed in is not a why, Andi, it is not an end. Then through the air, assaults through new Tusk exception on we will see I am Tusk them test camp has completed. Most be, um, why or pen cool? That's fine office, your passes and validation. Then we'll settle this on the school. Completed equals complete. So that said, complete. So now what we need to do is do the deadline. One. This a little bit more advance because it's a bit more logic in this one. So create the function. Um, set dead lane will be passing a deadline string and on We'll set our if statement. Hope on. Also, if it's successful, will set the deadline to the past in deadline care. So if it's not successful through new task exception passing a string and task deadline date's over time. Just what did time there? That's good enough. So the first thing we need to do is check to make sure because this is up, obviously, this can be optional, so we need a check of it. Has a value. So I've been like, what we do with the description there. So don't check. So custom deadline is not equal to know, man. What will do here is then do the check on the debt in time. No, Here we will try and create a day it from the past in deadline off. See, that comes in as a string. Just text the name. What we'll do is we'll try and convert it back to a string from a d it. And just make sure that the values much just make sure there's no funny business going on on the conversion. So PHP of it has a couple of function that could help us with this on the 1st 1 Um, we need to create the date. So did it create from groups from format? Takes two arguments. 1st 1 is a mask, which is like the former that would have supplied. So that would be did Men's year. I wear minute. 2nd 1 is obviously the past invariable, so that would be deadline. So that tries to create the day it I'm just gonna put the spaces here. Just look and see what we're doing. So now that we've got the d, it will need to convert it back. So instead of making this absolutely like massively long, I'm just gonna call it from the other function that would do in the conversion back. So I'm just create some spears. Could just wanted me to get clear about what we're actually doing here. So the other function which converted did back to text is did format. And then this takes two parameters. The first bean the day it object. So what we'll do, we'll put that in in a second because that create this function created object, so we'll just use out within this function. So the second argument is the mask this time. So we just want to try and convert it back to the same type just to do the comparison. So we did a month. Yeah, I were second minute story. Um, and then what want to do is compare this to make sure, um, that it's the CME. So if it's not the CMAs the past in deadline, So if there's any conversion issue that's happened here, ham and the values doing, then match back then It's an issue. So I'll do here have only put this over here just to make it a bit clearer. We'll just move this or cut this and we'll put it in as the first argument. Like I said, that is a dead object. So it was just to make a clear really. So we'll just get rid of this white space here. That should be our deadline function. Check here. Everything looks all kiss. Or if it's not so if it has a value, tries to create a date fall in this format of the past in string, then what it does is converted back to a string or tries to convert the date object back to a string. He's in this format, and then what we do is do a comparison check to make sure that the past in deadline is the CIA Mars, the conversion of the debt. It just make sure that it is actually converting the deer, too, and you know, back to again and it's fine. So now that we've got all of the set of methods, don't what we need to do is create a construct method. Let's create some space, appear now construct method allows you to, and it's a stand appear to be used What's called a magic method. It allows you to create a new object by just saying new. See task, Um, with problem with with prominence in otherwise you'd have to do something like Task new Tusk and then run the set of methods on its or you're right task set title and then obviously passing a title here. So we don't want to do that because just Messi would be nice if we could just do new task and then passing the arguments that we need here, Um and then, you know, title here description. Yeah, you get the point. So that's what we're gonna do. So the construction allows this to happen. So it's a public function. And then because it's a PHP magic method is to underscore, so to underscores, and then it's called Construct. We'll be passing in some values, which is your idea, your title. So we'll just quickly tighten these in now, just talking. Use them Title description deadline completed, and then all we're going to do is take these and run them through the set of methods to do our validation. Basically. So what we need to do is call the set of methods. So this set i d i d. And they will pass in the i. D. So this set title passing the title, they said it's not that lying description and then pass in description. No, todo this'll set a deadline. Deadline turned last one this set completed, then person that completed. Okay, so now that I've got that, so create the objects that I d title description, deadline complete. That's all the variables here. So do that. Okay, the next thing we need to do is, um, be able to sort of transform this object into something that friendly for the jets on in court that will be using when we, you know, send the response back. So obviously you can't have tasks, including that. So what we need to do is create a helping method to allow the former to be nicely sort of easily used within the response. So what we want to do is converted into an A re and, you know, from the response lesson we demonstrate that Honoria can be then properly are nicely formatted into Jason just by using the Jason in court function. So we're just gonna create a helping method public function, return task as a really it's not going to take any arguments because every soul that deals already in this object So we need to create a task ary and then set the theater. So first, once I d, um, equals this get I d task title. He calls this get title task description equals, um this'll catch description. Close hopes deadline equals this get deadline and should be last one task completed calls Thetis completed, and then we need to return. And it'll need to return the surreal, which is called Tusk. Okay, so hopefully that should be all we need to do in this model. So the test it we're going to do what we did with the response. We're gonna created the test file to try and create a task. Andi, return us to client Basically. So in order do that. We're just gonna created in model because we are going to delete it. My click model new file. We'll call it tusk test dot PHP creative page P start tag. So first thing we need to do is um, when you call in the file, the task file saw require once because in the same full lacking, just called Testa pH. Pete and then we need to try and creates the task. Now, if you remember, the task can potentially feel it can through a new exception. Where exception to concerned, you need to try and catch them if you remember. So that's what we're gonna do here. We're going to try and create a task if it feels we're going to try and catch the exception , so try and then catch on. We specify the type of exception we are looking for, and that's a task exception. We'll give it a name so we can utilize the message that will pass in, which is task I D era, for example. And all we're gonna do is just echo out to the client era, and then we're going to upend the message. So the exception, the exception class has a function already to get this passed in message, and it's called a get message. It's that simple, so we'll just call it get message, and that's all we need to do to handle that. So now we need to try and actually create once or task equals new. And obviously you remember that were created the constructor. So I'm just a new task and then pass in the values so we're going to try and create a task that is successful. So valid data. So one title here description here. Deadline, which is the sort of CIA 11 2019 12 o'clock. And then the last one is completed. And I'm just going to see in order that for the time being So we'll also test our, um, return task as a re and try and converted GS on just toe. Give it a whole test. So because we're turning GS on, remember, we have to set the header. So the client knows what type of data it is that's coming back. So remember that was content type application slash She's Sohn char set equals utf it? Sorry, do you have dashi it for this one, Onda and would then need to call the Jason in court and neck or the Js on data around. So echo jasan in court on. We need to see a task and then we need to get it as an aureus when you get the task as an Arria, so return task as a really remember of function that was created. So what we should be able to do now is use Porcupine to try and retrieve this task that we've created. So what? Make sure Mom's runnin on. Postman, take Nour El for the structure source Version one and stored it in model slash task test dot PHP to start to get request. So clicked. Send. So you see there that we've actually got a successful response. We've got the task back in a nice formatted way. So we've got the i d the title Ning. See there. Let's pick the values up. If only to do now is just to test that. Make sure some of the validations working, and that we get a valid sort of every response to go back into a test file on change some of this data so we know that it's involved. We should get an error messages time so we know that a task I d should be greater than zero because that's what we said in our court here. So said I d it's gonna be greater than zero basically so If I said that the zero just see of it and then try and run it. We should get an error message. There you go, Tusk idea. So the air is actually working, which is good. So if I said it back and then just try some other data will just take the completion status out because, you know, we said that it has to be a Y or an end, So if you just leave it blank and see if that don't try and win it. So you see, they were getting the error message, obviously, depending on what the ever is the changes. So I'll just say that back to end and what we'll do, we'll just try and put in, you know, the deer that incorrect. So we'll just try and change the months to 20. So obviously there's only 12 months, or in theory, this should feel, so we'll see if that run it again and you see there the task dear time era has sort of being out. Put it so that's what good looks like that validations working where we sort of responded back or returning it as sort of Jason, um, we should be good to move on to the controller now. So the controller is where all the logic goals basically a p I It's the fundamentals of it . This will be split up among sort of different videos, depending on what part of functionality that we implemented. So now that we've done with this, we can close this and deleted because we don't need it or delete task test. Well, this right click on delete. So Okay, I'll see you in the next video. 13. GET - Get a Single Task: in this video, we will start to implement that control of file in the first piece of functionality we will be implemented is the ability to get one task by providing a task i d. So if we start by Open and Adam and on the Left will be creating a new file within the control of folder so far, I click new file and we'll just call this tusk dot PHP. First thing to do is to start the PHP file, and then what we're going to do is call in all of the other files that were created so far . So we'll need the DB file because that's our database connection. We'll also need the response file because we'll be generating responses from this control of file now. And we'll also bring in the task file because we would be creating tasks so require once the 1st 1 is db dot PHP. Next one. Quiet Once this one's in. The model fooled us all after never get up to model and then tusk dot PHP and then same again, it's in the model fold up, and this one is response. Stop PHP have called in relevant files. Now you know, control it just going to see if that now the first thing we're gonna do is attempt to connect to the database. Remember, anything to do with the database can trigger an exception. So we'll have to sort of encompass this in to try and catch statement. So we'll try, and then we are going to catch on. The exception is a pidio exception. Uh, well, just give it a name. Groups No, proper that right? So in here, we need to create our database connections. Remember, there will be a right database connection and read database connection. So we'll create them now. Right? D B equals. Remember to static method. So called the name of the class, followed by the name of the static method Connect. Write DP Andre Reid, Debate Connect, Read TV. We'll see if that so. These are the message that were created in the DB class before you have got connected, right? Db connect. Read debate. So I called them attempt to connect to the database. Now, if it feels what want to do is output one of our standard responses. The 500 error message, like with de moored in the one of the previous videos. So what will set the responsive Now it's or response on, and we need to create a new response. And then what want to do is set thestreet escort So response. Set http this court in this view 500 because it's a server error. If Akon connected the dubious and the next thing we want to do is set the success. Two. False because it's an era. And then we'll out a message message on. We'll just put a string off database connection ever on. The next thing we need to do is obviously send that response back. So just run this send method, Okay, we'll see of that. So now will happen is attempt to connect to the database or both connections on the read on the right. And then, if a card, we will get a standard response back as a 500 now as well ascending the response back, we want to log it in a ever log file. So why was sister administrators could potentially find out if there if the sort of the my sequel survey is periodically time and out or something like that now, you wouldn't display the true exception error to the user, one that won't be interested in to. Sometimes it can come. You know, it can contain sensitive data such as user names and things like that. So you never want to display the era sort of to the use of themselves. But we want to log it just from a system administration point of view. So what we'll do here is used the build in PHP error log function that error log. Andi. We will see the type of message so we can see a connection error. And then what we can do is the pens. The PDO exception on that. So X takes another parameter of where you want to send this error message. Now you can look this this method up yourself on online, but zero basically means that its stores in the PHP error log file. And that's fine because our system administrator should be sort of looking through that periodically anyway, to see if that so. Now they've got our response. Normally want to do after sent it out is type exit. Just make sure that as nor following cord that comes after this can roll, I'm just excellent the script and because we already sent the response, that's sort of a nice sort of way to end. So the next thing we need to do is now start thinking about the logic off the A P I on bond . What sort of things we need to do in this video. Obviously we concentrate on getting a single task saw. That's what will start implement now. So in order to get a single task, we obviously need to pass in a task I d into the U. R l. The idea is that we would have a root such as tasks slash or sorry slash task slash warn. And what that will do is get the single task with an idea of one. Now, this bitch is sort of pretty fight, and we'll do this near the end of the video. But the were to understand how it'll work is if I just show you task I d equals one. So you're probably familiar with this sort of you are else. Here on you have parameters rul query strings as the cold that your append to the file in a web address. So what we're doing here is task I d equals one. So this one, this value here is obviously we're gonna pick this up and utilize that in our sequel statement to retrieve that task. So the first thing we need to do is to do in if statement because you need a check to see if it exists. So if inquiry strings there passed in by the get method, you could be Causton Or you could be deleting boat anything that in the query string you used to get super global. To pick this out basically get is an Arria off key values. So we're looking for a key off task I d and will be picking the value over that. So we need the first check if task idea exists or we'll use the function. Re okay, exists. Andi, we're looking for the task I d on. We're looking for that in the get super global. So now that we've got that, I just expand this not just school down slightly song, see where we are. So this says if you provide a tusk, i d Then do whatever in here. So the first thing we need to do is actually get that task I d so you can see here that the is something that has been presented to us in the task I d. So we need to get that So we'll just call a task i d For the time being, Andi will get this on task I d. So what I'm doing here is calling the get so within the get a rear that could be multiple in the query string, so we'll get the task i d. Now what we want to do is just to make sure Did Val idiot us soldiers do some simple checks on it? So if task I d um, it is blank because we're gonna throw out a standard error Messages standard every response if it's not valid data, just like what we've done in our task model and stuff like that. So if it's if it's blank or if it is not numeric, it was 11. Their task I d Then we're going to respond back with in every response. So create a new response. Hope Sorry. All the response. New response. And then we'll just build this off his normal So, um, response said http steer this court. We'll give it a 400 because 400 decline error. So that means that we haven't provided the right type of data from the client side. So I'm all set success to false that successful on. And we can add some messages in here so we'll see groups response. Um, odd message. I will just give it a string task. I d cannot be blank. Most be numeric. They will go. That's That's a fairly similar every message I never want to send it and then exit. So now done our ever check on the past in task i d. The next thing we need to do is to check what type off request method is. Remember, we're getting a single task, so we'll be using the request method of get now if we step back a little bit and just think about the types of things you will do on a single task and we'll sort of at these in is a place holder now, because that, you know, this is the correct point to at these in so on a single task, you can retrieve it. You can delete a single task, and you can also update a single task so they are the three things will be doing on a single task. Whilst we're on here, why don't we at these in this place holders so we can build it up As obviously as we go along in these in these videos, we need to check what the what? The request method is sore. If statement and then we'll use the server groups server Super Global on. We'll get the request method. So that's request method on will do a check to see if that is in the first instance. Get now. This is all the kind of logic that you need to work out what sort of request method it is. Now. I'll just like I say, I'll create these placeholders, Um and then we'll sort of build them up from here. So that's that. And then else, if hopes and then we'll just do exactly the same source ever, always missed the underscores. Out. Make sure you put them in. I keep missing the boat and request method. And then we mentioned delete So will handle the delete on. We will also so else if Sarah request method on the one for updated in, If you can remember it is patch, so patch now what want to do if it's not, if it's not any of them. So see the ascendant in another one, such as Paused. You would never paused on a single task. You would pause just on tasks because post is normally used for Korean. So you couldn't pulls task one, because it doesn't really mean anything. How can you create task one. The system automatically gives you the identify or the task I D. So why Why would you provide one? So we'll just put a catchall in the bottom? Which errors are handles a standard every response. And what we do here is just building a standard response is normal, and we use the status court of four or five, which basically means request method not allowed. So it's a catchall fourth, any sort of request method that's not get delete or patch. So I will do. Here's build up the response. Um, and the first thing is art. Sorry, can you create the response and then stop building it up? Sore response City it Phoebe Status cord. And this is a four or five on, and then we'll set response up on will set the success false on. We will add a message and the message will be request methods not allowed. And then we'll send that back on wheel exit. So you say here with started building up the place All this obviously will do these and earlier the video on the one we're gonna be concentrating on is get method. So I'm just going to minimize these for the time being, just to sort of make it simpler on the screen. And I'm just going to create some space in here. So now that we've got our request method set up and we'll just focus on getting the moment first thing we need to do is to try and retrieve the task from the deadbeats with the past in task I d. So we need to attempt to query the database like anything else with the date abyss. It's between a try and catch statement, so create our try on our catch on. What we'll do is PDO exception. That's the database that we'll just call it Hey X, and we'll start building a query up sold to see Queary. And then the were that you create a queer using PD or is used prepared statements. Now we'll show you here, hold a build these up. Just stepping back a little bit. Will have to database connections were called the Read and the right database connections. Now, anything about what we're doing is just literally retrieving a task so we don't need to set up the right database. We don't need to be synchronous. We just need to retrieve the task from the database. If we use the redid abyss that that means that could potentially reduce the Lord on the master dear dubious server. So use read D B, and then what you do is called Prepare. And then what you do is pass in the sequel query. So what we want to do is retrieve everything to do with the task. So that's the I. D. The title, the description, the deadline on the completed status. So select i d. Title description Deadline will come back to that in a second. Andi completed from another table wars tbl tusks, but will put where the I d is equal to task. I d. Now you're probably thinking, What's this? If you don't really know much about PDO and prepared statements But this is like a placeholder, and what we'll do, we'll bind a variable to this value that get inserted here. This stop sequel injection and all of the other sort of nasty stuff. Sort of good were to sort of do you database queries. So, as I mentioned before will come back the deadline because what we want to do is format this because this is held as it did in the database. We want to form at this to be consistent with all of our other did. Now that is dear Month, year Spierce our call on minute. So we need to use the deer format function from my sequel. So the first thing is the deadline. And then the mosque saw We will put in groups we will put in the masks or ladies percentage D slash percentage M hopes slash percentage. Why Space percentage each cool on percentage. I So we will be retrieving the deadline. But in this format So dear month, year, our minute. So if we just on the next line, we need to bind the parameter. So what we'll do is Queary hopes, Queary, And that was what we re correct and then it's called Bind, Haram because we want to insert the task I d into the sequel. Query. First thing is, which Which placeholder was it in a sequel? So it was task I d on what is the variable that you wonder insert in there And that was task I d So this task idea is the one that we got from the u R l basically the query string . So what store than in the task? I t already done our validation checks on it, so hopefully we should have a number. The task i d on the type is PDO Haram. And because it's an indigent number, it's a number basically. Okay, so now that we've built the query open you to execute it. So Queary, um, execute that should ruin it. Now, hopefully, if we've supplied a valid task, i d We should get some rules back. Um well, e rule. Because, you know, task ideas a unique So we need a check. So if we just create a new variable called rule count Andi Queary raw account, so that should stall the raw account. And then what we need to do is check to see if any rules were retrieved. If not, if the zero rules, then we can send a standard response to see Task not found. Now if you remember back to the status cords, have you? You know, you browse thean end of clicked on a page and something hasn't been found. You normally get a four or four error, so that's what we're going to return. So, first of all, for check the rule account rule, count on for checked that is equal to zero him. If it is, that means there's no roars. Founders North tasks found the lack task i d. So we'll send a response back, so we'll create our response. The response on We'll set the stairs court on it is a 44 error. That means it's not found and we'll set the success flag. I said Success. We'll feel that's false. Andi will out a message to see that the task wasn't found basically, so add message task not found kit so we'll send that back on will exit. So you see, here we are trying to retrieve the task for that given task, I d try and retrieve the how many rules has returned If the task I d or the task with that idea doesn't exist, then we send his standard four or four era back. However, if the task does exist off, the road does exist. What we need to do is retrieve that so for do while and then rule. Then what gets the Queary hopes of Spalla Wrong Queary? And then we want to do a fetch on we want to fetch and a source associated a rear back. So that's a key values. Basically, it's just easy to work with. So PD or and then let's fetch. Yep. So fetch that back, Andi. Right. So now what we've got is the values back, which is your idea. Title your description. So now that we call the values we need to create a task from that Now remember, we've got a task model, so we should just be able to use the new new task based basically in Pastis in now. What that should do is do all of a validation for us. But to be fair, the stuff in the deer dubious should be valid values because the went through this method to get in anywhere on or the beginning. We've inserted stuff just to get this bit working. But you'll see later on that. Actually, if we try and create a task will provide strange data or not volunteer, then we should get every spark. So the first thing we need to do is, um, created Tusk. No going back to task. We can throw exceptions here, so we need a handle them. So if I go back to the task control of file a school up hopes there, you can see that we are actually already in a try statement. So all of this is within a try. Now, at the moment, we're just catch in database errors. But if you remember from a previous video Aiken See, actually, we've been cash specific exception types, so we want to catch or potentially catch a task exception just like we did in our testing. Now, if you remember what I said, we can catch multiple ones by just listing them one after each other. So we'll call this task exception. So you say here it tries to school up, it can try multiple things. So it's trying to query the database. If that Harris, then we'll be caught by the PDO exception or when we try and create a task here. If the data feels or there's something wrong with the task, it will be called by this task exception and we'll implement these leader. So if we try and create a task now, so our task new task and we'll just pass in the values that were retrieved back from the rule. So if we do and the 1st 1 was rule, they'll be the idea. So rule I d. The next one would be rule title. The next one would be raw description, then deadline. Then there was the company. That status wasn't a sore role completed, so that should attempt to create the task. Now, I know this is in a while statement, but the years only one rule and I'm just trying to be consistent because in a later video will be retrieving all tasks. Now I just want to use the same method basically here that we're using just not, you know, the stock, any confusion. So now that we've got the task back, hopefully and that it hasn't felt to the exception, we want to store this task in our tasks every I am like, I see we're doing this year, even though we're just retrieving one task. Yeah, respond should be consistent. So if you're gonna have one task, it still should be in a really could potentially up multiple tasks. It just makes it similar to then for the client handling the response. So it will just created tusks task, Correa hopes. And then we will at this task. Now remember, from the task we heard we created to help a method called returned task as Arria and we'll just be using that sort task Return hopes 10 task as a re case. Or now that we've got the task, we've added to our task Serie What we need to do now is return the rapper that normally done with the response as well as any tasks that's being brought back. So just outside of that will just get rid of this white space. Given all that as well, to be honest, tidied up a bit. So now we need to create our sort of return. Did every turned dealer We'll just call this start a clean a rear. Now we need to odds the tasks themselves, but also the rules returned as well, so the client knows how many tasks have been returned. Now, in this case, it is just one task or awfully one task. But it's always good to return it anywhere. So return Deirdre. So Ross returned. That's what will be displayed on this on the screen, to the client. And then we'll add in the rule count because we got that from the query previously just up here. So it means, well, reuse that. And then we need to add in the task sort return deer there. And this part is tusks. Andi. We sort of appends the tusks Arria through the task Correa to that. So now that was set the return, Dear the rope. We will send the response back so we'll build a response up now. This is a successful response, remember? So it's gonna be slightly obviously different because the ones that were built previously are all sort of one successful responses. So this one makes a change. So what new response, And then what we'll do, We'll set the http cord to begin with sore set if he steered US court and this is a 200 because it was a successful hoax. Then we will set the success flag. Smart response. Wrong there. Multiple times response and then so set success. That is true. Um, now think about this. We want to be able to catch the response back. So if if a client attempts to get a task off I d one for example you know, multiple times within a minute or 30 seconds, why go back to the database servants, you know, get that to do the work when? Actually, that's probably very little changed within 30 seconds off getting that sore. If remember, from the response that were built, we had a to cash function. And actually, we're going to use it here cause they're going to say we want to be able to cash this response. So it was to cash. I want true. So now we need to set the data Would never use this function even in our test. And we've never used this one because we never really returned any theater. So, um well, use this now. So responds Set. Did you know the data that we're returning is the response data and this contains rules returned on the list of tasks So return data on, we'll send it. So response send in that exit. Okay, so I'm just gonna get rid this White spear. So let's have a successful response on what we'll do is quickly implement the standard response errors that will get here. And really the only thing different would be the every message, because it is just a standard five under response. So what we'll do is we'll quickly created here. So response equals new response hopes. And then we need to set the status court. It would be 500 error because it's a server. Erin, at this point, we'll set thes success flag on its false, and we'll add a message and, well, basically, just see here. Um, so this is a task exception. I guess. The good thing with task exception we built in all of the standard error messages. So go back to the task model you can see here we built in the standard error messages, so we should be able to just return this in the message. So from here, we'll just see a B X on it was get message, remember from the test on, so that should just return the standard error message that we added in here as a message within our standard response. So and then what we want to do is send it and then hopes and then exit. Okay, so the PDO exception very similar. However, all I'm gonna do is cause we already sort of build a standard one up here. Um, I'm just going to sort of copy this because it's already built. See if that's a bit of time, just school back down. Pierce that in there? Um, we'll just change this slightly. Just makes more sense. Did a best Queary Kara, And then we'll give the exception error to 500 cause it's still a server error on. It's not a connection ever. We'll just see if feel to get Tusk just a generic every message feel to get Tusk. Okay, if I just get out of this white space, see if that so hopefully we should be able to test this. Now, um, should be passing a task. I d. Hopefully, I'll search the database, create the task and then return the task. So what we'll do is we'll just make sure to see if that on we will fire a postman. Just make sure mom's Moonen um minus. So I'm just gonna open postman Kearse or we're just going to go to our local host again. And then the poor was idiot it remember it was the one Onda We are looking at the controller, so it's in the control of folder. Like I say, we'll tidy this up next to make it look pretty, But this is just for testing purposes on this is called task dot PHP. Remember, we need to put in the task i d in the query string soldiers see task I d one I will send this it to get request. Like I say, we build a placeholders for delete on patch. But it is just to get request with testing here. So hopefully five million years Hey, there we go. So we've got I was standard response so you can see Status court and also that much as the stairs caught up here. Success is true nor messages because it has actually returned some data and then once I would did within our data. We have rules returned on the list of tasks, So obviously there's only one task in here, but this is where you would have your tasks. Now, you see here that the deadline is no going back to our database rules that we created. That is correct. In just a double check that I'll just go back into the database on Did you can see task I d warn. And it has a blank deadline. Now if we try and retrieve task I d to So we go back to postmen and just do task I d to to change out at the top and send it. We still get a knoll deadline. Now, that doesn't look right, because we do have a deadline in the task I d to so quickly. Do is just double check our dear. I were cordon just to make sure that we are setting it correctly. So go back here for scroll up and then we're looking here. So, dear format, we are returning deadline. Oops, I forgot. Actually, alias status deadline. So as deadline because of the moment the column would have just said did for much. Except now I want to call that deadline so of how to alias it. Saudi's called that so I'll just see if that and then we'll just try it again. So there you go. That was established. A simple fix. So deadline has now returned in the full days. So we'll go by the task. Warn? Still No. Which is correct, because it doesn't have a deadline for Go task three. So there you go. Now, if we try a task that doesn't exist so if I quickly look, Andi, anything greater than six or seven shouldn't exist. And I should get a 44 ERA back. So for changes to fall Sorry. Seven. So there you go. A status course four or four. The success is false and messages is Tusk not phoned? Miss Nordea. So you say there that our logic is working, so that's pretty good. Now we'll just give this a test. So we try and send something like paused to talk to a task I d. You can see there we get a four or five error, which is request method not allowed. So that validates that our cord and logic is working. But just change this back to get and changes back to task. I d one. Everything's working. Fine. No. The nice thing about this, what we need to do is tidy this up a little bit. You know, the client shouldn't need to remember all this. What they should be able to do is just type in task slash warn version one of the FBI, and we're trying to retrieve task I d. One back, just like we did here. Now. Currently, if I send this now, I just get the standards, mumps, sort of four fire. This is not a standard response that we would send back. So what I need to do now is to handle this. So go back and Adam. And if you remember the very beginning we edited a file called the H T access file on. What we've done in this was basically just turned PHP errors on just so we could use thumb for development purposes. Now, within this file, this is where we write our sort of pretty roots saw slash task slash one type of thing. So what we're gonna do now is go through this and just create the warn that will pretty five, this one. So what we need to do is tell Apache to turn the rewrite engine on because we re right in ur l to me get to basically have any alias re up spree re white engine on. And then we need to put some conditions in, So ri, right? Oops. Icon spill, rewrite condition. Okay. And then what we're gonna put in here is, um, request on the score file. Name hopes will pull on the rope, request file name and then 50. I'll explain these in a second. I'm just write them down yet. Really? Right. Condition. Um, request file name. Right. So basically, what this is doing is don't rewrite if the requested file name, for example, you are l is a directory or folder, Um, or if it's a file, I just want to enable this to still call folders and files. Aside from the C A p I stuff. It's kind of out of the scope of this course. Apache config is a core course on itself. Sore. It may be worth looking into that if you're interested. But for this course, all we need to do is that. And then we need to do our rewrite. And here saw three. Right? And then it's a rewrite rule, and then it's a tusk. And then so this is our pretty you are l or pretty route that we're creating here now. Tasks slash Andi For this one, it's any number. So what we use here's a regular expression. This is also out of the school of this course, but I'll just show you how to do this. But you know, regular expressions are a big topic and themselves as well. So we want to see a well would warn. You want to accept task ideas. That's numbers. So it's not to nine, and then we need to have it needs to see it needs to include That's what the plus means. It needs toe have one or more numbers, and then we'll just end that their aunt, the U. R L that would tighten before. This is sort of what we use here saw controller because version one will always be used anyway. So I'll rewrite everything after the one which was control a slash tasked our PHP and then it was task I d. Now what we do here because in the regular expression, we encompass this in a in a sort of brackets. We can use the value here and put it here now to do that. It's dollar one. So if you had another set of brackets after this saw slash one slash one. You know, I'm not in That would do in this course. But if you if you were, you could see well, the next piece of deer that your supply and would be dollars too ex cetera. So you can use these placeholders and, you know, use the values within the U. R. L Okay, saw what this is doing here. Is rewriting that toe look like this or tasks slash than a number. And then what we need to do with the end is just see if it finds a much on this rule. Just that's the last rule, because the order of rules can actually make a difference. What we want to see if it matches on this, that's the only rule you should have. We will be creating more rules, obviously, for our different on their end point and roots. Elliott Iran. But that's that's all we need to do. So now if I see if this will see the HD access file, go back to Postman and remember when we run this before it just give us a four for just the generic mumps sort of 44 page. So this tributary of the task I d with one have made a spelling mistake. The electricity tasks remember, always used florals always use plural, because doesn't matter if you bring about one task. So if example, all tasks would be tasks or one task, which would be just slash one. So send that in. There you go. You can see that now is brought back. Task one changes to task to see. That's no task too. So now I've created our pretty route. So instead of using task dot PHP and they're not in sort of query parameter off task, I d with no pretty rised it up. So in this video, we have school back. Yet we've created the logic to return one task. And now in the next video, we'll concentrate on the delish in of a task. So whilst were in dealing with single singular tasks, we will handle the daily task next 14. DELETE - Delete a Single Task: in this video, we will be following on from the get single task epi I an implement in the delete single task. So for one about him, and from where we left off, scroll up. This is the get request. So that was to get the single task. I'm just going to collapse that because now we're going to concentrate on the delete single task. I'm just going to make some space here, and we'll go straight in on. What we need to do is attempt to delete the roar from the database because we already have the task. I d hope here we should be able to just go straight in and implemented elite rule. So I need to try on a catch like we did previously. And it's PDO exception the cops down a bit, sort and see a way. We're going. So in here, we need to build a query up to delete saw Queary Queary. And because of the leading, this is not a read only request, So now will be connected to the right database. So we need to call this query against the right database. Right? Devi, prepare Onda. We need to write the sequel Steam and not what we want to do is delete from tbl tasks where the idea is equal to the past in i d so delete from tbl tasks where I d equals task I d remember using placeholders yet, So the next thing we need to do is buying the parameter. So Queary find Haram on iwas task i d on the parameter waas The variable was tasked fighting on the type was PDO Parham int and they would just need to try and execute it. Okay, so we'll call the roll count on the query because that should return the amount of raw zealots deleted now because we're personally you get unique. I d Then it should just be one rule, so we'll be able to check to make sure it has deleted something. So, um yeah, we need to get the rule count. School rule count equals Queary. Well, count never do the checks. Or if the rule count is equal to zero, then we need to send our unsuccessful return response. So we'll build a response. New response and then response. I am setting TTP Steelers cords. No, generally Well, haven't here. Um, if there was an error deleting it. It should be caught by the PDO exception. However, if it attempts this query, but it doesn't delete any rules, then what it is is basically the task. I d mustn't be found. A roar mustn't exist with an i d off the past and I d so going back to what we did before where we provided a task i d. But there was no raw for that task i d. It was a 44 error. So we'll return a four or four chord because it is not found its task not found on. We will him set the success flag to false Andi on. We'll add a message and we'll just see task not found. So it's very similar to the previous message that were created and then response. Send, then exit so they will try and delete. If it's successful, delete that rule country be worn. So we handle. If it's if it zero saw. If it hasn't deleted anything, then we send a standard response with a 44 task not found. However, if it is so, if it is successful, um, we create a new response. So, um yeah, so sponte equals new response response on Set it she api steer scored. Obviously you see the pattern here? We're just creating a lot of responses dependent on the logic. So the state is called, um, if successful would be 200 because that's a nor case status court on will set the success. And that is true. Um, we'll set the message. We'll just see task delete it. So response Send exit hopes. Que so that that was carried with white spears. So this one's actually really simple one it tries to delete if it has deleted something. Sorry. If it hasn't deleted anything that comes testing are found. It has to leave it something it sends here successful response back to the client. So what we need to do now is handle the every response with some sort of connection issue or query issue. So school down, Um, response. Um oops, new response. And this is like a catchall sort of era. Sore response, said th steers court. And obviously, if there's PDO exception, I mean there's server era, so it's 500. Okay, in response sets success the false. I want to send a message multiple that in court feel to delete Tusk, then we'll send mix it. Okay, so for this white space, so that should be it for the delete so prepared. Delete. That's fine. Yeah, that's looking good. So what we should be able to do now is test this right space. So if we try and send a delete to task warned, we'll just go back to our mom. Task one is still there, so we'll just try and delete that. So got a postman change it to delete, and we're gonna do Here's use our roots. So, http local Horst needed idiot. Now it was version one. Now it we now using a pretty five version because we're set it up. So it was tasks slash Warner. So deleting the task with i d want so send. So that looks like it is successfully to leave the tasks to hundreds days. Court success true and tusk deleted. So we quickly go back to the database, refresh that and you can see now task warn has been deleted so that that's working. So now we go back to post month and just changes to get so now that was deleted. If we're just trying to retrieve it again. Task not found. So there you go. That's successfully Sures. That was deleted task. So if I go to delete and then if we choose the task seven like we did before it doesn't exist and send it, we'll get a 44 which is correct. Task not found. So that shows you that the logic for delete is working fine. Quickly. Go back to Adam. So it deletes all successfully. Don't know. Now, the next part of the single tusk functionality. So we've got retrieve. We've got delete. The next one would be to update a single task. This one is pretty complex. The logic in this So what we'll do, We'll actually come back to this. We'll come back. We'll come back to this in a little lesson. 15. GET - Get All Complete and Incomplete Tasks: in this video will be implemented to get for all complete or incomplete. The functionality here should return all complete tasks or incomplete depend on the value in the U. R L So for good, Adam things he hear what we implemented our last video scroll up. So this was getting a single tusk. So what we're going to do, which is going to collapse all of these? Collapse that and collapse that or kiss So you can see here that this was passing a task I d That's what we want to do now, when this one is actually passing a completed indicator, so are why Orrin. And I guess so. I'm just going to get rid of this white spierce. And this if steer mint is inclusive here. So what we want to do is doing else if so, else if really key exists, and then who pass in, completed in the get Okay, so we're just going to minimize this. So now what we're dealing with is if completed, and this parameter will have a Y or an end, so an example of the or else is slash B one slash tasks slash complete slash b one slash tasks slash in complete. So these are the pretty fight you RL's The true you are l will be slash v warren slash tasks Very tasked a PHP and will be completed equals why that will much complete or and which would be incomplete. So that's why here we check to see if the completed parameter is passed in the query string . That's a this bit here. So obviously we'll have to go back tro Entity access file and have these in at some point. But let's implement the logic first. It's very similar to the get single tusk. So will be Instead of getting a task, I d will be getting a completed status. We'll be checking to see the complete status is valid and then we'll be doing a check to save it. Does it get request this u R l or this route will only accept a get request, won't accept any other request. So if we the first thing we need to do is to get the completed it is called completed on git is get complete it so they still get the value within the completed query string and then we need to check the value. So if completed, that's both correctly complete. Yep, is not equal to. And it's a why Andi, it's not equal to completed, is not equal to. And so it's not a Y or an end. Then we will send a in every response, basically so response. You response. Um response 32 GOP Steer this court and this will be This will be a 400 error because I haven't passed in the correct value. Basically, to this parameter response. Saw and response said Success, false on and response message and we'll see completed, um filled a most b y hole and and then we'll send it exit. So that is Theo. The failure response. That's fine. So it's not a wire on end. Then it sent a default sort of response back on. Now we need to check to see if it is get response. If not, then we need to send another standard every response back. So if remember the server Louisville for request method, we need to see if it is them. Get else, then we need to send a standard response back for four or five, so response equals you hopes. Response response set itchy if he steals court member four or five. So they're trying to send a delete or opposed to the completed route. So which would be slashed? Tasks slash Complete slash tasks slash incomplete off so you can only get you can only retrieve from that. So they're trying to send anything Bush A retrieval to get them will send one back, see, and sending Erin back, seeing that it's, you know, that it's not followed. So response set success, False response. A message on request method not allowed response send and then exit. So have dealt with the era. Gonna get rid of this white space here. So dealt with the era. Create some space here. So now if it is a get response, we need to retrieve all tasks that have a completed why or depending on the the route that would go down or completed in. So we need to attempts to retrieve thes using the date of this connection. So remember, try and catch so catch, um, it will be pidio exception begin with this will obviously contain the task exception as well. So we'll just put a placeholder in Furlatt catch task exception. That's them So what we'll do first is set up the responses for the task exceptions and the PDO exception. So for start response, new response this one set. Did you please stay discord of the task exception? Then it will be 500 era and response said Success. False response. Uh, remember for the task exception, we had some messages automatically bean output depending what the problem Waas it's or a call them out, basically get a message and this once, send and then exit. So that's that one. Um, we'll just copy this. Temporarily pissed it in there to find in every message. Exactly the SCIAM art message. So this is a PDO exception. So we'll add our own message in here, which would be something like feel to get tasks or something to get tasks with a pidio exception. We utilized the era log function because we shouldn't get database errors than these should be logged for our system administrators to to run through. So we'll use this hair a log on did ofhis Queary Uh, and then we'll depend on the exception error message, and then remember, it takes another parameter about where you want to show the error. So we want to show the error in the era. Log for PHP can get a send emails and stuff like that be worth looking up this function on the PHP Web site. But we're utilizing the zero, which means just stored in the error log. So that's our two exceptions court and handled. We will now send the database query by starting because this is well read. And again, we're not We're not doing any updated morning reading. So will attempt Queary. They read theater base connection. So, Queary, um sorry. Um, read TB, and then we will prepare Onda. We will. Right. So what we want to do is very similar to how we retrieved a single task. So we will select the i. D. The title description deadline will completely on the second completed steer this from our table tbl tasks. But this time we will look way complete. It is equal to, um in the completed place. All that deadline we need Teoh format. That again. So did on this golf format passing deadline. Um, and then we need to put the mask in, which is, um so there was percentage dear slash percentage months slash presented. Why? Percentage our cool on percentage minute. So that should be that. And then the mistake. That was the last time we need aliases to us. Deadline, kiss or select i d completed from TVL. Tests were completed. This place was completed. Okay, so we need to bind the parameter now. So, Cleary, find Haram. Now, this time placeholder is completed. Thieve variable for school of slightly is called completed on the type. This time it's not an energy. It's a string value because it's a y or an end. Um, till p do your and then it was Parham underscore s t r. So that's a string parameter. So now what want to do is execute the query, okay. And then you say I'm just sort of going through these fairly quick because this is very similar what we've just done in the get single task. So we need to check the raw counts or roar. Count equals Queary and Count. And then obviously we need to dio you need to create a blank Correa this point task serious or task re like Maria Ready to return, hopefully filled with tusks. Maybe so this time actually, don't need to check if there is any returned because it will always be successful. We're not going to see this task does not exist or north tasks exist. We're just going to return a blank tusk surreal with a raw count of zero because it's not really narrow it it's just actually the is no data, whereas previously we're seeing get task five, for example. But task five didn't exist, so that is an error. Okay, so now that we call the Blangger really need to return all the tasks, all the rules, so we'll do the wild loop again. Um, that was raw on it. Waas the Queary Fitch. And then it waas the associate of RIAS or PDO fetch Sore feared that Arria. And then we need to attempt Teoh create the task because we're need to try any potential issues will be caught here as well as obviously pidio issues. So she'll be able to just attempt to create the tasks or task new task and then we'll pass in. 1st 1 is so it was rule and then I d rule title Greul Description rule deadline rule. Complete it. So what? I d title description deadline and completed That will be a test created and they won't want to do is add this tasks or Tusk re. And we need independent to that sort task. But we need rip ends The the the every representation off the task. Remember that? Help A message that were created. So I returned task as a re. Okay, so just get rid of this white space. No, I don't know where we are. No need to set up our return dear s or return did. Ah and this was started long career and then we need to upend. Um return deer there on this was roars. Hopes returned Will set this Teoh the roar Count on the tasks turned dinner tasks should be the ary of tasks Saw that was task Correa. I hope so. Variable. And now we need to send a successful response back now that I've got here, So response equals you Response Http. Steers court tribute to 100 response slits success True. Um, we need to allow it to be cached because we're returning theater. I mean, this is obviously dependent on your requirements, but for this we know that we can catch the response that was set up in the in the response model response to cash. It was true on we're going to set the data. Did, uh, Anil pass in the return, dear should be fine. Um, we need a send it back. Just get rid of this white space. So hopefully that should be it for this. Um, so check to see if the completed is in the query string will get the completed. We'll check to make sure it's why. Or an end. That's the only valid values. Um, well, then make sure it is Get on. If it's not schooled out, will catch that here in the else, um, to see that nor the request method is allowed. Just give this one spierce school back up, and then we will try and get all of the completed or incomplete tasks from the day it appears. Um, we'll add it to a response on will catch any exceptions if they were to occur. Okay, I'll see if that right now we need a quote, create our prettified route so we'll go back to the HT access file on. What we want to do here is create another rewrite rule. Oops. Right rule on and tasks and then it's complete. So this is the 1st 1 So this is all complete tasks. Groups on this is your only used before controller slash task dot PHP on it was completed on the complete one. Should have a why on on the last parameter again. So you see here this is Thea. Actually, you are l that will be using within the control of full of the task PHP file. And then the query string is obviously we checked for the completed them parameter and that is why so that should this slash tasks slash complete should return all completed tasks. Now, what I'm gonna do here is just copy this because we want to do in complete Andi were the n not exactly same rule. It's just slash task slash incomplete maps to control a slash test. Appeared p were completed is equal to end. So we'll see if that so. A lot imports man up on. You can see here. This is our request from the last video. So I'm just gonna close that create a new one. It should be p local Horst Poor idiot. Its last 31 slash task slash complete. They should return all complete tasks or completed tasks. So we'll send that. So you see here, um, we've got two tasks returned. Task I D three in task I d five and see here completed is why for them. So we'll just quickly check the database to refresh out just to double check. Now, looking here, the only two tasks that are complete our three on five. So that looks like it's working. So if I quickly go back the postman and change this to incomplete so it's slash task slash incomplete send that we now get three returned. So that is 24 and six innings. See here that these are not complete. So 24 and six. Now, if we check the date of this you see here too for on six are incomplete. So that looks like it's working quickly. Go back to Adam. We've created the pretty five you RL's all the routes. Um on we have created the completed logic basically all the incomplete logic. So this allows you to return just complete tasks or incomplete tusks. In the next video, we'll set up so we can return all tasks. Doesn't matter whether they are complete or incomplete. We should be able to return all tasks 16. GET - Get All Tasks: in this video will be implemented in the end point to return all tasks in the deadbeats regardless of their completed stairs. The end point for this will be slashed tasks. So for one Adam up, you can see the completed one that we're doing another last video. So I'm going to do is school in the bottom of that? Andi this'll next one would be, um, Pell's if on the check for this. So when we return and all of the tasks, we won't be supplying the task idea and won't be supplying a completed Steelers, it'll be empty so they get should be empty. So what we need to do is school down. We need a check to see if it's empty, so they would go so checking to see if that global variable is empty or not. We need to do, though, as a final catchall is providing else Aunt create a standard response to see the end point wasn't found. So if they do something like slash tasks slash ABC D 12345 that doesn't mean anything to the system, so it should just return the 44 error to see at the end point wasn't found. So that's what we're going implemented here. However, if there were to supply a task, I d over completed status, then Obviously, it will follow this logic here. But if they ever, you know, send something completely random, they will need a handle that. So all we're going to do is set up us on error response here. Just quickly set the strategic could be steered his court on. This is a full fire. Er that success false. Um uh, message. Um, endpoint not found. Just send it back. Didn't exit. Okay, so that's Harkatul doing. Um, now we school backup will just collapse this sore within. Concentrate on returning all tusks. Now, think about what we need to do here. So the root for this will be slashed task and that's it. Um, were no person any I d or completed status. However, the slash tasks will also have, um, a post request applicable to it. So post will be to be able to create a task which will even meant in one of the next lessons. So we need a check to see if it is get or posed or otherwise. We need to see the request method is not allowed. So these the only request method that allowed for slash tasks. So the first thing we'll do is check that. So if, um, server request method is get or else If so, uh, Quist hopes, method posed and otherwise I need to see else on send, um, her response. And this would be a four or five. So they send something like a delete to slash tusks. We don't want to be able to delete all tasks. I mean, you could do that, but our requirements all that we don't want to be able to do that you must delete one task at a time. So said that that success as false we want Teoh at a message request method not allowed send exit case. And I've got that. So we'll implement the creation of a task leader. So the placeholders, they're ready. But we're gonna focus on just returning all tasks regardless of any status or task. I d. I don't need a query the database. So you try and catch again. Oops. So catch pidio exception the X And because returning tasks need to catch any task exceptions as well on will set up a standard responses here, maybe six. Setting these up shortly. Put, they've got to be doing and your response sticks Court 500 era that success. False response message. Because it's a Tusk exception. We you can get the error message that we send out in the task exception send groups exit, killed Kabala just to save a bit time. I was quickly Selves and quickly said this to um So I said this to feel to get tusks, um on we will ever log him. Did this Queary era the X zero kill? That should be fine. So have set up the two exceptions find it ever was so fuck to the query. So Queary equals, um, this will be a read only query. Now, obviously the post when will implement that leader? That's obviously ah, creation of write DRS. Or will be using the right database on that one boat for this one. It is read DB on it is pre pair. So what we're doing here is returning or selecting all rules regardless of any other data. So select i d title description deadline completed from a TPL tasks compacted deadline and well did it form out that in the mask for that is forgot about these in court. Single courts don't have to do that. Um, hand this force sent thes slash percent him percent edge. Cool on percent I And as deadline, make sure you put the Alstead lining. Okay, Still, check that plane and complete. So this should select all rules in the deleterious. We're not dependent. Any parameters or anything like that. It is just a little sort of all or nothing Taylor things or Queary execute on will create away, um, blank task Arrius or install the tasks in it. Hopes, Andi, before the do the while, we will get the amount of rules returned against or the role can't Queary count? No, I've got that. Um Well, no, it really over all the rules. So, um, Roy equals Queary. Fitch PDO fetch school down a bit. So we're going Does your feet role created? Tusk, You're tusk. So what has had in the prominence here from the return roars? Okay, so that's created that. And then we need to a pinged the tusk to tusk ary task return tusk Ellery. Okay, so that's for each rule tries to create a new task, if it feels, gets corporate task. Exception. So now we need Teoh have create the response data. Um sold Set up return, dear. There are a blank career. So I've been a pen stuff to it. And then the first thing need to set the Tyne Theatre um Rose Return. Sorry. Yeah, that's right. Um, rule couch return data. And this is where we need to. Said the tasks on the list of tasks in here that was task Correa. Now we need to send our successful response so quick response scroll down so I can see where we are. Um so his response? I said it. Three stairs court. They should be 200. That success Flug true. Um, and then we need to Yeah, we can cash this as well. So Teoh Cash Shops. So that true? And then we'll add in the daredevil seven data response. That was No, that's all right. Um was turned. It was not yet. And then sand on exit. It's clear that white spears, so this shouldn't know. Um, so we're not providing any query strings or values in the Queary? Um, it's a get request within trying create quite spears trying. Create and run the query. Well, then return that attitude that send them standard. Um, response. Some standard, every responses here, white space and we'll implement that. Posted a later stage? Um, yes. So if it's not get and it's not paused, then we'll get our generic error message out of this white space, so that should be fine. Saw what we need to do now is go back and oht access file. No need, Teoh create new rewrite rule. And for this one, it should be just tusks. Um, actually, it's just tasks, isn't it? So and then it is up to control, uh, tasked up here to pay. So this is just slashed tasks and that's it and that you're just Mup to task. Legacy would make ensure that the query string is empty so it doesn't contain completed or task i d. So they get all is just slashed tusks, so that should capture that route. So we'll see if that now, if I go to postman and this is obviously from our last test for the incomplete stuffs off close that create a new request Local Horst poorly idiot slash B Once life tasks and then just send that we get five returns. So Sears Court 200 success is true. Who will get five returns and this is a list of all the tasks have got them all here. So 2345 and six So recorder, I would dare to be us. We've got 2345 and six. So what we should have now is all of the tasks off. We created new ones in here and then we run this query again. We should get the Tustin or six returned or seven returned however many we create, so that actually looks like it working. So if I try and run a delete on the same route because we should allow, get and paused, I should get an error message yet, So we'll get a message. Request methadone loud. So I'm not allowed to delete on the roots slash tasks so that it So that's all of the tasks being returned all at once. Now this is good. However, if you have, you know, my knobby tasks that we're talking about, it might be product in a store. Now you don't want to return all of them's products all the once in one request because, you know, you might have tens of thousands of products, and that would mean that the query would take literally ages to return. It would be a lot of data, especially if using a mobile device to then return over a mobile connection. Now, in the next video, what will be doing is lamenting page in on them to get all tasks so you can see well for page one. I want to return 20 of the time, so it will be the amount of tasks divided by 20. So that would that would mean you might have. You know, if you've got 40 tasks, that would be two pages full of 20 tasks apiece. So we'll see you in the next video for that one. 17. GET - Get All Tasks With Pagination: in this video, we'll be implementing the functionality to return all tasks but a 20 per time on a page Corbyn about him. And if we go to our task controller and what I'm going to do just to make things a bit clearer, I'm just gonna fall these up. So this was the one that handled the get individual task and this was a bit of functionality here that returned, all completed or incomplete, and this was the one that returned all of the tasks. And then there was a catch, all of the bottom. If it wasn't any of them, it's going to minimize that. So we're gonna do here's handle the 20 per page so the u R L will look like So it's tasks slash page slash and then the page number so that we page one page, too. Page three, etcetera. Now that's obviously the prettified U R l on what will be using is task dot PHP and that will be paid equals one or page equals to four page equals three, and that I will be mapping that in the HT access while so we need to look for is the page so a bit like what we're doing here. We look for the completed, but we're actually going to look for the page. So I'm just going to get rid of them, tidy that up a bit. And what we're going to do is create another LCF. Now, what I want to do is put it just before this empty get press enter there in just right. Health if and then we'll just copy that. Pierce that in there and then change this two page. So this is our logic here. So now it's, um we're gonna be handled in the page here. The first thing we need to do is handle the server request method on the page. If we using the slash page slash warn, we only want to be able to use get requests. So we need a handle if any other request method was used. Justus output. I was standard every response. So if we do the if statements or was if and then it was server, and then it was request, hopes method, and it was equal to kit. This is where we're gonna be working in. So what we need to do is handle the else Onda, We need output. I was standard response will just create the response The response hopes response and then we want Teoh response. Set http. Steer discord. And remember, this is a four or five error because we only wanna handle get requests on this route, so slash paid should only handle get requests. So this is a request. Methods not allowed. So we need to set the success hopes set success to false underneath out a message off. Request method not allowed. Send it. You need an exit. Okay, so let's our handling of the Everly. Okay. I saw moving on. I'll just create some space here so we'll see what we're doing. So within the gets, we need to get the page number, so page equals get pitch. So obviously this is passed in on the task dot PHP slash page. So we're getting this number being passed in here. The value get out of that and I want you to do is check to see if the past in value is he valid value four page. So that would be something like, make sure it's not blank. So make sure it has a value, but also make sure it's numeric. And if it's not, if it's neither of them, we need to send a standard response back. So I need to check if the page, um, is blank. Or and if it's notion, America. Andi, if it is an error off, it is nonviolent value. We need a set. A standard response or response equals you response and then response and will send. Um So when you set the http Stairs court and this is a 400 error because of past into wrong did all the clients passed into wrong data? The mere prevented something like page equals test or, you know, some text. That's not a valid pH. Number, so we need handle that response. Set success, false response had a message. And the message is, Page number cannot be blank on and must be America. And then we need Teoh send on exit. Okay, so that that is checking to make sure that the past in ph value is valid. And if it is, we'll move on to em the rest of the logic. So we need to decide how many per peered will want to send back. So our requirements said 20 per page, so we'll just set. This is a solid value here. It's or limit Per page said that a 20 and I would need to perform some database queries. So with all database queries will do the try and catch on him. Catch 1st 1 of the PDO exception Kourtney X on. We will be handling tasks here, so we may as well build the place all before the task as well. Catch the task. Exception key. So what we need to do here is Bill. They were standard response. Are standing every responses back for these two exceptions means we'll get these other way now. So response equals new response response. Um, set each TDP stairs court and that is a 500 sever ever. We has some things went wrong. I said success. Okay, need Teoh at a message. Um, actually, here's a task acceptance or need to display the returned message. So x I get a message andi need to send takes it. Well, just utilize this one to save a bit time Pistor in here him to get rid of this message because we're gonna add one in which is him just field to get tasks That's a good catchall . And then because it's going to be a database sort of error here, we should log it in the error log. Um, dear dubious Queary era and then append the exception to that on Put it in the PHP era. Look, So we'll see if that que Seletto exceptions don't know if we go back to the try statement. So if you think about this, the first thing we need to do is work out. How many pages will will be returning now if we do a sequel, count on all of the tasks and then divide that by how maney per page that should give us the amount of pages that need to display. So if we try and get this value to begin with So Queary, um, equals and this will be will be used in the redid appears connection for this because we are just queer. Indeed, back. We're not writing at this point, so we'll just use the three db and then it is prepare and there were use our sick will put our secret Stephen in here so select and they would do count how many ideas they are on will give it a nearly ISS total nor off tasks told number of tasks from tbl tasks. So that should return. The count of how many tasks is isn't it is in our table. Just execute that hopes Cleary, execute. We need to fetch obviously this value back. So if we just get this rock, the 20 a single rocks that account query So we just see a raw and then it is Queary. Fetch. Then it is PDO pidio and fetch associate of a rear. Okay, so now that we've golfs the roar, we need to get the value and mobile deals will just make sure that it is an indigent that's being returned. So we'll call this task discount. Yes, that should be fine. And then what will do Will cast It has an interval to make sure it's in India jet And then what we'll do is we'll get rule and then office either feel that returning his total number of tusks not in their tall number of tasks. So that should have signed side or north sea. There's five tasks, so that should have signed five to the task county here. So now we need to work out how many pages is needed for this many tasks. So, like I say, we need to divide the two together. So we'll call this gnome off pages, and then we need to do tasks count, divide by the limit per page. So this will do here. You're presented with a decimal value if it doesn't divide into each other. Perfect. So what we want to do is always round it up. So if we retrieve and 20 per page and this 21 tasks, we should see the is two pages because there's more than 20 So we'll have one left over. So we need to see this two pages. So the decimal for that would be one point whatever. So we need to see that, too. So in order to do that, use a function called Seal, and what we do here is seal and then wrap that conciliation within the seal. So if it's anything greater than one, so you know, it could be 1.1. He would always comfort always round that up to sort of to now that's exactly what we want to do here. So the next thing we need to do is have a look at this and think about it now. If we look here the sequel query, we're counting how many tusks they are that's in the database now. You might have no tasks. Now. You can't divide something by zero because it equals zero now a minimum. We want one page displayed. You're probably thinking, Well, why should we display one page when there's no tasks to display on that page? Well, the reason is that if you do slash pages slash one, you should get returned a successful response, but with a sort of a blank task. Serie. So you're not getting an error message because it's not an error you just literally retrieve and nothing. So we need to display the fact that there's no tasks. So in order to do that, we need to say that this at least one page if the test come to zero saw if number of pages is equal to zero, then we'll set number of pages toe one. So it's a quick check there. So if this works out zero so zero divided by 20 0 they'll always be one page. So the next thing you do here is validate that the page that's requested is not like a random values or see. There's only two pages. If there's, you know, if someone sees well, retrieve Page five. We need to send a response back to see this page is not found so that we would do large is do an if statement, and then we'll be doing two checks here. First of all, the can be ever as a page zero. It's always paid one. So when you do that, check to make sure it's not paid zero. And the other thing we need to do is to make sure that the pitch the past in page is not greater than the total number of pages. So going back to our example before, if we pass in Peered five. But it's only page two. There's only two pages. Then we want to show on every message so that we would do that is so Page is greater than the number of pages, and we'll just build this response now. Um, new response hopes and then response. Set the entity API steer discord, and this is a four or four because you're requesting appeared that doesn't exist. The man will set Success said that false. And then we will send him a message and we'll just see a page not found, homes. And then we want to send. Then we want Exit Hopes Page. If the past 10 pages greater than number of pages, that's when we get this error message. Or what we need to do is if Pidge is equal to zero. So that handles our hair. Is there school down again? Now what? We need a workout. Is the offset so dependent on what page? Where on we only want to retrieve results from that roar number. So to give an example, Page one will retrieve all rose from raw warn to 20 and page two will retrieve 21 to 40. Do you need a workout, this offset. So call it offset. And what we're gonna do is do something called a territorial period. Basically a short hand. If statement, so I'll explain it as we sort of create this or with me to do page equals one. And then, um So all this is doing is this is if if the pages equal toe worn, then so the question, what means then? Zero. And this means else so else. And we need to work out here. So let's think about this. We need to do 20 times pidge minus born. So because this is a compound statement will wrap this in brackets on the brackets again, make sure get our order, right? Yeah, that looks fine. So if the P H is equal towards so the first page there must start with start at zero because of want zero and above. Otherwise, that's what that colon means. Otherwise, we need to work out with the pages. So Cirone, Page two, we need to do pitch so to minus warn is one. And they were needed times the offset. So what we can do here is instead of hard called Not in There we already hard core Did it appear so limit per page. It will pierce that in there. So that's 20 will just substrate that for 20. And that is page minus one. So if it's paid one, we don't have to worry about it. It started zero and calls off the 20. Otherwise, it goes what Page Ron's will say. We're on page two were cut work. We needs minus one there because if we do two times 20 that means it started 44 page two, which is wrong. That's actually pitched three. So we need a minus appeared. So page minus one. So page two minus one is one and will times out by 20 which gives us 20. So if you do this by three So page three minus one, that's too. Times 20 started 40. So that's how you work it off. Set out. The next one we need to do is actually use this to query the database and pull back them. Raws that relevant school down a bit, we'll create the query. Um, on where this is again against the reach database. 20 reading here so we'll do a prepare on will create the sequel Cleary like we did to get all tasks on one page. Basically. So for Dio select I d title description deadline her and completed from tbl tusks. First of all, I'm just going to format the dead again, just like we'll have to in our previous ones. So did for Mart. Put the mask in. So that was sent deep him forward slash percent month sent year and then it was percent our cool on percent cry as diddling remembered alias it. So just scroll right here cause I would finish the sequel Query. And now what we use here is the limit. Keyword on the first parameter that windy here is PG limit. Andi, next we use offset. Andi, we'll set the offset. So the limit is how many rules to retrieved from the database. That will be the page limit. So should be able to pass in 20 there. And then the offset is what role we start at now to begin. Recess will be raw Zero because we want rules. 12345 to 20 The next Warren obviously be 21 of over. So now that place hold them. And they if you just school back on bond buying the parameters. So Queary change around. So the 1st 1 was PG offset. Sorry, Peggy Lim. Just think about that there. And then we want to buying the number, the limit per page. And then this is type PDO her interject because it's a number care the next one we need to bind is Queary change. Haram. And that was offset on. We're finding the offset here Oops. On that again. Waas video. Haram. In person in numbers. Basically, kit. That's fine. So no need executed Queary execute. And now we need to get the raw counts. Organ office. He used this theater elsewhere. So just like we did last time Roll Count Queary Rule count. And then you need to create a blank task ary to store with tusks and enough retrieved. And then we need to do I will, while loop should iterated over each rule to create a task. So through equals Queary. And then it was fetch. That was PDO, Fitch associative Arria. And then we need to try and create a new tasks or task equals new task and then will pass in the columns retrieved by the sequel Query appear raw. Heidi Rule title rule description, hopes and then rule deadline Pro completed. Okay, so that's I D title description. Deadline completed. I detailed description. Deadline completed. Yeah, So that should attempt to create the rule off. Sorry. Create the task. So if that feels off so you could catch it here and then once it's created it, we need to add it to the task arrius or task hurry and we need to repent it. Task return task as a Really. So now we need to build up our return data that's gonna be sent back in the response or return data will just create a blank area to begin with, and then we'll start adding stuff into it. So return did a rule was returned, just like normal. And this will be the raw account. Then what we're gonna do is something a little bit different here. We're gonna do return return data, Aunt Total Rose. So we know how many roars is in total so you can work out. You know, if there's 20 pages, um, each with 20 per page, you know, there's gonna be that many rules. That's obviously a task. Come from the top of here when we did the cunt. So I got that care. So return data on. We're going to return the total amount of pages, um, told pages and this is number of pages. We were just reuse and all What? We worked out just above here anywhere. So we just returned in that you don't have to. Um, but why not? If we already got a dinner the next two piece of data are if it has a next page. So serum peered one but the can be page two. You know, we've got enough rules to go on the page to We want to set this to true or false in the same with previous page. If we're on page two, we need a set. Has previous page to true because he has appeared. One. This allows the client, you know, we can make use of that. So the North, if there's a next page or not, that they attempt to try. So return data. And this is, um, has next page, right? So this one's a little bit different because we need to use theater three operator that we did up here. I can find it instead of writing a big if statement, which you can do. But I find this week quite neat and tidy on one line. Well, actually do then here. So we'll just right above here, because we're going to use this to Saturday either true or false. So how will work this out is we need to work out whether the current pitch is less than the number of pages. So say this two page isn't all it. Where appeared warn we're less than that. So that would mean that it does have a next page. So do the So this is the if statement here. This is if it is, so we'll just wrap this in brackets just to make it a bit Tidier. You go, then we'll just move this and we'll just set this to true. And then we used to call on P a study in and sent it to false. I'll just explain what we've done here. If statements saw if the past in period. So if the current piers that way on is less than the total amount of pages, then we know that will have. So then what this is then set this to true. So it has the next page otherwise saw else said, has next page two false and we'll be doing a similar thing for the previous page as well. So we'll copy this just to see what time tasted here and then. What we need to do is if Page if the current page is greater than warn, then ha's previous pH changes here is true. Otherwise false. So it's a sin is if if we're on page two. So if it's greater than one, we know that we have a previous page. Obviously we can't get appeared to unless he has appeared one. So that's theologically for that. So now that we've got this data, when you add it to the return sorry, we need to add the task store. Forget them. They're important. So we turned deer there. Tasks equals the tusks career. It's not like the tasks. And then we need to send the response back. So this the successful response response that institute he steals court, this is 200 cause successful response. Said success. True response. Um, do you want to be able to catch this? Yes, we do, because it's a bit like getting all roars. We should be able to capture really sore We'll set that saw cash to true. And then when you set the data and that's our return did not build up here. Okay, we need to send, then exit. Okay, We'll just get out of this white spears and see of that. Okay. I hope all of you stared with us there because it has been a little bit different to the rest I was doing. I have introduced a new PHP concepts shorthand if statements. But you can look that up if you want to, and quite easy to use. It's quite neat and tidy as well. Okay, so we'll just review what we've done quickly. Before we tested out to make sure the page parameter exists, make sure it's get only if not, we're sure the A Ramesses down here about request method, not allowed kind of this white space as well. School back up. We get a page number. Store in a variable will make sure that the page is not blank and it is numeric. Otherwise, for a standard Harry response, was that the limit per page? Well, then try our dear to be his queries. So the 1st 1 is to retrieve how many rules there is in the table that will allow us to work out how many pages we need to retrieve that back. We'll get that value backers and interject were just custody is an energy just to make sure that it is a number that we could do a calculation on, we'll look at how many pages it's going to take to display all the results. So would do how Maney tusks the years tool divided by how maney per page. We use the seal to round up because it could be, you know, 1.2, but we want to split at least two pages with N C. Well, if there's no rules in the table, was still want to retrieve Peered one. We still want to be ableto browsed, appeared one. Even if it shows no results, that is good. So then we do a bit of a check here to have a look to make sure that we're not passen. Inst. For example, Page five. When there's only three Peters exist, we'll also stop appeal from person in Ph. Zero cause there's no Ph zero with them. Work out the offset. The offset allows you to start from a Ross off unpeeled one will be zero to 19 for example . And then, um, Page two would be 20 to 39 that sort of thing. So we work out the offset within, retrieve the tasks in hand with the given offsets, and they give us limit. Beach rule would try to create a task. Well, then add some new fields to the data that was sent back in the response, for example, Tool Rules and Tall pages has next page has previous pitch with another tasks into the tasks career to return In our response here, if there's a narrow them, will handle it in the task exceptional. The paid your exception. So what we need to do now is we'll see if that we need to quickly edit our HT access file to put the route in for the slash pages. So go tht access and we need to write our new rule underneath here. So you need to three cups, right rule, and then its tusks slash um, page slash on. We want to be able to put a number in. So it been like what we're doing here. We were hard. This slash tasks slashing in the task I d need to put a number in and use that number in the query string. So exactly what we did just above here, basically the same thing so nor denying it's gonna be a number, and it's got a content at least one number. And then that maps to controller tasked our PHP pH and then exactly what we did appear. We can use the value that's being passed in in the query string. So Paige and then we normally do one because it's the 1st 1 yet they will put the last flag there, so we'll see if that okay, so we'll open a postman and then we'll trying to Barroso http. Call on slash slash local Horst reported it slash b one slash tusks No for just run this, he can see this five tusks. So now for do slash, page, slash warn So you still see that this five tasks because we're allowed 20 per pidge. But you see that we've got two more metadata here, so it doesn't have a next page, and there is no previous page because we're on page one. You say there's only one page and this five rules and this is how many rules was returned on the page, and then you have the list of tasks, so we try page two. You can see they were going to 44 ERA, which is correct. Success is false. Page not found because he is no pH to there's not enough rules to generate a Page two go out a page warn Appeared two year old will get that every message for what appeared one. I'm just going out to new rules into our database. Just just, you know, just to take your over the one pidge that we've got now. So bear with us how fast forward through this bit because we just had any new rules. You do this in your own time. Case of out of them. New rules Paige wants over. Just get that. You can see that there's taught roars. Is 37 swords 37 rules now? So should get his two pages so told pages to. So now, for pros to second pitch, we'll get 17 which is what's left over. And you say I just created some test data here. Should Robert Really, it is all the same just to speed it up. We can say there that the pages is now working, so it has previous page because we're on page two but doesn't have a next page because we're on page two, and basically that's the 12 pages. Go about a page one has next page. True has previous page false to know that have done that. The next part is actually creating the task. So we're going to that in the next video 18. POST - Create a Task: in this video will be implemented in the routes that will allow us to create a task using the data that we pass in viajes on request body. So let's open a bottom and you can see here that this is the route that we implemented on the previous video to get results on a per page basis. We're just gonna close that up for the moment because we're not going to use that one. And we're gonna go to the one that handles way. We're doing passing anything. So it's just slash tasks. So for expand that and you can see this was the route here to get all tasks. Now, if you remember, I just minimize that we created a placeholder for the post, which is used to do a create. So this is where we're gonna be spend our time in this lesson. The first thing I'm going to do is create some spierce, just organ. See where we are on day, we will be creating obviously a task using the past India, but also will be querian and insert it into the database. So the first thing we need to do is to set up our try and catch, just like in previous lessons. So try Andi catch and the same that would did in the previous lessons. Task exception. Hey, X on and P to your exception, the X So we'll just fill these in on bees Obviously need. The handle is standard every response, so we'll just call these in here now. I just said if I was standard every response here, So we need to set the http status cord. It will be 400 because the task has some incorrect theory in or concrete the task correctly set success false. And then we'll add a message that will pass in the exception message and then we will send takes it. So that's the 1st 1 on. We'll just copy this for the PDO exception. That one is a 500 every law on. We'll pass in an actual error message. Get rid of that. Um and this will be catching the insertion of a task in the database. Obviously we use and post which is used to create so will decide in and every message here feel too in search task into did base chick submitted theater for Harris. There we go And then, obviously, because it's a database error, we want to look that for our sister administrators. So use the era log and we'll pass in. Did the suit Queary there, uh, penned the exception? Um, and then zero for our PHP error. Look, care that looks fine. So we'll just see if that and then we'll go back up to the tryst statement because this is where we're going to be implemented. A lot of the court here. Now, this requests a little bit different to the ones that we've been handling previously. This will have a request body, which is some data that we need to handle. Now, this theater is in Jason format s so it looks something like, just bear with us, and I'll just drafted out here. Um, I don't know, maybe something like title and then my title here. And that will be something like him. Description with my desk. Yeah. So you see there this bit here. This is Jason on this is thief or mother will be using to pass in our details. So when we want to create a task, the title is this value here that we insert and the description is this value here are we insert. Now we see these all those other fields that belonged to a task. But just for demonstration purposes, you can see here that this is the fore much that we'll be reading from. So this is valid. Jesus on. So we need to check that the past India is of type GS on. So the way you do that, you send a request, Had an http request header for content type that is of type application slash Jason. So we need to make sure that it is that type that we've passed in. Now, I'm just gonna get rid of that because that's not valid. Cord for PHP That's GS on cords. Or that was just a dem or what I'm gonna be doing here. So we need to do a check to make sure that the content type request header is set to application. Jason. And if it isn't, we need to send a standard every response back to the client and exit. So we'll just do that here now. So if and then we use the server global area and then it's for content, underscore type, and then what? We need to do is see if it's not equal to applications last GS on, then send in every response, so we'll just create our response now. New response response set. Http Status court And this is a 400 error, which means the by request because obviously we haven't submitted the right type of content from the client point of view and then response said success. And then we'll see false response well at a message, and we'll just see that content type Cheddar is not set to Jason. And then where will hopes response? We'll send that and then exit. So that's our first check we've done there is to make sure the content type which is sent in the request, header his application. Jason, and I'll show you where we do that in postmodern when the testes. How later? So now we need to get this deal that's passed in in the request body, and we do that is to use PHP input. Now I'll just quickly show you this year. So for just call this raw paused data Onda, we will be m file. I'll explain this in a second Halkett contents, and then it's PHP him input. So what we're doing here is ignore this variable. At the moment, we used the file, get content, which should read. So say we doing with the file reads the contents of the file and stores it in a variable. But what we're doing here, instead of passing in a file path, we pass in this sort of input from PHP. Now, what this does is allows you to have a look or inspect the body of the request that sent. So we're going to be putting Jason Chord in the body now. What we want to do is just pull in that in its rawest form, hence the name of the variable I have created. And then we're going to try and Dick or that as Jason using a PHP function. So this page pay import will pull in the request body. So the request did that you've sent not the headers, just the body of it, and then was stored in that. And then what we're going to do is just to make sure that that it is valid, Jason. Now, the way that you do that is an if statement And you, we used the genius on D chord Look, de cord If you remember, we used the Jason in court when we took an Arria converted to GS on. Now this does something very similar, but does it the opposite way. So it takes GS on and converted into an object that we can use the details from So Jason Discord and will pass in this variable here because that's what we're trying to record raw posed theater. Um, but this function here, if it isn't valid GS on that you passed in, will return false. So we need to check to make sure that it's not false on benefits. Not we need to store that in a variable so we can use the Js on data in the genus on format . So we'll create a variable here called Jasan data and will assign that. But we need to make sure that it's not false. So we just put the exclamation mark there to do our check because it if it is false, we need to send back in error response. If it's not false, which means that it is valid Jesus on and has Dick or did it successfully will then move on to the rest of the core that will call implement. So I'm just gonna copy this up here is a basis and then paste it in there. It just saves us a little bit time. So what we're gonna do here is just change. It's still a 400 error because it is a client area. You haven't sent the right type of dealer to the server and we're just going to change the message here, too. Request body is not valid, Jasan. So we'll send that an exit. Okay, now that we've got our data in the genus on variable, we can use that to check the data to you to use the theater. And the first check we're going to do is to make sure that the client has provided the mandatory field. Now, remember, four task to be created. The two minded Rayfield are a title on the completed status. It's not too bothered about a description or a deadline, but it must have a title in a completed status. So the school down a bit make some space yet on we need to do in if statement. So if on we're checking to make sure that these are provided. But if the not we're going to send a standard every response back here so we'll do if on the way that would do it is used the object the Jason Theater object on. We can access them by using this. Now you're probably thinking, how does this work saw this here Title is what you call the element in the J. Sohn deal that you passing. So if I just quickly explained, I'll just write that dress on out again. So title and then my title here. Oops. So that they title maps to this here. So this is the element name or the key, And then we can use that just by colon. Jason did object, and the title is a bit like a PHP object. And you just calling the, um Thean instance the instance variable. So we can use this to check whether it exists or not. I'm just gonna get rid this again just to clear it up because that's enough. All appear to be cord. So we want to do is check to see if this exists in the way like you do that is used. The is set function. So is set hopes, and then I'll just rocked the end bracket round there. So is such Jason did a title. So if it exists in the past in Jason, then obviously we can carry on with that foot, just like the way that have courted everything else. But if it doesn't exist, so then if we put in an exclamation mark, if it doesn't exist, then we will put our error response here. But I also need a double check to make sure that the completed status is in there. So it's very similar to this. So we'll do, Ah, in all because these have to exist and then we'll do. The same sort is set, and then it's Jasan data on to complete it. So now that we've got that, that's the two checks that we needed to revive. A mind if you data I need 100 year response now. Soul just quickly created response. New response, and we're going to do something slightly different with this one. Then I'll explain when we get there. Um, and we'll just set the HDP status. Court hopes 400 Eric, because its client plan will set success false. And then we're going to add some messages now on the response. Obviously, we can add multiple messages, and that's what we're going to do here. We're gonna add a message to see the titles missing. If it is only if it is missing. Andi, if the completed status completed is also missing. So that's two separate messages we're gonna add only if one or the other is missing. So the way we'll do that is to use eternally operator again. That's your seen in a previous lesson. So it's like a one liner if statement, so we'll just quickly set off the message. So response. Odd message on. We'll see. It will do this one for the title. So title field is mandatory and most be provided. Okay, so that's the message there. Now, what we want to do is use this check here to see if it is there. If it is, then we don't send this. But if it isn't, then we do. So we need to do the check of the begins or is set. And then it was Jason did. Ah, title. I remember. The tannery operator is question mark, which means then So we're saying if it doesn't exist. Remember the exclamation mark. If it doesn't exist, then art. This message otherwise just returned False. Now I love one. Do anything. It just means that it won't. It won't run this function Here is the way we just returned and false. So if we wrap that in brackets and pretty soon we call on at the end. So we're basically saying if title doesn't exist then at this message to the response otherwise false Now if a copy that to see if this typing it out again would do the same for completed and changed the type that changed the message and we'll see completed field is mandatory and must be provided. So if the titles missing, then we'll adds this message. If the completed is missing, then it adds this message. Now, if the both missing, it will add both of the messages, which is good because we want to see what missing it'll. I was declined to see that. So then after about it, the messages we need to send the response send troops on, then him exit. Okay, so now that we've handled the mandatory fields, make sure that there exist the next thing we need to do is to try and create a task from all of the other past India, so hopefully that we should be able to. We've done the basic checks here, so it should be able to create a task. Obviously, we are within the try eso if it does feel to create a task for any reason. I were every response here for the task. He'll be able to handle that. So if we do, it would create a new task. We call this new Tusk and then we'll just try and create in your task and passing the data . So what we need to do here is remember, the first parameter for task is the task I d. That is provided by the system. So we need to provide no here because we're not deciding that. So, no, and then the next one is the title. Now go back up slightly. You see here how we get the title is to use this format here. So that's what that's what we'll be doing here. So, Jason Data and then title. Now we're not doing any validation on the title. Apart from making sure that it's the before we're trying created because monetary. But remember, the task does its own validation on the 4 march the criteria, You know, that sort of thing. Make sure it's not more than 205 characters, that sort of thing. Now, if if part of this validation wants to feel this task exception here would catch that the next bit was the description. Now, because the description is optional, we need to provide obviously some data here. And that data would just be no, which is been like what we did for the task i d. Now, if it exists, we need to put the data in. But if it doesn't exist, we need to put no. So this sounds like a good scenario to use this. Turn the operator again. So that's what we'll be doing. So if it's set jasan data, what I'm gonna do, I'm just gonna make some space here. Just want to see what I'm doing. So if it's set, Jason did. And, um, what was it? It was description Was Nestle description then? Well, I didn't Js on data description because we want to use it. Um, otherwise, no, If description is set like I say we're not doing any validation here. We're not saying Well, you know, it must contain 12 characters. You know, nothing like that, because the task exception will handle all of that. So if it if description is set, then pass in the description the past in description here is this is 1/3 parameter for the new task. Otherwise, it's no. So that should be that one. The next one we need to do waas title description. It was deadline. So we're going to do very similar here again. So I'm just gonna copy this and pierce that here and just show you this or the next. Um, but it did. It was deadline. We're going to see if deadline exists then James this then use the deer that's passed in for deadline. Otherwise, no school writes like, there you go on the last thing we know this is provided because it is a mantra field here that we checked. So be like what? David title weaken. Just type this in here. Saw Jasan did, uh, completed. So not do any checks on that because we were already done them. It's just a bullet. So this should create a new task from the past in data. So now what we need to do we need to get these values back out, install them in variables ready to insert in rodeo. Dubious. Now, the reason that would do you know that would do this And don't use the variables on the data directly from the Js on data is because I would task performs a validation. So we try and create a task. And then if it succeeds, then greet Then all we do is use this new task and pull the data back out. So we'll just quickly create some variables title and we'll just see hopes. New task get title and the next one waas description. New Tusk catch description. Make sure I spell them right description description. Yet next one was deadline. And that was new. Task him yet. Get deadline on. The last one was completed. Hopes on it was new task. Okay, Completed. Now that we've got the theater in the variables were no need to create our query to insert this data into the tasks table. Now, bit like what we've done before. Um, Quick Queary, um, this one's obviously going to be against the right database because we're put in debt or in Esso needs to go against the master Day be You don't have to obviously design that this way , but I think it's a good It's a good sort of architectural way of designing the application so it can scale in the future if need be. So right, Steve, Be me to prepare. And then we will write our insert statement into here. So in search into tbl tusks three columns which is titled Description Popes Description Deadline, um, completed and then for use. And that is, um, title. Some soup on place was in here description. Um, it's deadline next, but need a format that sore s to your two digit soft away passing in a string in a former that we decide, which is didi slash month, month slash y y y y and then space our call on minute. So obviously we need to tell the database what sort of format to expect so that all we're doing here is we're using strengthened it, and then there was doing deadline hoops and then we're using the format mask now. Obviously, we're using single court within this strength. Will need to escape from here. So the we'll let you escape them is by backslash Onda single court. So I'll just put another one for the end and then we'll put them here. Saw it was percentage de forward slash percent m um, forward slash percent fly spierce percentage each cool on percentage high. So that is the former de Monte er our minute Salalah off course, This function here. Um well, just what with the next one completed saw completed was the next bit of data were important in Yep, that looks fine. So that's I was sequel. Query there for the insert statements who are trying to put obviously the deal that was passed in into TBL tasks. Title description, deadline and completed title description off. Seen former deadline into a property. It escape. Obviously mask here on Dhere, the end, and then we passing the completed. So now what would do is to bind these parameters. Eso remember Queary, um, find Haram on the 1st 1 waas, um title. And then that was the title up here, remember, because we're getting the title description deadline from the task object that we've created with the dealer That was passed in on. This is a type PDO promised. Er, because the string I'm just gonna copy appears thes so got title description deadline and completed. We'll just meet the changes here. Description. Um, description here. Deadline. Not here, then completed. Completed. Okay, now that we're buying the parameters just creates a spear school downswing. See where we are. You need to execute the query Saw Queary execute, so that should insert it. Now, what we're gonna do now is just to make sure that has inserted this, we're going to get a raw count. If we call, the rule can function. That should return how Maney Roars was affected. Now, obviously, Roni, uncertain one rule. So it should be just one. So, obviously, then we need to perform a check to make sure that it's not zero. And if it is zero, then through our standards response foreign ever out. So we'll get that, um, here, your couch equals Queary Rule count. And then what we need to do is to do a check on that. So if raw account, um, is equal to zero, which means that it has field. So we needed a set. I was standard every response here. So response, new response hopes, response. And then we'll set the incredibly steered US court. And we'll do here to 500 error because it's a It's a server issue. If it hasn't been able to and said the ruling of the database for, you know, for some reason, um and they will set the success two fools and then a lot of message off feel to create, um, Tusk. We'll send an exit. Okay, so let's handle the error. So if I scroll down, creating more spears and school down again now we're past the era. Well, now want to If it has created the rule, all the task in any API I What you should do is when you create something, you should create it. And if it's successful, then use what you should do is also return that same data back. It allows clients to use the deer like you've submitted in a 4 march, that you you know, that's consistent with every Euler sort of get task call. So what we need to do is to do a fetch now from the database of the inserted Roland return that in a response so the way that we do that, we need to know what the last The last task I d was because we don't want to bring back all obviously task. We just want to bring back the one that we just created. Now the is a function. It's part of the pity or functions in PHP called lust Insert I d. Now you're probably thinking, Well, there's gonna be multiple people using this. Why doesn't return? You know if if to it rules get inserted a roughly the same time it might corrupt. As in, we may get someone else the task I d back. But it's only for this session. So it's guaranteed that we will only get the I D that we've inserted and not someone else's task I d. So we'll store that. So we'll call this last task I d on. We will get this from It's not the query this time. It is actually the database connection. So it was the right db and it was last insert I d. So that gets that I d back now. What we want to do is another database query, um, to select that task where the tusk I D is this? I d now obviously was done. Not when we got a single task. Um, you know, earlier on in the videos using task i d here. So it's just gonna be very similar to that. But the one big difference here is that will be calling the the retrieval on the right DB. Now, the reason why we do this is the sleeves or the re databases are here. Singleness. So it you know, by the time we have created this way immediately trying to return this from the database now, it may not have had time to populate or to push. This did this data to to the read slaves. So we must call this on the right day, be even though it is just a read statement. So if we what we do here is create the query on will read will do this on the right debate groups Might db aunt, that is prepare. It's and then hopes in court sort select I d title. Um, no description. And then remember, deadline. We need return in the Senate for months or did format on git waas deadline and then the format waas and percent d slash percent M percent, um, slash percent. Why? Couple? Why? Because we want to return the four digits. Not just to then our thin minute, and then we want alias. Side is deadline. And I also want to retain completed from tbl tasks Where, um I d is equal to the task. Um, task I d That should be fine. So all we're doing here is return and I d title description deadline and the completed status from the tasks table where the i d. Is that off the last inserted tasks, for example, the one that we have just created. Basically. So we go back now, obviously, we need to find the parameter So Queary Oops. Bind, Haram on it was task I D on it was the last task. I D um this is PDO Haram int because it's an imager. We need execute it. So it's Queary hopes execute. And then we obviously need to return the raw account. Make sure that the is a rule A for that task idea. Otherwise, we need to return and standard a response. So it's just handling all the errors. To be honest, that's what majority of this court is, it's it's handle in the errors. So we're back here on day and get the raw account on. That is Queary Roar, and then we need to do is check. So if rule count is equal to zero, as in can find it, then response equals new response. Set HDB. Steer this court 500 error because obviously there's something gone wrong on the service side here for it. If you can get the Congo the role, um set success cops response its success as false and then we'll have a message here. Have message. Just something beer sick. I feel too. Retrieve task after creation and then send and exit. Here's let handle that error creates more spears. So if it has been able to get the task back, then we need to get that rule and then send it in a success Responses time be like what we're doing with the single task. So it was quickly do that sort corpse whilst airman again. And then it was raw. Can you get that rule? So, Queary Fitch, um and then it was associate of a real was netiquette. That's what being using fetch. So, um, and then we need to stall the tusk. So we need a passing. These details here. Door for rule yet so raw. I d rule title hopes rule. Okay, look. Description. Okay. Headline on the last one. Rule completed. Yeah, that's fine. And then we need Teoh. Actually haven't created a task. Ary have Wes. We need to do that to be able to append it to that. So if we create a task ary Sorry about that. Just get a bit ahead of myself here, Tusk a re new hopes. Hurry. So I've created Blanked us Correa here, which is fine. So if they're not that they now we need a repentance or task a rare then append tusk. Yeah, that looks right. No, it isn't because we need to. We need to return the taskers in a really return task as every That's fine. Yeah, that looks right now. So not just returned the task. We need to return it as an A rear. So we've been used Jason in court to put it in a nice format. So we need to create a return dear to know, returned era, um, career. And then we need to groups, um, create the roars returned and that is broke out. Yeah. So this is just what we're doing in when retrieve tasks anyway. So I know you're probably thinking, Well, why you retrieve it again? Because it is part of rest API eyes. Every time you create something, you should also return it back to the client. So that's what we're doing here. So, um, return did Ah, on this is, um, tasks because we need to do of the task, Serie. And then we need to create the response to return all of this or new response. In response, set Egypt, he steered his court. Now this one is a tool one because we've created something here. So this is the successful response that was sending back, which includes the created task is part of the tasks. So because we've created one, we're now at the success point. Sort of. Two will want to see something has been created. So response set success, and that is true. And then we'll just have a message Well to see, task created, and then we need to set the theater. Don't forget to do that. That is important. And that's obviously our return. Did a really have created. Yeah, on that. We need to send and exit get to the white space. Okay, that we should be there now. So we'll just see if that, um that is quickly go back on the top and just a brief run through. So this 1st 1 was the if statement for the get which handles getting all tasks we handle in the post here, which is the creation. Now, this is in here because the route will be using is slash tasks and we'll be posting to that . We don't posed to tasks. Slash to which would be a task I d. Because we don't know any idea at this point. So you always posed to slash tasks we'll cover to that woven our try statement. So within that, we have the if statement to make sure the content type is applications Last gs on basically Jason data. If not, send every every response back with, Then get the body from the request to use in the file. Get contents. PHP input. We'll see if that in a variable called roar did rule poor stada. Well, then try and do is create or decode the Js on from this rule pours data. If it succeeds, then greet. However, if it doesn't, he'll return false. So we're checking for false here. If it's false, we send in every response. The next thing we do to make sure that our title mandatory title and completed status these are mandatory are included in the request. Otherwise, we'll send a response. Well, then talks, um, messages on every messages. I guess if the not, if it's if they are provided, would then try and create a new task using the data that's being passed in in the Js on request Body will then get that data out. And then we try and insert into a database. Once we've answered it, we then need to retrieve it because with every post request, if it's successful, it should also return the object that we've created. So then we try and get it back out. Based on the last task i D. Which is this one here, which is the last insert I d school down. And then what we do is, um, return as normal. The standard response for success, which is the envelope which has the state is called the Success flag in any messages, but also the data which includes the rules returned on the tusks themselves. So if we we contest this now, make sure Mom's running on open. Postman, Um, we will new request here. Don't forget with Post. And now we're creating something. And if we type in http local Horst idiot idiot and there was slash V one slash tusks. So we just try and send that Now we get an error back. Seeing the content type head is not set jasan. So that's good. That's a valid era and you can see that it's been a bad request. 400 error. So the way that you set the content type header is by going into the body, we're sending raw data and the type is application. Jason. So it's Jason Data. Now I've just clicked on that. What you've probably seen there is the headers now has worn. So click on that it automatically puts in the content dash type in its application. Jason, Now, that's what we're checking for. So if we send this now, we've got rid of that Arab or now it says the request body is not followed, Jason. Now that is also correct because in the body we don't have NJ sonnet all. We actually haven't specified energy. It's on. So what I'll do here is now create our GS on body. So Curly brace and obviously you're and curly Brace. Now here is where you supply the fields that you pass in in so a title new title for post test. So if I just send that now, if a scroll up, you can see there when I get a different error message. So the completed field is mind a tree and must be provided now, obviously title and completed a mandatory we've supplied title. However, if I quickly just change this to complete it and send this again and all that doesn't value makes nor sense for this this variable here. But I just send that it now sees the title field is mandatory and must be provided. So if I take them out completely on, send that it's still valid. Jesus on because we've got the curly breezes. That's the start and end off Jasan. But I would feel too now missing. Now you can see there would now have an array of messages, so title field is monetary and be provided in the complete of field is mandatory. Must be provided. So we will do this now. So title um, new title from post. Andi will give it a completed status off. No, remember completed. Must be Wiren end. So, actually, to test it, what I'm going to do is just type some theater in here, so we'll send that. So you see that the air is also wound because we've got task completed. Must be. Why are in So this is your client obviously indirect? Um, with server and we're getting some helpful error messages back here. So for saying no to that this should create a new task and return it back because we're provided the title and the completed status. So we'll send that you can see now we've got a 21 which is a creative sofa. Go over here. You can see created misters tax test created, but also have got some dear to here, which is roars returned warn, and then your task. So you see there it has a task idea of 39. It's got a title off the past in title that we've created up here. It didn't have a description because we've been supplied one. It didn't have a deadline because it didn't supply one. It does have a completed status of end, which is what we supplied up here. So now this task has been added to our task list. So if we, um, create a new request here and we're just type in local Horst sport number V one tasks and we're just gonna run to get on this and this should return all tasks in the date of this and if we scroll all the way down to the bottom, keep going. There you go. You can see our task is now listed in the get all tasks. So that has successfully created task for us. If I go back to the Post Request on if we just change us again, Teoh, Second test from post. But then we supply a description. Um, well, just see it. Description text here on will also supply your deadline because we're just going to make sure that it's all working. Remember, deadline is in a certain format. Sort was, um it was dear soldier. Say zero warn zero. Warn 2019 and we'll see five oclock in the afternoon. So if you create that now got back an error message that says the request body is not fella Jason, that is correct. Because I can see what I've done wrong. They haven't actually put a commonly so that's my mistake. All the fields must be separated by a comma, so it just shows that the test is actually valid in our error messages. So now that looks correct to me now. So send See, that's create a new task again, Has a task idea 40. So it's got it's now got a title of second test from Post. It has me description in there tells me deadline there. So the first of the 1st 2019 has completed status. So now if we go back to the get all tasks, we should have a new one. After this 39 of sand that scroll down. There you go. You can see our 40. So that's our task. They're being created. So now that would prove that that works. Just go back to Adam. What we'll do now is move on to updating inexistent task. Now this one has a lot of logic in it which is why I wanted to leave it toe last because some of the logic will be using in there we have used in here. So it will be getting the Jason Data will be deke ordinate and will be updated in it and then return and the updated task. Like I say, this this was the easier part here to explain. We've been through a lot of the similar functionality they'll be using in the up dear request. So now we'll move on to that. 19. PATCH - Update a Task: in this video, we're going to implement the patch method for updating the details of inexistent task. The details will be provided to the server in Jason for much in the request body. Very much like how we submitted a request to create a task in the previous video. Okay, so Lorton, Adam, and you can see here that this is our empty get, which is the slash tasks route. Now, in the previous video, we implemented the create the task and that was using the post. So I'm just going toe sort of shrink that down. Um, because we're going to be focusing on the slash tasks slash than a task number because we want to provide a task i d of the one that we're going to update. So it's back in this route here. Task i d. So we just expand that, You see, we've got I would get requests for not interested in that at the moments will fall that up . Delete also will fall that up. Andi, In one of the previous lessons, we created the shell for the patch. Now, this is the one that we're gonna be using in this video. So what I'm gonna do is just create some space here and just move it down so I can see where we're going now will create the try and catch statements to begin with toe try and then, um, catch The 1st 1 is a tusk exception the X on the next war on just like the previous videos Catch PD or exception he x and which is Phillies in whilst we're on. So the task exception that we need to create the response, your response, and then we want to, said the http Status Court. And this would be a 400 error. You want to set the success be false because of dealing with the errors. And then we want to add a message. And that would be the message that passed in from the air off from Korean. The task. So want the X, get a message and then we want to send it and then exit. So that's a task exception done. So I'm going to do is just copy and pierce this. So the task exception has a 400 http Status Court. What? This will have a 500 error because that's a server error for two PDO exception. Where's the task exception? If we've passed in some dealer, that is not followed for a task that it's a client issue. So instead of getting a message from the exception, will just provide a standard message in a string. So this is a day in the tasks or feel Teoh did task. Check your data for errors, for example, to go There a message there. We'll send that and exit that now with being a PDO exception. Well, look, this just like doing previously in the analog. Um, Pierce Queary. Kara. It will upend the exception onto that and then save it in the Ph. Pierre a log, See if that get out of this White spears tidied up a bit. Okay, so we're gonna be working, and within this try statement. Yes. I'm just gonna create some space. Okay, so think about this. We are sending a request in http request using the patch method books were wanting to update on existing task that in the database, so it might be to change the title or to add a description or something like that. So what we need to do first is to check the type of data that's being sent just to make sure that it's GS on dear. That was sending in the request body so very much similar to how we checked or did the initial checks on the creation of a task. Initially, we're just going to sort of run through them, see him checks for this, so I'll just create them here. So when you do an if statement, then it was the content type off thesis er vor global variable so content and score type on , and I need to check to make sure it is application slash GS on data. Yep, so that's checking. If it's not application GS on, then we're going to, um, send a error response out. So what I'm gonna do, just see a bit time copy MPs This one because it is very similar. So create the newer response to 400 error because three client hasn't sent the writer with data successes false. Andi, we're gonna send a message back Sore content type header not set to Jason kid. So it's the first check. Don't. The next thing we need to do is to get the content or the Js own dear that that's being passed in through the body. So we need to get the raw data rule patch dear this time and it was file. Get contents, remember? And we using the PHP input method so that you get the contents off the deal that's been passed in. See it in the variable Sorgen check. Do some checks on it. First check we need to do is to make sure that it is Jason dear, that's being passed in another way. Would do that. Will try and record it as Jason on def. If it can't dick or did as Jason, we get a false response back, so I need to check that. So I need to check. Um, And if we do get a response, will save it in this parable, as JSantana Jason did a girl's face on record on it was Role patch dinner hopes. So we're trying decoded Jason so that role patch data from appear which has been passed in through the body and you'll see when we tested at the end using postman, we sort of generate the GS on data for the for the data that we want to update on the task we'll see it in a variable. Andi, if this Kontic ordered is Jason they returned false. So we make sure that it is not false. So various false. We send a response error back. So I'll just copy this on its 400 yet because it's still a client issue. Success is false. Who will just change the error message that gets sent back? Request body is not valid, Jasan. Okay, so let's I was second check in place while the school is down slightly. So now we need to We need to keep track of which fields are being us to be updated. So what we'll do here is just create four variables that we can keep track of what is actually being updated. So the 1st 1 is title did it? It will just initially set all these two false and will set them to true where it is the kiss or title of deal of false description, updated articles, false. And then it was dead Lane off. Dada ji equals false. Just don't keep track of you know what? What is being updated? Completed? Dated corpse, Of course. False hopes. The table. Okay, so now we've got the fields that can potentially be updated for the task. Obviously, we're calling updated and I d So we're doing trying update that. But we can update a title, a description, a deadline and the completed status. So just keeping track of what has been updated. Okay, so what we're gonna do here is used the update statement, the sequel statement for update. But what we need to do is build this Queary dynamically, because when you want to update the field that's being provided and just leave the field that haven't been provided at the current values, it's what we need to do here is dynamically build the queary up, and as they go through this, you'll understand. So we just need to create an empty string at the moment. And then we're going to be a pendant. The query as we call. So if we create a query fields and we'll just create a blank, a blank string of the moment kiss or we need to check to see which fields of Bean passed in the genus on data. Then we need to update thes two. True, if it exists or the wiser just will be left false And then what would need to do is upend the dynamic sequel query to this string here. So it build it up as we go through each field. So we would do that is an if statement who need a check that it is set within the genus on data. Now we'll use the dick ordered GS on data here. And if you remember from our creation of tasks, we can just access it like a an object variable so we can use Jason Data and then we'll look for the title. Create that. They're just so you can see it so well. Firstly, seeing that try and access the title from the past in Jason Data. If it exists, so that is set. Then what will do is set the title updated to true. So keep check off what has been passed in tow. Idiot. But now what will also do is append to the query field, sore query fields, and then how we append is dot equals. So the doctor in equals keeps what's currently in there. So if they said test, it would currently keep test and then whatever we said after that. But the minute we just need to get rid of that. So, like I say, this is Sequel dear that way are a sequel. Stephen. That was sort of build no PS. So it's it's sequel that were Arden in here. So it will be title equals. And then because we using PDO we use in place all this. There's a lot of come together towards the end of this video as we go through these hem, but we're building up. What needs updating and using a sequel statement So I'm going to do is run through each of these fields and do exactly the same. So on the next one. So if is set and then just on data on then this time corpse it was description. It's not spell description, and then it would be description. Hope did it equals true and then it will be Queary fields dot equals And that would be description. Actually, I forgot something there that's just reminded us. So because we're building this of dynamically the sequel statements between each field that you want, Toby, it is usually of Kama. So in this what we're gonna do is title and then the value of title, which is a place holder of the moment. And they were just going to put a comma because ideally, I'll just explain it. Yes, What we'll do. Updated TBL tasks. Set title equals title description. Hopes descript shin um equals description. Con spell description. Um, I'll just do that for the time being put. Um, where I d equals task i d. So it's very much similar. What? We actually building up dynamically here. Saw where would do in the set. Is this piteous? We concede up it There is actually this bit here and description will be this bit here. So we'll need description and then description with a calmer after it. And then we'll build itself as work or just get rid of that. Just thought I would explain actually what we're doing here, so spells correctly description, goals, description. Don't forget the common and the spears. Um and then the next one would be the deadline saw If is set jeison did there deadline deadline off. Did urge equals true And then query fields Dr equals And it would be actually this one slightly different because we need to format the d it in this one toe born back, Teoh. The creation of a task will use the same sort of former. So first of all, it is deadline equals, because that's next equal part of it. And then the sequel, Stephen is String two did it. And then it was the placeholder. So that was deadline, and then it was a mask. So that would be percent hopes percent the slash percent m slash percent. Couple why? Space percent cartilage cool on percent I and then semicolon. Yeah, that looks right. So day, month, year. Our minute. Yeah, that's fine. So after that store, forget we need the comma and then a space. So that's deadline. So the last one is completed yet? So if is set, but yes, on dear, they're completed. Hopes toe completed. Update it equals true. Andi Queary fields dot equals and then it is completed. Equals completed. Comma. Spierce don't get a semi colon. Okay, so that should build our set. Part of for the query saw title description deadline off the deadline. Slightly different cause we're for Martin. It did because the story, as it did and then completed, is completed. Now, it could be a combination of these things because you might say, Well, I'm going to update the title, but I'm not going to update the description. I'm not going. Oh, dear. The deadline. But I'm going to update the completed status. So it would just be title and the completed status? No, in the sequel Query. Um, on the last value that you put in, Obviously you don't have the comma. It's just then obviously you're any conditions after that. So what we need to do is because we have the calmer on everyone. If we just look at the string, the query fields string and just remove the last comma, then that should allow us to have a valid query so that we ever do that is Queary Fields. And then we need to equals. And we're going to use the right trim here. So are trim. And then we puss in our initial query feels. And then what we want to do is remove the last comma and spears So and what we would have here is a body of tbl task set title calls title where task stops away. I d equals task I d. So if we didn't do this here, this is what the sequel, Stephen would bay. So we up there tbl tasks that title hopes tasks do not use now don't wire corrected that put So I've set title and then title equals the placeholder we can see here We've still got the common here. Now, at the moment, that is not a valid sequel statement. And what you could do is then have description. I would see again, we would still have the comma, which is not followed. So what we do is it doesn't matter which field is provided. We always strip off that last comma. So there you go. So now that would be a valid statement. So that's just an explanation of why we do in our trim and then trim off the last calmer on there. Let's get rid of that again. You don't need that. Okay, So, since little, natch, um, we need to check to make sure that has bean some dealer provided Otherwise we kind of did anything. Eso is a bit of a general check will just make sure that these are not all set to false, because if they're all set to false, then why haven't updated anything? So we need to sort of throw an every message out or standard every response out. So I just scrolled out, speaks and space again on We'll do an if statement because we're just going to do a check to run through these updated hopes, going a bit far updated variables just to make sure that there is one of them, at least true. So if, um, title updated, um, it's false, and then we'll do and description. Did it equals false? Andi? Um, Dead lane did it. People's false completed, updated equals false. So it was seeing if the titles false or the title updated. Sorry is false on the description of data it is false. Onto the deadlines of theater falls on the completed is updated equals false. Then why haven't provided anything? Because this checks to make sure that something has been provided and if it has, it, set it to true. So that's the check. Just a the end of that. We'll just do our if statement, um, so this is the era, so we need to create a response. So just copy this response to say it was a good time. So it's new response at a 400 error because we haven't provided any fields to update it. So it's a client issue and we'll just change the every year. So no task fields provided. I think that's good enough for that. So school down again. So now that we've got or, in theory, got invalid data, what we need to do is retrieve the existent task using the task I d. That's passed in by by a task slash see task i d seven. So we need to retrieve that task to then update it. So what we'll do is because what what we don't want to do is to just update the task without calling it back. Now mines fairly simple here because I call the task back. It's then stored in the task model that were created, which doesnt validation and things like that. But what you might want to do is every time a tasks of deal, it may be increments the the amount of times is being updated or something like that. Now, in order to know what that value is, you have to retrieve the task initially to then updated, so I don't necessarily have to do it in this case, but I think it's good practice to retrieve the task, have that as a task object in PHP and then call your setters and get is on that and that still provides the validation for the theater. So what we're gonna do here is create the database query to do that Onda Guess because we're or dead in here. We want to query this against the right db So the master db because the last thing we want is just, you know, pulled back an old version of a task and then updated that an overwrought and your old or any new dear to Russia etc. So we'll actually run this against the right db even auto just to read query at the moment . So queer e equals m. And then it was right d b. And then it was pre pair. So we'll just call that tusk back or retrieve that Ross or select i d title description. Um and then it was did for much and then it waas deadline, remember? Bring the back in a certain we're hopes on. Then it was percent percent. De sent him percent couple Why percent age cool on percent I and then release it as deadline and they were one of being black, completed from TVL tusks where I d equals and then we'll passing Obviously task i d Tusk i d. So that's a sequel, Queary, who have done this before to retrieve a single task actually passing a task i d. Let's go back and then we want to bind the promise. Or on a query bint Haram on it. Waas task i d. Because that's what we're being passed in groups on if you remember for school all the way back up because I haven't been this b B yet, but is part of the check for the route we get Task Idema story in a task clarity so we can make use of that here. It's a school back down. So if a do tusk i d. And then it is of Type e D or Haram into cousin interject to Now that God's that we can execute it, hopes execute. So in theory, if the past in task i d is valid, it should bring back a roar. So if that task idea doesn't exist, that would be rude to bring back. So that's why we need to check now, so you get a raw count, have broke count, equals Queary and then function rule count. And then we need to do a check on that role counter. Make sure it's not zero saw rule count. If it is zero, then we're going to return. He response and every response so we'll cover that one. Pierced it in there. I mean, you can take it out for written. This must amount of times now during this course, or it's the same sort of standard stuff here. So we're going. Teoh she and just for 44 Erica's four or four is not found, Remember? So technically, I guess it could be a client era butch. It makes more sense to return a four fire because the client probably beast doesn't really know how many or which task I ds our existence because some might have been deleted. So I think it makes perfect sense to to send back 44 not found error. So it's false. Um, and then we need to change this to see nor task found to date because we can't find the tasks that we can update it. That's the first check so scroll down to see where we go on. However, if he is a roar, then we will return that on stall that or try and create a new task model. Store the details in there so that we would do that is the wild statements. If you remember, and then we'll see if that raw in the raw variable and then Queary and use their fetch and then it is PDO and then it was fetch associate of a really. And then we'll try and create a new task here. So tusk Yep. Task. He was new course Tusk. And then we'll pass in the rules or rule full i D. And that was rule completed nose. And it was title description. Deadline completed. Case We've got that now So they should help create a task. Will pass in the values retrieved from the database saw the I. D. The title description, the deadline and the completed status. We'll see if that in Tusk No, what we want to do, I guess if it has, it has a bit trouble creating a task here. If it hasn't got any valid theater in now, you know, people mess about with the back end of the deer dubious. Rather than going through the front end of the FBI, as in internal people, they could have corrupted some deer. Awesome, like that's or potentially that task could feel. And you've got our task exception down here. Toe handle that. However, if everything's gone in by the FBI, it's it still has to go through the same validation. So in theory, it shouldn't. It shouldn't feel it should have field before the task got put in there. So hopefully that shouldn't feel. But if it does, we got the response there to handle that. So now what we need to do We've got the task we need to, um, creates the query that will be used to update that tusk in the database. So we're gonna build this of us. We go Well, um, create the query string, and then what we'll do, we'll bind the parameters for that update query from the values we get from this task. So we've got the task. That's the original data at this point. Well, then go through our Jason data. Um, from the values that's being updated will attempt to update this tusk object if successful , let's create. And then what we'll do is we'll then do our updated statement and buying the parameters from what was stored in the new task. So what we need to do first is create the query string for the update query string because we're going to dynamically build this on the query fields is obviously part of this whole query string. So query string, um, it's updates TPL tusks. And then what we want to do is set with spears. And then what we're gonna do is upend the query fields in the middle of that and then, um spierce way I d equals Tusk. I d Yeah, that looks fine. So create McCreary String were pending the fields in the middle of this, and then we're seeing where the i d. Is the task i d. So this started the updated statement. Well, then do here is prepare this. So, um and we'll do this against the right Deby because we're now dead and stuff. So it needs to be done against the master, um, tour the queary yet Gratifying, because that's a query string we're gonna process until the query equals right, DB, and then it's pre pair. And instead of putting the sequel, Steven and he had just broken down. So we're just gonna put this variable in here? We re string. So we've prepared at this point, and now what we're going to do is cycle through, scroll up. I was just going to cycle through these and where the true. We're just going to set the task so schooled out the tests were created here where it's true, What the top. We're going to set the value off the task variable. So it could be titled description, that sort of thing. And then what we're gonna do is retrieve that back out because we want to make sure that it has been successful on any task model. You might do some four Martin or something like that. We don't know we're doing in this one. And the only thing that we do some former non is the day it. But it depends on what you're doing. So it's good practice to use the task object to set something, and then you get it back from that before you then opened it the raw in the database, because then it could do validation and that sort of stuff, so you'll see. You'll see your big clear as we do with this year. So we need to check to see if the title is being upstate. It's or title updated equals true. So if it has, we need to update the tasks or task such title. And then we'll pass in this title from the GIs on data, remember, because that's that's how we're getting the values. So that GS on data and then if we just used the title, so try and set the title off the retrieve task so it could be over right here, that's fine. This data will be validated because we used in the set isn't get us from the task, so that's good. So there's a validation that can, obviously, through a task exception, which is then handled here. And don't forget, we've got a customary message to see what has gone wrong with the theater, so we're in good shape here. So said the title and then what we want to do is retrieve that title back out like a secret . You could have formatted it, or you could have done some processing internally. With that, you should never up deer. The deer, dubious directly with the soil of the deal of that's passed in should always do some checking on it. So what I'm gonna do here is just create new variable called Hope Basically updated title Just so weak intelligence tree in the title and the updated title We'll call task, get title. Like I say, I know this sound to be tough to sort of said it and then get it. But, you know, we might be doing some processing in there. So now what we've got is Thea update a title value. And now what we'll do is bind this to the to the query. So if we dio Queary and then it was bind Haram and then the parameter don't forget Waas title and then we're passing in. Not this title. Don't forget we're passing in the update The title The retrieved title So Hope Title So you're probably thinking, Well, where's this came from? But if we go up to our dynamically created query you see here the placeholder is title so the next one will be description and then obviously I were deadline but format in that first and then the completed status school back down. So that's the 1st 1 there. Now what we're gonna do is exactly the CME for the description, the deadline, the completed status. So if we just do the same hopes so description updated. If that's true, then him. We're still working on the same task. Yes, or task set description. And then we'll pass in Jesus on theater description. And then we'll get the update. Its description yet. So hope Description get description. That's fine. Yeah. And then what we'll do is buying the parameter sore Queary change, Haram on that waas description. And then it was the updated description. And then it was type She forgot to do that appear having a So I got to give it a tape. So the type was PDO and then from and it's a string PDO Haram. And it's a string. Yeah, just old check So past that in done that Yet? The updated description. Okay, So next once or if, um, did lane dated equals true, then Tusk Sit deadline. It was Jason Data Death Lane. And then I did it that lane equals task. Get deadline and then query find Haram on dit waas hopes did Lane more passed in your d Adige deadline? That is that a string as well? Even though it's a d it we're passing it has a string pidio program String OK, school down a bit. The last one is completed status. So if completed off dead equals true, it was one to us against or set completed. Just make sure not mean any table was here. Really? And said completed. I m just so did, uh, complete it him completed on. Then it was task get completed and then bind that to the query. Find perm completed and then it was Your deal is completed. Pidio perama strength. Okay, so we're building up the query as we go here. So got all of the dealer there. The last thing we need to do here, Yep. Is to school Back up is to buying the tusk. I d. Because we haven't done that yet. We've put the placeholder in there. Um, here. Well, haven't found that parameter yet, So the real would do that. Obviously done this excited the CMAs just up here buying prom. So, Cleary. But this this task idea is not based on any of the other fields. So this is why that would do it outside of these, if statements so find program task I D on. That was task i d. And that was PDO Haram Until in a Jackson number. Okay, so now we need trying executed. So Queary and then execute. Give it a space there, so we'll bind the task. I d We're trying to execute the query, and then we, um, see if it has successfully updated the raw and the way that would do that because we're running a a no update sequel statement. The raw account should be the amount of rules that being affected by this statement. But because we're person in a unique task idea, it should be one. And if it's not one, then there's been an error. So we need obviously handle that saw. Get the rule count. Queary grew account, and then we need to do the check on that sort. If rule count is zero took out and never response. So I'm just gonna copy this peace that in there success is false. And then Wilder's passing in an error message. Um, task not updated. Um, nothing that Sanofi a task not updated. Okay, so at this point, the task should have now being updated in the database. If everything went right. No, what we could do is just return the the task object. So this object here that we've done our amendments on Soave updated them and things like that. It's not really that good to do that, because we might see, Well, we've changed that to, you know, a value. But actually, the value in the data base is still an old value. We always want to return the value from the database. Now it shouldn't be, but it's just to make things consistent. So what we need to do now that we've updated about rule in the dead appears we need to re retrieve that rule. So, going back to the top, we got that rule out of the database initially to school down. So we got that out there Initially, we'll see if that is a task object. Well, then don't know, update to that task object, and then we have updated. That's back into the database. So we want to do now is to re retrieve that lane or that rule out of the database to make sure that we've got all the right values on return that to the client Now. Every time you update an object, you should always return the updated object back to the client. So they know that the details are right And they have got the latest version off that rule . Basically, all that all that object. So because we've just updated it and because this is all running, you know, sequentially after each other, we should retrieve this based on the right db, we need the master DB because if we're trying queried against the reedy bees, it may not have populated or, you know, pushed out to them yet. So because we've up there, that something we need to retrieve the updated one from the right Master Davy. So just like previously on will create a new query which will just bring back the rule from the from the database. So we'll prepare that, and it was select i d title description deadline completed. Don't forget that Lane. We need to format. That sore was did hopes did format, and then it was deadline for by the mosque. So I was percent the percent I m I said, Why and then it was percent h cool on percent. I No need alias eyes deadline Never go back to hear Completed, um from tbl tasks swaps Ballarat where I d equals on task. I d don't forget that. Okay, so now what we need to do is buying the task. I d parameters. So Queary buying to Karam, and it was called Task I d on the variable was called Tusk i d. And it was type, um PDO Haram. And then we just need executed that queary cold. And then it was so this retrieving the new rule or the updated wash would say from the database, hopefully check a rule count, because all should be one role here because just updated it. Um so rule count, We'll be the rule coach. Yeah, Hope spelled that wrong there. Okay. And then we'll do with check to make sure the role count is not to your guests. Roll cart. So if it is the year old, then, um Well, let's copy that on And 244 error because the rule doesn't exist. Um, and were returned nor task found after I opened it. Now in Syria, we shouldn't never get to this point. Bush. It's good. Put the check in there on, then just give a bit information about what's gone wrong or which which steer Just gone. Run school down. So hopefully we should have a raw account of warned. Now, um, on we need to create the tasks. Arria, um task every to store this into, then returned back to the client blank career. And then we'll do our while coops while and then rule equals. And it Woz, Cleary Fitch. And then it was, was a PDO fetch associate of a Really? Yeah, that's fine. And then we need to create a new task. Doremus or Tusk you Teske! Then pass in the rule and values for rule have a description completed. So I've got the task. That's fine. So then we'll add this task to the tasks area, so we're going to return it. So task three and then append and then Tusk. No, that's wrong, because we need to return task as a really Yeah. Don't forget to do without that's important. So for a while yet, and and then we just need to send the response back to the client so we'll build the return date up like was done in previous lessons. So return did a, um creating a rear for that? That's what it is and then returned here there who's tinge that was rule count and then return data. And then it was tusks. And then this is the tusks. Also, the task ary tusks Yeah, to find and then we'll create our scroll down will create our success. Responsible response equals new response. Then its response said it should be Stairs court and at this point, it to 200 because we have successfully dear to the task. So it's an OK on Bennett ISS Response said Success. It's true, which is good, would all right many of these ones with due mainly era check and but hate them and then response. And then we'll add a message and we'll just say I am task did it homes. That's fine. And then we need at the dlrs or gloves he will need to return. The newly hope did at rule. What task I should say. Last theater, I did a story and then that iss the return data and then we'll send it then exit, he told us. Get rid of this white space to see if that so. Hopefully we'll test this in a second. Um, like I say, this was pretty complicated. This one. It's something out of the ordinary because we're retrieving what did and Andi retrieving again from the database. So there's a There's a lot more cordoned logic in this, this one. Really. Um, but hopefully as we build it up, you can see that we've done the checks and we've set the values where needed and created the dynamic updates Sequel for the fields. I am so hopefully. And when we test this now, it should work. So for a mixture of mumps Ronan phenomenal postman and what I'm going to do to begin with, I'm just gonna make this bigger. I'm going to run a get request for Tusk. I d warn the thing with local on the date of this http local host 48 it it version one slash um tasks slash one now to get request. So it should hopes I've got a syntax error, so we'll just go on double check that. So that is online 161 So we'll go back to our Adam Well, school upto line 161 I probably forgot a semi call on or something like that. Query fields yet? Semi Colon. There you go. And you? I forgot that. So see if that on go back to postmen, hopefully send Well, we've got another era. Um, lying 246 Let's quickly diagnose that called out to 46 So that's over here. Um, double check here. Yes. I haven't put the sequel step and in a single court. Or forgive me for that and then single quarter the end. See if that Yes, because the sequel query should be in court. Look here. Hopefully this time. So send that. Okay, so we haven't got a task. I d of one so try to write so I can see that we do have a task idea of too. So we'll try and update this one. So currently, the title see, is Tusk to and description too, and completed of North will change this to a new task to new description to and will change a completed toe. Why? So I'm just gonna create a new request here because I want to go back to this one shortly. We're going to create a patch request, remember, Because we're doing an update. So we're going to do here is local Horst port version one task slash too, because its task to that will want up there. So now that we've got that we need to go to our body because we need to provide the fields I will want to look did. Now if I just submit this, you can see there that I will contact type had a has not been said to Jesus on. Okay, so that bit of the logics working so change are too raw and we change that to type of Jesus on being see that it's then created our header off content type application. Jason. So now if I rerun this, you can see now we'll get a different era message. Request Body is not followed. Jesus on because we're having provided any so that ever disappeared for the content type for the header. 20. Mid Course Review - What we have done so far: I just wanted to take a minute to review what we have carried out so far. We've created near P I that can create a task or deer the task. Delete a task, return a single task, return all tasks and return all tasks with 20 tasks per page. This FBI can now be used in a live environment, but the moment there's no authentication, so anyone can see or modify any tusk in the next set of videos will be adjusting the system to make it specific to a user, so we'll only list tasks associated with that user, and only that user can modify their own tasks. There's a little bit of theory first, but we'll get into re factor in our record to take advantage of the user system. The reason why I didn't build the user system at the same time is developing the FBI was to simplify the build and teach you the basics of rest API I designed before communicating that with the user authentication system in the real world, you would maybe build the authentication system first and then build your FBI endpoints, which encompasses the requirements of the user authentication within this However, like I said, I separated. This just so wasn't too many new technical concepts to learn it once we focused on the FBI development, and they're now as an addition will now focus on the user authentication development. This also includes Integrion. It toe what we have already built in the previous videos. 21. Introduction to Token Based Authentication: we're going to run through some theory in this video in relation to talking based authentication. Normal basic. All syndication is based on the user name and password. Be incented with every request because it's a send with every request, there is a high risk that the password could be exposed because he http requests a stainless and therefore rest API eyes also steer lis. We need a weird toe. Allow users to send something to the server with every request that is not a secret as a password, and this obviously will only have a limited lifetime. This is where an access talking comes in, and over the next few lessons we will re factor in our Air p I that we have created to handle talking based authentication. This will include being able to create new users, log in, log out each task or belonged to user so forgiven user they will only be able to view updated, delete and create tasks that belong to them. So what is talking based authentication? The talking is like a password with a limited lifespan when he used raw standard kids with the use new and password that you're given to talk ins, an access token and refresh talking an access token. Has this really short lifespan Hugely Minute or I was. And a refresh talking is valid for a lot longer, usually weeks or months, both talking to usually just a random set of beer, 64 quarter currents. For example. This random 64 recorded string is sent in the http header. This is used as a password to authenticate you for every request. But when an access talking expires, you will then use the refresh talking to get a new access talking. This also comes along with a new refresh talking as well. So the reason why the refresh talking has a longer lifespan because once it's sent to the client, it is not then re sent on every request and response. It is only ever re sent to get a new access talking, so it is less likely to be leaked or exposed to a potential hacker. We also have to take and recount sessions. We use session so that we can use a system from Moldova devices at the same time. If you have ever used Facebook or another social network and service, you will know that you could be logged in on both your computer as well as your smartphone at any one time. If we didn't have sessions, then if you move from using Facebook on your computer to then your mobile phone, you would ask you to log in again. And this would love you out of Facebook on the computer. This would not be good from a user experience perspective and also can increase the likelihood of a password being exposed. I should be sending the password every time you switch devices. Now what we're gonna do is go through the floor of how talking based authentication will work in our your P I. This will give you a good idea. Hold implemented in your puppy eyes. So this is the floor diagram here. Now you can see the client is here. The authentication epi eyes here because it's not part of our resource here. P i The resource FBI is basically the a p I to get the tasks and talk to your tasks. Your dedication, your P I is what will be using to submit log in requests and user requests. It's all have it on controller. So I think it's a down this left hand side. These are the user actions. So log in, get a task refresher talking, get a task and log out. So the way that will be using the authentication e p. I. Is to send a request to post sessions so posted, remember, is used to create. So want to create a session so slash sessions and we'll be sending a user name in a password in the request body off the http request. So it's just Jason formats or user name. That's a user name user. 123 password And that's a password. So we'll send that the authentication FBI, the authentication MP. I'll do the check if it is an error, which is what the red dots are here. He's a sort of error clauses. So if he isn't era, you'll get an http state is called a four or one or unauthorized back to the client. Then you'll get narrow message. User name or password is incorrect, however, if that user use a 123 with password password. 123 is Vallat, then what happens is you get a 200 steers court, which is an or key a message back to the client. The details returned in the response body is a session. I d your access talking here. He talking expiry because it only has a limited lifespan in that in seconds, your refreshed organ and you refresh talking expiry. You can see that the refresh talking expose a lot longer than the talking expiry. So now that we've got our access talking and refreshed, Hawkins will try and get a task for our user. So moving on to get task on the from the client device, we use this slash task slash to to get task to and obviously these Ah, the FBI endpoints that we've just built in previous sessions. However, on this request, now we'll be sending an authorization. Head of value. So is an http header will use the authorization on that will be our access talking. So I can see here to every CD 123 Now, that's not a valid access. Talking in the real sense. That's just for demonstration purposes. Here, we can see that is our access talking for this session. So we sent get slash tasks slash to tow a resource, FBI. So that's our task c api I that we've built that Does it check to make sure that the valid user and that the access talking is valid So you can see here If it's not valid, we get a response back of four. A one unauthorized, and we get an error message. Access talking is invalid or expired. We don't give really too much away re garden. Every messages would wanna be to specific, especially when authentications constant, because people can use that and check out error messages to target exactly what's wrong. You know whether it's a using the in, that incorrect or password will be a citrusy used. Your password is incorrect. Instead, if this authorization 12 deny access, talking is correct. We'll get a 200 back, just like we normally do. Task I. D. And then obviously a task details e like we have in previous sessions. Now what happens? Obviously, that access talking is only valid for so long. See a 20 minutes or so. If you know you may have lots of task requests going on, you might be up day in task. He might be getting tasks. You might be the leading tasks now, after 20 minutes That access talking will, you know the start to run out of time. So what we have to do now is refresh the talking. So what the client should do because the users should never know this. You know how this works in the background. The client should handle this. The client should know that the access token is approaching this expiry time when it's close. Really? We shouldn't allow it to run out what you can do as long as the client handles this. So once it starts getting Klaus, what should happen? The client should check and go, right? Okay. We've only got about a minute of sort of goal before the access talking is expired. So what that will do is send a refresh talking request to our authentication FBI. Now, the way it does that is use the patch, Remember? Patches usedto opiate where updated in our session. So we've got slash sessions slash three. That is the session that was created when we first looked it up here. So I've got sessions on the score ideas three. So we know that our session is number three. What? Send with the refresh talkin request is the header for authorization and that is our current access talking. Even though you know it might be expired, it doesn't necessarily have to be still currently might be expired. And then in the body, we will send the refresh talking. Like I say, we only send this refresh talking when we need to refresh the access talking. Otherwise, it's just stored securely on the client device. So we send this refresh request to the authentication FBI on the authentication epi. I will respond back 200 orchid. I mean, obviously it could era, but we're just Do you know the quickness to show any here that it's an OK session i d three . So it returns to session information again to still the same session. We're not creating a new session. It is still a CME session. However, we get a new access talking new, obviously talking expiry time in seconds. But this time also get a new refresh talking on obviously a refresh talking expiry. So now the client device will stall this new access to organ on refresh talking, ready for the next set of request to the resources a p I. So the client just you know, plus along is normal, So get slash task slash two. However, this time you can see that the authorization talking is the new one. So a resource. The FBI goes OK on all that valid because I've just created it. So it returns the task back to the client. Once you've finished with that session on, do you want to log out of the application? Although a lot of people don't look out of applications these days, the stay locked in, which is fine because our access to organ Andi refresh talking is stored on the client device. Now our refreshed organ will be stored. I don't know is valid for see a month C 40 endears. That's totally up to you. I mean, you wouldn't have an ongoing, you know, three years or so access talking so refreshed. Talk invalid. You would have like a limited sort of time scale. Soc two weeks or 30 days is probably ideal. So if there's no if there's no if there's no activity within 30 days or until that refresh talking expires, then when the client organs the device again opened the application, it can carry on with that. This sort of session here. So after 20 minutes, if you haven't used the device, the access talk and will be invalid saw the client will automatically request of the new access talking based on the store. Refresh talking. Now if the refresh talking has expired as well. So see, you haven't used the app within 30 deer's. Then when you open the up, it should basically log you out of the up and go back to the log in screen for you to log in again. You probably noticed that on some websites are so maps that your use if you haven't used them for a while the law automatically log, you wrote. So if you're still logged in will go back down to this part. If you still logged in on the user clicks the log out button, we're now want to get rid of the session that we have. So, session number three. So we used the delete HDP method for this. So delete slash sessions slash three. Now, all that's needed for this because the North session that we wanted elite is the authorization talking. Now, at this point here, we're not really bothered whether this authorization talking or access. Talking is valid because we are just logging out. If it was invalid, this potentially that you could have a rock session on the service somewhere. And that's not what we want. Basically, if the access talking much is this session, then it should just deleted whether it's still active or not. So one forgets wants to send that request, which will get a 200 back or K and then the session that we've logged out of a session. Three. So on all that's a fairly basic floor diagram there because there's a there's a lot more like and go on with the user experience. But I couldn't fill it all on the screen to be fair, eh? So what I've done is just cut down to some of the basics, but hopefully from this diagram you should be able to see how we're going to implement the also medication FBI and how the floral work as we're going. Okay, so we'll stop building the authentication functionality in the next video 22. Users Table Creation: first thing we need to do is to create a table within the deer to be. It's just stole the user's details in, and this is what we're going to do now. So the first thing you need to do is open. PHP my admin. So I've already got the me in screen organ. But if you haven't got this organ, all you do is open month. Click the organ Web, start pitch, hover over tools and click PHP my admin. I'm just gonna bump the font size up so you can see what I'm doing and we'll go to our tasks. TB and you can see here have currently got a table called table tasks. This is the table that were created, obviously in a previous lessons, and this is a test data for the tasks. So go about the task. TB. When you to create a new table toe hold, the users will call it TBL users. We'll give it six columns and we'll click Gore. First field is I d causing you to store user i d. This is not the same as the user name. This is an internal sequential number for the prime UK. The data beers, the type is begin. The index will be primary OK to this. And then auto increment. Because this is a sequential number, remember? Well, let's give it a quick comments or user i d The next column is full name. So this is the users full name. You could separate this out into first name surname, that sort of thing. But we're gonna do full name stored is a bar chart. 255 characters. And then what we're gonna do is just give it a comments or users. Full name. I think that's okay. Well, no need to add Ian using him. This is a vulture to refute five characters, however, this one is going to be unique. So we need to put a constraint on to see, nor one user can have the same using him. Give it a name. Soul just called us using here because being clusters and index okay, that give it a comment uses using him something like that thing. That's okay. Next field is password var char to 55. This one is a little bit different because we need to change the correlation on this. Normally, we use utf ph General C I for kiss insensitive So it use utf e it school down. And for this field, just this field we're going to use utf it. Underscore Been this allows case sensitive. So with a password. Obviously, we're gonna hash this in the database because you shouldn't be storing passwords in plain text. So even when it's hushed, we need Teoh do in verification based on upper and lower case letters and characters. So we need to stall this values utf it? Been so you TF had been has also just noticed that I spelled password row. So I'll make sure that's correct Password. And then we're just going to give this your comments or users Password. Next one we're going to do is use the active and this is an Denham. Enumeration will edit the sets and the values. Get rid of the bottom two. I will say no. And why? So these the only allowable values we'll give it a default off. Yes, So when a new uses created love, a default of its currently active Now we may want to disable the user may be a valid reason to disable the user. So we said a flag in the day to be is to see whether the user is active a lot. So is user active. I think that's OK for comment on the next one we need to do is log in attempts we want to store how many tries the user has. Heart Soul will recall the unsuccessful attempt so into J them. It will be one number cause we're gonna have a policy that locks the user out after three failed attempts. So we need to record some way in the database where the attempt saw. So we're going to give this a default value of zero because the user should have zero log in attempts that begin. And that'll increment. If the attempt to log in unsuccessfully who will give it a comment so am there will be attempts to log in. Yeah, then, yeah, I think that's fine. We'll give the table comments. So uses table groups and the correlation for the rest of the fields is utf it school down And it's general case insensitive. So this will be for the other fields, such as full name using him. Like I say, we've explicitly put that one on because We need to allow the database to check or verify beer. Start over and lower kids characters for the rest of the fields were not bothered at all, Really? So we'll see if that so. Now we're gonna use this table. Of course, browse should be blank. That's correct. So go to structure. So in the next video, we're going actually create the endpoint to create users, so that's where we're going to start off from. 23. POST - Create a User [Sign up user API]: in this video will be creating the A P I. That will allow any new user to sign up in other words, creating users using a post request to slash users. So we'll need to create a new controller for this and to make some changes to the HT access file for the new route. So, first of all, for open a bottom and this is our test control here, what we're gonna do is close this down, create a new controller for the users, a p I. So far I click on control it new file and we'll call. This uses the PHP so we'll create this start PHP tag. And then what we need to do is because we're gonna obviously be communicate with a database on did use now a standard response model who need include these files so require wants hopes the 1st 1 is db dot PHP on the next one is require. Once on it was root him after Navigator it sorts dot dot, slash model slash in response to a PHP because I response model is in the model directory. The next thing we need to do is to connect to the database so with authentication, and we will always be using the right DB, which is the master database. Fourth Indication would never use the read slaves for anything, so we'll try. And then what we'll do is catch. This will be the PDO exception. It's not statement in your exception index on what we need to do is to create our standard error response. So because this is a PD your slash connection error, we want to put this in our log. Saw the PHP error log. So remember from previous videos ever log. And then it is theme, message or connection, Kara. And then what we'll do, we'll depend the exception and then stored in the PHP errors file. So that's that created no when you create the standard response. So response. New hopes, new response. The response said it didn't pay stairs court, and then this is a 500 error because it's a server error for Con connect and then response set success. This is false and then response. Want to add a message on something like, um, dear dubious connection era, And that's fine. I will send it so response send and then exit, so we need to try and actually initiate the connection stole out invariable so we can use a throw this script. So skates of space and we'll call it right DB And then it's using the static method from the dubious class. So Devi connect right Devi the method were created to go back to the dear ofhis this one here starting method. Okay, so that would try and connect to the database. And then if Akon connect will Hundley exception here, you know have done that's the next thing we need to do is to check the http method of the request method now, because we're only gonna handle post requests, for example, creating new users will just need to do a simple check to make sure that it is a post request. And if it's not, then just send us an error response for 45 which is a request method is not allowed. So I do. And if statements and then we'll use a cervical Louisville variable, and this is request method. We need to check Teoh. See, make sure this isn't is something other than post. So if it is post, then don't show the era. If it's something other than post, we need to show an error. So I will do Here is just copy or standard response. I've done it many times before. State is called, is a four or five, which is a request method not allowed. So if it's something other than paused, it's a request method not allowed because we're only allowing post requests. So the error message will be, um, request hopes, Request method not not allowed school down slightly. Okay, the next check we need to do because we are sending a Jason body, which will have the user details that were creating, such as full near me. User name, a password, that sort of thing. We need to make sure that the content type for the request has, Bean said, two GS on So, like what we're doing in our previous lessons over do if save a global variable and then it is content type on. We need to check to make sure that it is application slash gs soon, and if it's not copy. I was standing every response, which is saying a bit time here because I've written this out. Lords, so the state is called is 400 error because we, um if it's if we haven't set this than it's a client issues or set this from the client for the request on the message will be content type had not set to jasan care school down. Give us a bit space here. Right. We need to get the posters deter the postage es on on will store this in in a variable sore for call. This something like raw posed data and then we'll use the file, get contents. Remember, it's the PHP and then input to get the request body they wanted to do. Make sure it is valid. Jason. So we need to another if statement, um, jasan data will need Teoh check to save its false positive. False. Remember that the Js on Dick Ord returned false. If there's an error. So, um, Jason on the school discord, and then it's raw course dinner. And then if that is an error, copy this again. Response response yet and then it's 400 message because we're having supplied Balaji s on. The only thing we need to do here is to change the error message. Um, request The body is not valid. Jasan. So we're saying here is trying to call the Js on that's passed in in the request body. This function returned false. If it can't recorded, for example, if it's not biology Hassan So if it is valid Jesus almost stored in this Jason did a variable. However, if it's false, then we'll send this every request. So we have a response back. So now that we've got followed Jesus on hopefully on the school down, we need to do some basic checks on the dealer that was sending in. So the first thing you need to do is just to make sure that mandatory fields are there. So if we do an if statement remember, we used the is set Onda, we need to check if it's false because this is Hundley era, so is set. And then we'll use the GS on Deirdre. And first thing we need to check is to make sure they have supplied in the um so this is called full name on the next thing we need to check. So, Paul, um, is set is to make sure that sanity using him gs on deer there using him Oh, is set. Jason data on its password. Okay, so it does the check to make sure these are set. Make sure that provided if one of them is not provided or if all that is not provided, we will send back a on air response. However, gonna do it slightly different here, so we'll copy. This is a basis. Who pays that in? It's gonna be a 400 error because the client hasn't supplied the correct or mandatory fields success. However, we're gonna do something slightly different with the odd message. We're gonna make the message specific to the ever. So if we used the term re operator again, So the first thing you need to do is to, um, we'll just change this message for the 1st 1 so we'll just see a full name not supplied. Create that kit on. We need to do the turn. Re operated here. Saw in brackets we need to do if it's not set and we'll see a GS on data on full new um, Then send this error message. Burke, move that to here. The cynical enough, Otherwise just false, because we're not bothered about sending anything back if it is supplied. So we're doing here is creating a standard response we used internally operator, which is a shorthand if steam. And if you remember. So we're saying if the full name is not supplied, so not false, then at the message that's his full name, not supplied otherwise false. So what we need to do is for each of these, we just need to do the CME. So it builds of the error messages so we'll see a full name. So this one's using him, and then we'll just see using IAM not supplied on the next one is password. We'll just see password not supplied. So if there's a combination of these are all three that are not supplied in the body, we'll get that error message that every message and our neighbor message. However, if using your misapplied what full name and password isn't, we will get that error message and that our message replied in the response. I was stripped that white space out there. Okay, the next thing we need to do now that we've checked that the data is there is to actually check what type of theatre it is and make sure that it's volunteer, so make sure it's not just a blank string or make sure it doesn't exceed 255 characters, so that's what we'll do next. So this one is if, um, will use string length. So STL Len. And then we'll use GS on data and the 1st 1 will check is just the full name. So if string glands off, the full name is less than one. So basically, if they have just supplied the full name, but it's just a empty string. So they've done something like, um, full name and then just on empty strength. So that doesn't have any length because there's nothing in there. So we're just checking to make sure that it does have some sort of value. So if string land full name is less than one, but then what we need to do is check to make sure it's not greed a than so we need to do in or and then we'll use thes string length again for Jason Theodora full name, and we'll see if it's greater than 255 characters because we're building up an error response here. What I'll do. I'll just put the if statement here now bill The body of that, um so that string yet? So we need to do exactly the same for full name using him and password. So these are all limited to 255 characters on the must have something other than an empty string passed in. So what I'm gonna do is copy this, see if some typing doing all and then sorry, I put that in the wrong place, Spierce there, or just creates a more space here so we'll see what we're doing. 255 and then we'll do it all. And then we'll pierce that in there. So for school back across, you see there the original, too, and that we need to adjust these ones. So this one here hey, is three years and name on using him again school across. And then we need to do it all on pierced and again. So that was the user near will. Change is pasted value here to be password because that was the next check. And then we'll get rid of this white space. So basically said for each full name used the name and password that there have to be not a blank string and not greater than 255. If that is the kiss, we're going to send in every response back. And what we're gonna do is use this sort of conditional statement here to build a dynamic response. So I'm just gonna copy that is obvious. Pierced it in there. Still a 400 era because it declined. Hasn't supplied the correct. He deals all the details in the right. Former. So this is where we checked previously. The is set. What we're going to do is just substitute that for the checks here. So the 1st 1 is gonna be make sure full name is not blank, so we'll just replace that. So string glands. If it's less than one character, then the message will be full name cannot be blunk thing that Sam quite descriptive. It is going to get rid of this because I want to copy this line here because it's gonna be very quick to make the changes we need. So the next check waas greed and 255 characters saw greater than 2 55 and the message for that will be full name cannot be creator than 255 characters. So now that we've got them to their, we need copy and pierce that once twice because we got full name, user name and password, the full name. Next one would be user name and use the name here and then we'll change. Is there a message so we'll see. User name cannot be blank on user name cannot be greater than two new 55 characters. So the last one is password. Then then password. And the message for that would be password cannot be blank on board Possible. It cannot be greeted. 255 characters. OK, so that's our era response handled. So we're doing something a little bit different here where we're actually sending back to the client the exact error message. Um, and obviously we're adding messages here, so it's not just one message, so it could be a combination of things. So the phony, um, you know, that may have ended blank, but the user name that may have ended something greater than 255 characters, for example. So they would get that every message along with that error message. Okay, so the next thing we need to do is perform some, um, for not quite four Martin on the deer. That butch trim some excess spear self just tidied up slightly. So what we'll do here is creating variables on what we're gonna do is strip any white space off. So if someone's provided a full name off Michael Space So it's not just my village Michael Spears. We don't want that because that's not very good. Now what we'll do is we'll use the trim function, which will trim white spierce from the front and back off the text provided. So we used trim and it's for the full name. So it's Jason Data and then full name. So we'll do the same for using him because they use name. Shouldn't have any white space after it for Jason Data using him, um, and password. We won't be doing any tree monitor because a password potentially could have a space in, um, you know, makes it secure it a valid character. So your password might be password. 123 Spierce. So what were you going to do here is just collect that password value from the Js on data in the story and password. So now that don't not we need a performer database query to make sure the years and they're not being passed in is not currently used by someone else. So you know, when you try and sign up to certain websites and things like that, you can't have a using here that someone's already got. So we need to do this sort of check now. Now, the the only way you can do this is to query the database based on the user name to see if there's any rules exist for that using him. So are normally, obviously, when we do database queries, we put them in a try and catch statement. So that's what I'm going to create first. Just this. Just this rather here. So try catch. And then it's gonna be a pidio exception a X, and then we'll create the ever response eso response. Um, actually, it's era log first because it's a database query errors. So we want to Nor, you know, the system admin. Want to know this or hair a log? I m did the best Queary era, and then we'll upend the exception and then zero to put in the airlock and then we'll create our response and then respond. Such http status court in this one is a server error sort when it's gonna be a 500 and then said Success not false. And I'm going to add a message and the message is going to be there. Waas on issue hope spell. It was wrong. Creating and use a accounts. Please try again. And then we're going to send the response and then exit. So it's kind of the end of the file there. But obviously we're going to be doing some logic within this Try steam and here. So the first thing we need to do is to create a query, to check to see if there's any roars that have a user name of the past in using him. So we'll create Queary and it will be on the right d b. And then I'll be prepared. And then when you to put the sequel career in here. So we select, but only we returned. The whole role will just return your value because all we're going to do is do a raw count to see if there's any roars. And if he is a rule. We're gonna send an every message back in every response to see the using him already exists. So what we're gonna do is return the i. D. Although we're not going to use it. Select I d from TBL users Remember the table I would create in the last video. So tbl uses where user name equals and then a place hold of using here we'll do query and then we need to find the parameter. So it waas using him and that is bound to the user name variable that was stored in the past in using him from the Js on body. So we'll check that against that entities of type pidio Parham str because it's a string and then we will execute it. Queary executed. So now we need to get the rule count. So we do that by query, and then it's rule count. So, like I say, if it is, um, something other than zero, then we need to send a never response back to say the using him already exists. So we'll do a quick checks or raw count. Um, if it's not zero. So what I'm gonna do is copy this every response and then change it here now. Two new response. That fine status court. However, this is a new one. It's a four or nine, which is a conflict error message. So 409 is conflict. So the data that provided is conflict in with something else set. Success is false, and then we're gonna change the message, and this message is going to be amusing. Name already exists, and that's OK till send. That's an exit dot Okay, so if we now move on so we have a using him that's not in use. The next thing we need to do is to hash the password that was being given. So the passwords currently passed in here and stored in the password variable. Now, it's not very good practice to store the password in plain text in the database, so we use password on the score. Hush and password underscore. Verify Now what this does is hush the password using appeared people in function. It's sort of used within the industry. It's a well known method and a tribute here to really so what we're going to do here is create a new variable called him hushed password on a password on the score. Hush on takes to prominence. First is the password so that's currently stored in our variable appear. And the next day is the algorithm usedto hatch the password now. PHP. When you read their documentation, recommend to use the password underscored default. Spell it correctly. Default on what this does is this always uses the most newest algorithm that supported by your PHP version. Now they're documentation says that this could be changed in the future. So it's just something to keep an eye on if you swap between PHP versions and things like that. So password default is the standard one that PHP recommend. It's very secure. So hash password. Andi. Now what we need to do all the school down slightly. We need to insert or try and create this rule in the table of for users or TBL users. So check the dead and our need inserted in saw. What we need to do is create a new query was still within. I would try and catch them. Remember so Queary and it was right D B and then it waas pre pair and then we need to use insert into tbl users remember summer Some of the fields in the deer base have default values, so don't need to supply values for them. Things like user active on, um, number of blogging attempts. So user activity defaults toe. Why? So Tony, supply value for that Andi number off path M number of a log in attempts that is currently at zero. So the fields we need to supply is full name, user name and password. So the values will be Please hold this. So the 1st 1 is full name and then itwas using him and then password. But remember, when we bind them, it is the hushed password we need to see. If so, Ok, TBL uses full name, user name, password values, full name, user name and password. That looks OK. So when I will bind them. So Queary find Parham. So the 1st 1 is full name on its the full name on its PDO hopes Perama String buying the next one bind Perama and this is using him. So using him on this one was PDO Haram Strength on the next one is query planes, Prom password. This is important here. We are not put in the password field in there were putting the hashed password field in here. That is very important has password. And then this is PDO Haram strength. So now we'll try and execute it. Get a rule count. Make sure it actually has inserted the rule. So Queary, bro account and then we'll do a check to make sure the raw account is not them. No, Sorry. Not zero broke counts. It is not. See your or sorry. We need to check to see if it is zero. Because this is the era, Andi. Well, supply back and every response. So I'll just copy this one down here to 500 error because it's been a database problem. False. Andi, I think that every messages okay, his basic c And if it's field to insert into the database for some unknown reason, then, um, send this hair response back. But I think that's OK care. So now what we need to do because we've got the raw in the database, we need to return years of D deals to the user. Now what we're going to return is the user i d. So that is the the generated primary key auto increment value. The next thing we need to return back is the full name and the user name. We will never, ever reply back the password. It's a bit of a security house. It's will never report. Reply that back. So what we'll do now is build this up. Sel, after you've inserted the were to get the last inserted row I D, which we've used previously is to use the last insert i d. Function of the connection. So we'll see if that in last user i d. And this is against the right database connection and not the query. So it's last insert i d. So now that we've got that we need to build our successful response. But obviously we're returning the user I d the full name in the user name. So we need we need to build the return dinner. Return data. I am sorry. It's That's an Arria. So the first thing you do is return did there, and we're gonna call this user I d. And the user i d is that lust incident I d. They saw last user I d return theater. This is full name. So the reason why we return in this Because every time that you create something, so we will use a post request. We should always return that new object back to the client because the client may want to store that on the system. On the client side, we don't know, but it's always good practice to return this back to the client. So full name is, um, full name on return dinner, Miss, is Theo using it? Kiss called down slightly. So now that we've got them return, did there. We need to build our standard successful responses. Time response equals new response in response, said he actually to be steered us court. And this is a tool one because it's a creation. So to one response, sit success, true response. And then we need to add a message. So this will be user string user created responsibly to set the data. And this he is returned data because we're returning that I read Ascended Aunt Exit. Okay, give me this white space, see if that Okay, so, in theory, that's our create users. Um, done. So we'll just have a quick scan through here to make sure looks OK. So we're getting the database file would get requiring the response file. We're trying to create the connection with the connection. Feels we catch that and send our every response back. We'll make sure that it is only a post. If it's something other, we'll send our standard A response back, which had a content type to make sure it's GS on. Otherwise, send the era was safe. The law Post data from the request Inter variable will make sure that is valid. Jasan otherwise was sent in error. We do some standard checks on the data will make sure the monetary fields are provided. Make sure that it's validated within that. I mean, if it's if you're check in the password. I mean, we haven't done that in this one, but you could create an if statement to say, while the password must contain an uppercase letter, a number, a special character, that sort of thing. So this is where you would you would do that check here. So using their full name was stole them, and the variables would trim them to get any rid of white. Any white space would do the check to see if the user name that's being provided or he exists. If it doesn't, we hush the password so we don't stored in plain text in the database or insert that into the database. We'll check to make sure that it has actually gone in. We'll get the last user i d. That's been inserted and then we return our user object back to the client. So the next thing we need to dio is before we can run this and test it need to go back to our HT access file and then we need to start a new route in here. So after this one was going to create a bit spierce, we need to create a route because we're gonna paused to slash uses. And that's what we're going to use to create a user account slash users. So we need to create a rewrite rule that ticks, um, uses. And then we'll and that. And then what it's gonna be is let me think about this. He'll be controller and then will be slush uses. Yes, I think that looks ok dot PHP and then we need to put our last rule in there. Yeah, that looks all case. We'll see if that So we re writing slash uses and that's gonna 0.2 controller slash users dot PHP Because that way I will file stored so controller, and then it's called uses dot PHP. Okay, so now we can try and create one, so I'm quick going to do is open. PHP Maya Hartman. Well, gold. I will use this table. Go to browse and just make sure there's nothing in there. So it Emily, we'll go to postman, we'll create a new request. It's gonna be a post. What I'm going to do first thought is just to make sure that I would some of our logics working. So we're going to try and just send something as a get request. Like I say, I know this is gonna feel but will be a good test. So its did he pay Global Horst 40 idiot idiot slash everyone slash And then it'll be uses. So we'll just send that Looks like I've got a syntax. Aristo still check. So go back to Adam. Could line 61. Then we'll just double check here. That looks okay. That looks OK. That looks will care. I've got an end bracket there that the door needs will take that out. Means we lost time in here is just double check the rest. It looks OK. Looks OK. And it looks like I've got one too many brackets at the end as well. So we'll just see if that go back to post mine run that. So now we've got a success, so I've successfully debunk that. Now you can see we've got a four or five era, which is a method not allowed that what I was expecting because we're no allowed to use a get request on this route. So change that proposed, then we'll descend it. So now we can see here we'll get a different error message. The content type head has not said a J S on. That's correct. So if you go to the body, click on raw change, the type to application. Jason, you see that now? The header. It's a content type of application, Jason. So for San Dutch, scroll up request bodies Novella Jason. That is also correct because actually, we supplied a blank body to this, so it creates a blank Jason in here. We'll send that ending, say there that our error messages work and fine. So full name not supplied using AM not supplied passwords not supplied. So for creates full name. So full name. And then I'll just say Michael Jones is an example. And send that so you can say that their full name era has disappeared. And that was just got our use name not supplied and password not supplied So that logics working or care. So the error messages of being dynamically sent dependent on what the error messages So full name will say a user name. And I'll just call this Michael and the password on. And that is what I see. A password. 123 So hopefully this should create a user double checking the uses table to make sure it's there. So we'll send That got a successful response back to warn. Created. They were also reply and back with the user object. So user i d. One full name and he using them. So users created No. If I call back to PHP, my outman refresh this table's over. Click on browse. You can now see that we have a user i d. Full name using them stored, and you can see the default values of user active is why and log in attempts of zero. You can see here that this password is not password. 123 It's actually a hushed password that we store in the database. Now we can't sort of decrypt this. It's a one way hashing algorithm. And the way that we check against this is to use the password verify and we use none of future lessons. So now what we're gonna do just for validation purposes is just crying. Try and create the same user again. So Michael Jones using here, Michael and Password 123 send. So you see, there were kind of conflict. Success is false, and using them already exists. So you say that now that user name performing the check to make sure we've got a unique using him. So even if I change this full name, too John Smith on the password password 567 it and send that buck, it's not bothered because it's doing the check on the use name. The user name must be unique. So if we create a new user called John with password 5678 and send that created a new user . So use a to John Smith and use the name is John. Go back to PHP. My admin click. Browse. So we've got a new user there, So we go back to Adam. That's basically our slash users route created. You could expand this for this, or people get actually updated their own deals. So it might be things like you might store email addresses. You might allow people to change their name. So for Michael, the user, I d. Was one. So be apart. Request slash users slash one. Okay, so now that we've created a user, we're now going to move on to the next part. 24. Sessions Table Creation: in this video will be creating the Sessions table in the My Sequel database. This will store uses sessions and user access and refresh Talking's along with the expiry dates and times Full open page pay. My Hartman, we're in the tusks. Db If you create a new table called Tay pl sessions on six columns, cool. 1st 1 is an I. D. So this has been like a session i d. It's a big in its prime e k. Okay, that on its an auto increment, give it a comment. So session i d. Next one is the user i d. Because for each session it's associated with a specific user, which will link with a foreign key from the user's TBL uses table, so that needs to march. So it's a big end as well, because that's what it's stored as in the user's table. School Along on will give it a comment off user ID. Next field is the place to store the access, talking to access talking. This will be a voucher and will be 100 characters. The correlation will be utf it school down and will be underscore. Been so a bit like what would used for the password. It is care sensitive So we need a store. It is a utf been Give a comment. Access talking they won't need to do is store on associated expiry date and time So access talking, expiry This is it did time on will put a comment in for access talking expiry date slash time Then it's a refresh talking This is a bar chart Unless this is also 100 characters on ut f here it on the school been because this is also care sensitive So this is refresh talking on the refresh talking expiry and they say is also a date time hopes from one the time and then this is refresh Tokcan expiry date slash time Give a comment So and this is sessions table on the correlation for the other field or just in general utf it underscored general case insensitive. So we need to see if that so now I've got obsessions table. The next thing we need to do is create some unique indexes on access. Talkin I'm refreshed talking because an access talking we can't have multiple rows in the table with the same access token and the same goes for the refresh talking. So the way you do that is tick. And then we want click here for unique and then tick for refresh, token and click unique as well. So you say here that's created Thea Assess talking to refresh talking as unique indexes. So they sports constraint on the table to see a rule in the database has toe have a unique access token on a unique refresh talking. Okay, the next thing we need to do we need to create a foreign key on the table to see well, the user I d the user I d in the sessions must exist in the TBL users table, so that links these two together so we can't have a rock session in here that doesn't link to any user. And the way that you do that, you click on Relational View. I don't need to give it a name here, so we'll call it session user. I d underscore f care for foreign key name or want to do is leave thes under liter. No, no debt as restrict. So what they should do is you can't delete a user i d or sorry, user. Where there's an active session so would have to get rid of the sessions first and then get rid of the associated user. Ever word deleting stuff. The column that Willingen to is the user i. D. So this is the user I d in the Sessions table and never want to connect that to Tusk. Stevie did. Abyss uses table, and it's the i D off the user. So it's not the user. Name it. Actually, the physical I d off the user. We'll see if that so. I've created that successful. So just assure you what that means is Insert will just manually insert a role here so we'll give it a user I d. And you can see here that these are our two years is that we created in the table the users . So John Smith, Michael Jones and the user I d next to it. So we can't create a session against a user that has an idea of 20 because there's not one exists, so it just allows you some validation on the table. So, for example, if we create one against John Smith, create a random access to organ, this doesn't mean anything. I'm just time in some test eatery here and then give it a default yet and then see, if so now we've created the rule you can see here, they've got a session I D user I D and access to. And then I just randomly created an expiry date and time refresh talking. Now what you'll find is because that's hooked up the user i d to Vicodin. Tibial uses Go to browse, trying to lead this John Smith, which has a user idea of to which that session is against click or care. We'll get an error message to see that we're card deleted because this child rose. So what that means is that because we selected restrict on delete, we can't delete that user because it has associated sessions. No, find out a little session and then go to users. Go to browse should be a little. Eat this user now. So there you go, because there's no sessions for that user. We can now delete that user, so it's just a way to put some constraints on the tables and on the database so you don't get any what's called orphan roars, which means that you might have around obsession against the use of that no longer exists, so it's just to keep a tightly integrated. So now that we've got our table creative processions who need to move on to create in the sessions and point or route that will allow us to log in as a user, which will create a session, so that's in the next video. 25. POST - Create a Session [Log user in API]: In this video, we will be developing the creative use a session, a p I, which is also known as locking in. We will be allowing the user to use the user name and password. They have to create a session. This one return an access talking for the requests and a refreshed organ for when the access talking has expired. This allows you to get a new access talking. So let's open about him and you can see here this is our users controller. What we're gonna do is create a new controller toe handle the sessions. This will include creating a session which is known as logging in deleting a session which is also known as logging out and also refresh recession, which allows us to get a new access talking. So the first thing we're going to do is close down this users right click on controller, create a new file and we'll call this session's dot PHP. We'll create the start tag for PHP and we're gonna need to include our database file on our response file, just like we're having the previous controllers so require once. And this one is the database one db dot PHP on require once and this woman in the navigate to the model So model slash response dot PHP. Now that we've included the files, what we need to do is create the database connection. Just like I mentioned in previous videos. Anything to do with authentication, which includes Logan and create user accounts. Locking out should always be done on the right db on the master database. So that's why we're going to try and do. We're going to try and connect to the master database so anything do. The database must be within a try and catch statement, so we'll create that now. Try catch PDO exception, and we need to create a where every response. So every log, because wanna, because it's a database connection. Everyone loved this for system happens, so every log connection era depend. The exception on zero means it goes into the page. Pierre is log file. So then we create our standard response for the error, and then we just start filling it out as usual. So response such a cheapie. It's dear, this court, this is a 500 workers were con connect on. The next thing is response. Sit success and that's false response. Our message did the obvious connection era response. Send on an exit. OK, so that's our error handling there. So if we can connect to the DB, which will create now, so call it right D B connect, write dp So the self static method from the database class, which is up here was that Okay, I'll see if that's still check. Make sure all looks all right. Yep, create the database connection with wise era log. Yep, that all looks OK. So the next thing we need to do is create some space. Schooled out is to create our if statements that will select the logic based on the route. So in order to call us the A. P, I were going to be using the slash sessions route. Now there's two things that can happy near slash sessions, which will equal a post request because this will be used to create a session slash log in . On. There will be a slash sessions slash and then the session I D. So that could be three, for example, will be two of thes, so they'll be slash sessions slash three, and the 1st 1 will be delete, and this will be used to log out. User on will be slash sessions slash three, for example. But this will be a patch. Remember patches to update it and will use this to refresh recession. So will refresh an access talking to get a new one refresh session. So these are the three things we're going to implement in this session's file. The 1st 1 in this video. We are going to implement the Post, which is used to log in slash create a session so we'll be using the slash sessions. But what we'll do, we'll put the placeholders in tow. Handle thes slash sessions, slash session idea the same time. If there's something else that you saw, maybe someone will try slash sessions, slash test or something like that that is invalid and what we're going to do. They is just provide a standard response to see four or four the endpoint not found because that's not a valid route. So we'll do that. Now, get rid of these. So we need to do if and then we'll use the area. K exists every que hopes reiki exists, and then we're gonna be looking for session I D. And this is within the get create that. So what? Basically, the route is going to translate to once we updated our waged he access is something like slash sessions dot PHP and then will be something like Sessions or Session. I d equals three. So that's kind of what it translate to for the one where we do slash sessions slash three. So that's that. Check there and then we'll do a check within this to see whether it is a patch request or delete request, which will handle the Logan in Sorry, the logging out on the refresh of the talking. However, in this lesson, the man thing that we're going to do is the next one, which is the else. If Andi, we're going to check to see if the get saw the bid after so the query string is empty. So it just contends slash sessions, which would be that maps to just slash sessions PHP, which is the file away dealing with currently? So yes, or check if it's empty and that is the get so that handles them to like I say, we're not going to be using this one in this lesson, but we will in the next one in this lesson, we're gonna be using this sort of one here. So the other thing we need to do is handle the catchall. The one if the right slash sessions, slash test, for example. So I'll just give it to them. So that's just gonna be handled by a normal else. DeArmond. And what we'll do here will create our standard ever response. When I'll do, I'll just copy this one for quickness Copy Pierced. It's not a 500. It's a 404 because slash sessions, slash test, for example doesn't exist. Endpoint is not found. And that's exactly what we're going to write in this error message. Um, and, um, and points not found. So we'll see if that so that's that created Andi. We're going to concentrate on this lesson in this bit here, so I'm just gonna create some space here so we could know start. So the first thing we need to do here is to make sure that it is only a post request that is handled because this is slash sessions. So this is creation of a session, remember? We always posed to slash sessions because we don't know the I d. That's just, you know, generated by the database. So we need to do a check to make sure that it is only a post request. And if it's not, when you descend an error response to see a four or five, which is request method not allowed. So for this route, which is slash sessions you wouldn't be allowed to get or delete or patch or something like that. So do that check now. So if server on DIT is request method, Quest method and then want to see if it's not equal to paused now we need to send us in our response back. So just copy that to save a bit time here was written us out millions of times now, and this is going to be a four or five era on a 10 point. Not found will change that, too. Request method not allowed. Okay, it creates more space, and I'll just see if that so server request methods not equal to post, then sending her response. So see it is a post, which is great. The next thing we're going to do is it's a bit of security here. So what this will do is prevent or help prevent a brute force attack. Now, take example. Ah, a brute force attack will keep hitting an endpoint try and lots of different used your password combinations. Telephones, one that's successful. Now this dependent on the speck of the server that you have. I mean, if it's just a really small server, it might not be able to handle that many requests. You know, at one time, however, if you've got a really sort of powerful server that that server might be able to handle, you know, maybe something like 50 100 requests per second. Now that that basically means that potentially the hacker could try 100 passwords per second. And, you know, if you've got a dictionary you know, with a 1,000,000 you know, different combinations in I mean, it's still going to take a long time doing is wrong boot by DeLeon it and that's what we're gonna do here. So what we're gonna do for every request that's attempted were going to put a Dillion of one second now one second tour a normal user that logging in is not really going to make that much of a difference. However, by Dillion, a potential hacker by one second will make a massive difference. Instead of being able to, you know, submit 50 to 100 requests per second, we're going to now limit this down toe one per second. So they have got a 1,000,000. You know, that's over at least a 1,000,000 million seconds, you know, to try. Oh, are, you know, trying every combination in the dictionary. So you know something that's not really visible to the end user. We're going to put this in, and it just makes the system more secure. Now. The way we do that is we use a function called sleep, and then it takes a parameter, and it's basically how many seconds. So we're just going to say if sleep for one second. So as it tries to post as it runs through, this court at first checks the post and then immediately it's going to sleep or hold for one second. Then it's going to carry on doing, you know, it's normal checks. So by just introducing out daily there, I wouldn't recommend really much more than a second, maybe two seconds maximum. But you know you don't want us. Every time a user logs in, you don't want them with, you know, 10 or 15 seconds for the log in tow work. You know, people, people lose patients and use a different system. You know, the lose your you know, the lose patients with your system. So after Energis that sleep for one second, the next thing we need to do we need to check that the content type that submitted in the request body because they need to submit, obviously a user name and password. Is this request Now? Obviously, in the previous lessons, we checked three content types being Jason. And that's exactly what we're gonna do here because this FBI and this whole courses dealing exclusively with jasan. So if we do the check now, so check and then it is in the school server and then it is content type. So it's content on the score type. And if it's not application slash gs on, then it's going to be another error message. Our ERA response. So I'll copy this one pasted in there, and this is gonna be a 400 era because it's a client era that haven't submitted, you know? Correct. Yes. On or the content types obvious on. And then we're just going to change the message to content type Had a not set to Jasan. And we've done this in the previous videos. Que the next thing we need to do is get the jasan and then try Andi, Um, make sure that it is valid. Jeez, on for a start. So just by setting the content type doesn't necessarily see lots of ology, Asan. So we need to check. Not now, so we need to get it. Sorry. So need raw post data, and then we need to use the file, get content, fight, spell, and then it is the PHP input hoops. So it's PHP input. So we'll get that is raw pours theater. And then what we're gonna do is an if statement and we've done this in the purest videos where we d chord it on chek to me, except make sure that the d chord stare mint hasn't returned false. So I will do that now. So if um, yeah, we need to check that it's not false or jasan did, uh, so Jasan discord and never passing the raw post era the school down of it. We use the diversity, the GIs on D chord statement here, passing the raw pours data, which he gets from the request body stores it in this variable. If it's successful, otherwise returns false. If it's not valid GS on and then we're going to send a standard a response back copy appears that it's a new response. Still a 400 message. However, the message is now going to change too. A request body is not valid GS on. Okay, so this point down here hopefully school out. We should have Symbology is on data. So now what we need to do is do our data validation checks to make sure the monetary fields that's must be sent with this request our past in now, the only two fields at your passing here is a user name or password, because we're logging in. So we just need to make sure that them exists in the request body. So we'll do that check now. So if and then what we need to do is is set Aunt Jess on dear there and I'll be using him, and then it will be or if it doesn't exist. So if it is set just on Delia password So we're doing here is use any, um, from the GS on data. Make sure it's set. If not so that's what the F statements doing. It's an era. Handle it. Oh, if the passwords not set. So in essence, that's what we're doing. If the user names not set or if the passwords not set because both of these are mandatory for this request, we're going to send back in every response. So we're coming. That one pissed in there and this time to 400 error message Exactly the same. But this time, we're going to use the term re operator again to see a whale used name is not supplied. All the passwords not supplied, depending on what we're doing, I was going to create some space here on Don't need to put it in brackets. And then what we're gonna do is just use this bit here. Has the check? Saw is sit. Jason did a user name. So we're seeing I'll just create some space. So we're saying if using him is not set, then remember question mark. Then we will send this message back. So I'm just gonna copy that. I'm gonna could it actually going to move it and put it there given of the semi cool on change the message itself, it will changes to using am not supplied. And then what we do here is after that, we do. He else otherwise basically returned false. So if we get rid of the white Spears and Alison, we call on the end. This is our BSC one liner. If steam it so if you use a name is not set then at the message using him, not supplied, otherwise just returned false. So I'm just gonna get rid of that weight, spears. And then I want to copy this line and paste adjust underneath. And then what we're gonna do is change the using them to password and then change this message to password. So now, obviously, this one is seeing if password is not supplied. Then on a message to see it. Passwords not supplied. So, on your request, if you don't supply you using him, you will get this message returned as an error response. If you don't supply a password, you will get this message. I wonder if you don't supply either. You will get both of these message. So using a blood supply it password not supplied. So that's our quick check. Their the next check we're going to do is just to make sure that it within its parameters. So for example, it must have, you know, it must be greater than zero in length. You know, it must be there must be some value there for used your password, but they have most both be less than 255 characters Long or maxim of 255 characters. So that's what we're gonna do now. So press and, uh, do an if statement. So the first thing we need to do is use thes STL Len function again. I'm just gonna create some space here, just organ. See, So string length on it is GS on dear there and then it was using him. So if the length of the using him it is less than one. So, for example, if the using him doesn't have a value in it, then what we'll do we'll create a no response. However, there's obviously more than just use name. And there's more than one check we need to do on this theater. So the next check we need to dio is all and then string length again. Str len And then it's Jason data using him. And then we're going to see well, if it's greater than two and 55 characters. Well, we also want to send an error. The other thing we need to dio. Obviously we're checking the using him on the password, so we need to do another or with the two pipes. Str len gs on data password me. Sorry and make sure it's greater than zero in length. So if it's less than one, so I mean that zero, I would obviously need it. Him. See in every response are returning every response or the next one is str Land and then it's G s own data password. If it's greater than 255 car does. You know, we're also returning an error message, so I'm just gonna get rid this white space because I tell the conditions there. So we're saying you know, if the user name is less than one, so if it's blank or if they use name is greater than 255 which is the maximum amount of cowardice. Or if the password is less than once off the passwords blank or if the passwords grieving 255 carpets, then we're gonna send a never message Buck. So I'm just going to copy this one here. Copy that. Pierced. So the check here is obviously the standard response it to 400 error on going toe. Sort of send multiple messages back, depending on what role. So I guess what we need to do here is change this beginning bit for this bit here. So that's the check in this case. So s T a. R Glenn and I was GS on data using him, and we're seeing if it was less than war, then we'll out the message and we'll see user name cannot be blank. I'm just going to delete this one here because we're going to use this as a basis. So the lens of the use and there must be greater than zero otherwise false use Name cannot be blank. OK, so I'm just gonna copy that. Paste it here in den. That's slightly. So the next check is obviously this one here. So if it's great in 255 so we just change the condition here. We're still dealing with the user name of greater than 255. Then instead of being blank, I will just say, use the name most be less than 255 characters, okay? And what we're gonna do is just copy these two lines because we need to exactly the CME for password. So we'll check the Js on data password and then password beneath that as well. So the 1st 1 checks to see if the passwords blank if it is, we will send back password cannot be blank. Otherwise, if it's greater than 255 characters, we'll see. Password must be less than 255 characters. Okay, we'll see if that so. That's kind of the check on the validation of the theater. The next thing we need to do is to query the database to see if we can find a valid user for the past in using him. At this point, we're not checking the password because we need a return. The user roar for the past in user name because there's a couple of different checks we need to do. For example, you know, if the user accounts actor for if the council locked out that sort of thing. So the first thing we need to do is to retrieve, hopefully a raw based on a valid using him. So the same West, any of the database connection or query, we need to put it in a try and catch statement. So we'll do try Aunt Catch. It appeared your exception and at a X And then what we need to do is send a response back. So we will look this in the airlock, actually, no warrant, because it may be the case that because the person in the used name and password and playing text and I'll show you how to verify that against the hash diversion in the day it appears we're actually not gonna log the exception era in in a plain text file, which is the error log. So it's not good practice to do that, because if someone gets access to the server, then there could read potential log files and see passwords in plain text. So actually, we're not going to do that which is going to send a standard response back. So response, new response hopes, the response and then response. Set http Steelers court and it's 500 error because something was went wrong with the database query and then response set success and that is false. And then it was response hopes response, and then it Watts message. And the message is there waas on issue looking in? Think that's okay. Generic enough not to cause a security threat but enough information to the user and then response send hopes and then exit. Okay, so that's I would try and catch them in there we're going to do. I'm just going to get rid of this white space just to bring that up a bit because we're not dealing with outside of that at the moment. And I'm going to create some white spheres here. Just so we're going to see what would do a kiss for. Now that we're gonna try and catch DeMint, we need to now create the query that was, You know, try and return a rule from the database, so user name equals jeison. Did there use the name on a password equals ji saw Indiana password Cave sold. Store these in the variable. So the past in use name a password from the genus on in the request body will store in variables. So if we create that query now and then if it was the right DB and then it was pre pair and then the sequel, Queary that we're going to write is basically was selecting. Um, everything out of the TBL uses database table where the user name equals the past in using him. Like I say, we're not doing anything with the password yet. We'll, you know, we'll come to that in a second. So select i d. Full name, user name passwords. More of the other ones was user active. Andi slugging attempt. Wasn't it from TBL uses where use a name equals on It was a placeholder. Use the name. Okay. So because using him, we set a condition on the So you're constrained on the database to see if the user name must be unique, so should only get a maximum of one role here. Anyway, um, you know what could have several rows or the use name doesn't exist, but on the maximum one, you know, is one raw. So from that query, when you find the parameter Queary, um, find Haram. And then it is using Nam on find up with using him under these PDO Haram um strength sort of string parameter. And then we need to query execute. So they still run the database query. Now on what we need to do is get a rule count. Real count on that. His queary, um, low count. It should be worn off zero basically so raw account, and then we need to do the check. So if the rule count is equal to zero, that basically means that there's no user exists in the system for the past in news in him . And that's exactly what we're gonna see. So it's a response. So we'll copy this response here and pierced it there. So the response is not a 500 error. It's a 401 which is unauthorized. Basically, you know, there's no use near impossible. It's all the details you've attempted are incorrect. So you've returned a four or one era court which is unauthorized will change the message here too. Use the name or password is incorrect. So what would never do when we're dealing with security is give very specific answers. Toe what wrong? Because I could allow a potential hacker toe workout based on, you know, logic of what right and what's wrong. We, you know, way trying obscure any error messages that we send back, You know, not not really our investors. I guess it's any messages that we send back. So in essence, what what's the matter here is that the user name that that's being given doesn't exist, so the user doesn't exist. But we don't want to tell the user that. We just want to say using your password is incorrect, even though we're not checking the password legacy were just given a generic message back to the user. So what I'll do now? In theory, that's if it doesn't exist. So if it does exist, we need to fetch the rule back. So because we're only dealing with one roll, we're not going to use a while, so we'll do rule, and then it is, Queary hopes, and then it is fetch. Normally we obviously would do this part in a while statement, but there's only ever going to be one or zero rolls, so we'll just do it here. Fetch. And then it was PDO fetch associate of Hurry, Basically. Okay, so now that we've got that, what we need to do is to store each of thes values here in variables. So what we'll do is, and obviously it's the i d so returns i d. And that is rule fighting hopes. And then the next one is I returned full name and that's rule full name. And then thank you returned using him. And that's rule using him basically prefix in these. So I know what is, you know, a past in value and what is a return value. So I returned, um, full name, user name. And then it was possible it roll password and then returns the next one waas user active. He's active the next one's returned log in attempts. So that's looking attempt AM Pts yet, right? So of gosh, each of these values from the query the i d. Full name using in password user active locking attempts idea, full name using and password. He's directive and looking attempts, right. We need to do some validation on this rule. So the first thing we need to do is the user active? So if they got a why then great. If it's not a Y, so the use is not active. We need to send an error response back to see this use is not active. And that's that's the end of that. The same with log in attempts. Now, what we're gonna do further down this script is to increment this number member a log in attempts started zero, and we're gonna lock it out if it's got three or more basically attempts in logging in now . We're not stealing with the unlocking of it or anything like that. At the moment, we you know there'll be no access to the database where a user will update the value back to zero or this back to Why, If you know we need to enable an account, we're not dealing with that side of it. So what we need to do here is doing this statement and we need a check returned user active , and we need to see well, is this e? If it's not a why, then we need to send a response backs or copy that Pierce that in there, two for one error because it's still an unauthorized era. It's still a user access era, and then we'll just change this message to use. Ah, the count. Not proactive. That's fine. So return that if it's not why user account not active? Que The next check we need to do, like I say, is to count the number of log in attempts or returned logging attempt on. What we want to see is if this is greater than or equal to three, I will never just say that it's three, because if somehow, for any reason you know the number is 45 or something like that. If we just basically said if it was equal to three, this check wouldn't work. So we're seeing if it's greater than or equal to three. The user is locked out of their account and the need to reset. So we just got a copy. This message put it here still a 41 error, and here we are going to change this to user account is currently locked out. Thes type error messages is okay. You just don't want to see a well. You use names, correct, but your passwords wrong or the passwords correct, but the user names wrong. You know, you don't want to give that deal. You just want to see a well, the user account not active. All the user counters locked out don't give any way you know anything away with, you know, is that a correct user name is a lot, that sort of thing. Okay, now that we've done our checks and I will use it to make sure that you know they're not locked out on your active, the next thing we need to do is to validated. Password is the same password. Word for word over cares for over case. You know, special Cardiff. A special character is the same as the past in one, But because our password is hushed in the database, we need to use the PHP function called password underscore. Verify now, if you remember, and I would create uses route. We created obviously the password or hash the password using the password underscore hash function. So what we need to do here, a password can never be unhatched. That's important to know. You know, you can't convert it back to replay in text. Password. The only thing you can do is pass in a plain text value and check. It does like a verify based on the hush, so you can never, you know, converted back to play in text. You always sort of do a one way hashing. So what we need to do is use the password under school, verify function, you know, and that returned a true or false. So that's the check one, even two. So we need to do. And if and then if it's false. So it means if the password is incorrect, we need to do two things. We need it. Update the log in attempts to increment the log in attempts. Number. So it's currently on zero that will goto one. You know, if it's currently on one that will go to. So that's the first thing we need to dio. The next thing we need to do is obviously return the error response back to see the use name. A password is incorrect, so we'll do the password. Verify first, so if it's if it is returned false so possibly had verified, it takes two parameters. The 1st 1 is the plain text passwords that's passed in in our request body appear so within the Js on data this password here. So a passage in the plain text passwords or password and the next parameter is the returned password. So this is the harsh of the password that you know that's stored in the database. So returned password. So if if the verify function returns false, saw the past words don't match. The password is incorrect. Then we need to update the user log in attempts. Andi. Then send the every response back. So we need to create a database query. So query and then we'll be right db and that will be prepared. And then it will be updated so we'll be OK. It tvl uses, and we need a set looking attempts to current value plus one. So log in attempts plus one way I d equals and then it will be I d. So it's a placeholder. So and ideas, remember, is not a using him. It's the sequential number that's generated from the database because it's ordering current primary key. So we're not doing that based on use name. We're just doing it on or, you know, user user righty. So what this is doing here is to set that rule for this user name. We increment in the logging attempt by one so it takes its current value, and then pluses want a lot. So we need to find the parameter crebain Haram. And then it is I d. And that is what? Passing the returned i d. And then this is Peter, your Haram Pinochet. And then we needed to query execute. So because with warrior within a try and catch damage here, we're fine. If it's, you know, errors because it will captured here anyway, so that's OK. Okay, so that's updated. The log in attempts by one will now need to send our response back to all this. Copy this, and then pieced it there. And then it is a 401 error still, and then we're going to change the message to the generic whose name or password is incorrect given this white space. See if that so you see here that if the passwords dawn match saw the passwords not the same as the one that was originally said in the database we update that user logging attempt. So this is how often the password lockout work, You know, you use the wrong password. It increments that enough to so many attempts user account gets locked out. So it was set that and then was sent our response back. So the next thing we need to dio so we'll see the password doors match. So, you know, we're progressing through the log in steerage here, off the all this. Is it visible to the client? This is just sequential cord that runs does your checks and longer in basically So that's all of the last check we need to do they The next thing we need to do is now create the access talking and the refresh talking. So to do that, we're going to generate some random text or, you know, random, random characters to then return to the client because the access talk and doesn't know it doesn't mean anything. It is just random characters. So the first thing we need to do we're going to use a function called open SSL random suitable PS mixture, spellers, Waksal's but wrong you to your yet that looks right bites and we're gonna generates the cut , you know, is the value that is 24 bytes long. He can create this. You know, I wouldn't say as long as you want. But within reason, 24 is a good you know, good starter. It makes it, you know, quite a big access talking. Anyway, I would probably leave it at that if I'm being honest, so we'll use open SSL in the score. Random underscore pseudo underscore bites. This is an SSL command or been SSL on. What this does is generate you, you know, random characters or London biter shirts. It's not really characters at this point securely saw what this will do. It will just make sure that it is value that hasn't been used before that sort of thing. It has its own algorithm to make sure that it is securely generated and still some sort of value for you. But because it's bites, we need to convert that to Hexi Decimal. And then we need to be a 64 in cord that to give us a character string that we can pass in and out in. You know of any http head of request, because in the end, that's where we're going to use this access talking. So the first thing we need to do is converted to hex decimal, so we'll use the been two. Sorry, it's to Hex. So we'll wrap this function in that. So that convert binary, which, because we're dealing with bites, that's what we're doing to Hex A dismal. And then, in order to generate some, you know, readable characters for us. Um, like, you know, a cord. We we wrap a lot in a beer 64 in court, and this allows you to pass, you know, passages in html Header uses. Sorry. In http header uses valid characters. You know, nothing. You know, nothing strange. Nothing massive. It just creates a nice Stringfield used in passing any http had a So now that I've got that , the next thing we need to do, which is something I always do, we'll take the scenario of, you know, user has an access talk installed on their client device. Now, that should be somewhere secure on the device. And your client is responsible for making sure that value is secure. However, if the user has not used their device in a, you know, a long time where potentially someone else in the system may have that same access talking now we put a unique clause on the access talking in the database. However, if our access talking's changed or expired and you know it's good practice to remove sessions that haven't been used or you know have expired on the refreshed organs expired. If someone's got what's called a steel talkin sitting on their device. Andi, in the chance of This is Heaven is really, really, really it's to be honest, it's probably not worth worrying about, but to make sure this is guaranteed to be unique and that no one else can have this access talk and stored on their device. We priests Sorry. So fix it with the time. So we at the time, onto the value that's returned so you might get something like, I don't know. You know, something like that returned. We then add the unique time onto that on the time function. Is Theo the E pop court or, you know, numbers basically the UNIX time from 1970 on to the end of that, so every seconds that will increase. So the chances of having a stale talking that matches somebody's random, you know, randomly unique talking in the database because obviously our sessions now being cleared so someone else could potentially which, like I say, we never really happen but could potentially have that same talking. And because I was a steal on the device because the user hasn't used it or open the app for , you know, 30 days or 40 days or whatever potentially, you know, someone else might. The system might have generated the CME cord for a different user. So to guarantee uniqueness, we always put the time on that. So just give it a, that is. What we'll do now is to see if this in the variable. So we'll call this access talking and then semi cool on at the end, so we'll convert. Not so. That's 26. DELETE - Delete a Session [Log user out API]: in this video, we're going to implement the law Gold session functionality using the delete http method against slash sessions slash session I d route. This is the route that will be used when a user clicks or taps the log out button on their client application. So let's open, Adam. And this is where we left off in the previous lesson. So if a school backup we're in the sessions dot PHP file a school backup and you can see near the beginning where we created Thea Outline for the slash session slash session I d route. So the first thing we need to do is fold up the empty one because we're finished without now. So I fold it up just to make it a bit easier. Sorkin see where we are create some space here because we're going to be dealing with the session I d. So the roots for this will be slashed. Sessions slash And then obviously an I d. So it could be five or three. Something like that. In this lesson, we're going to be dealing with the delete session, which is a log out. Just remove that. So the first thing we need to do is to get the session i d from the U R L So we'll stall out in the variable. Call it session I d. And then we'll use the get global variable on. It will be session i t. So now that we've got the session, I d. We need to perform some validation checks. We need to make sure that it's not blank and that it is a new miracle number, so it can't be text. So for creating if statement, the first thing is the check if it's blank so session i d. And if it's equal to Blank or if it is so if it's numeric. But if it's not New America, so on, then session I d. And then we're going to send here standard every response back. I'm just gonna copy this one. Paste it here. So change of state is called It's 400 because a client hasn't provided a correct session. I d. And then we're gonna change the error message. What will do here will do the turn re operator. So we'll allow us to return multiple errors back. So, like we've done in the previous lessons, So we'll just do these checks now. So for two session I d equals and then blank, then we need to send a message back. So this copy that piece that in there actually will remove that. So I don't complicate matters, and then we'll change this error message to be session. I d cannot be blank, get out of the seven. Cool on and put a normal call on and then false. So what we'll do is copy that piece, that here and then we'll just change this or it's not numeric session. I d get this. So if it's not numeric and then we need to see session, I d must be America. Okay, so that's that chick carried out. The next check we need to do is on the access talking that we're going to provide in the http request them Hedda's. So when we send a request, we will include the access talking in the http request. Headers, not in the body. This type, it actually goes in the headers. And we'll show you how to do that when we're test this shortly. So we need a performs invalidation on that He is a little fix. We need to do in the HT access file, which will explain later on. But basically the patchy, which is the Web server out. The box does not allow the authentication http request header to be sent. So we have to enable that explicitly. Now, whenever the documentation of basically sees for security purposes, it's turned off by default, But he is valid reasons to use it. You know, this is a valid reason, so we'll be turned it on later on in this video. So how we get this authorization header is to use the server global variable for http on the score authorization. So that's what we're gonna do. We're going to make sure that it is set So it has been provided and that it's not blank, basically. So it's, you know, it's greater than you know, zero characters. So we'll do that now. So, um, so we need to do if it's not set. And then we used the server Global variable. Aunt, it is http Authorization. It was great spear. So we'll see what we're doing. So if that's not set or if it, um, server http authorization and then we'll see if it's less than one character because it should always be creator than one character or one character. Both. To be honest, it should be, You know, more than one character, because the access talking is quite big. So create that. And we need to do your response or copy this one because it's half set up for us and will pierce that in there on. And this one will be. This one's gonna be four or warn error because the 401 error means unauthorized or the authorization talk and hasn't been provided yet. That's what the documentation Sears So 401 is what we use for this. The attorney operator for the messages were going to send back is basically these here. So these are the checks or just change just at the beginning. So we'll do is set. Okay. And then it is a server. And then it's http authorization. So if it's not set, we need to send a message or out a message that is access Talking is missing from the header on the next check we need to do is the length of it. So it would change this one here and s t all Lynn and then it is in the school server. And then it's http authorization, and we need to see that is, um hopes less than one, but less than one. We need to say access. Torben cannot be blank. That's the second bitch off. Validation were performing there. So if its past that validation, we need to get the value that's being passed in in the http authorization header, which is our access talking. So we'll start an invariable access talking equals server http on the school authorization . So that's how we get the access. Talking from the authorization http. Head up. And the next thing we need to do is to check the request method now, in this route here, so slash sessions, slash session I d. We're going to be able to deal with delete andi patch. They're the two that we're gonna be able to submit to this. We're not bothered about. Paused because paused handle in the slash sessions route. So we needed to create the place all this year using the if statement. So if server on its request method and we need to see if it equals delete, then this otherwise so else if server request hopes request method equals patch because that's the other one we're gonna deal with in the next video, which will be used for refreshing and access talking. Otherwise, we need to send a standard ever back so else. And then what we need to do, we're gonna copy this one here. Copy this because it's just an error response gonna change the court two or four or five, which has method not allowed. And then success is false. And then we're going to get rid of these because we're only gonna send one message back, the response at message and the message is going to be request methods not allowed. Okay, so you can either send the delete or patch. So we're not dealing with patch in this video. We're going to deal with explicitly, you know what elite? Because that's what logs out to use a session. So let's create some space under delete. So I need to do is to attempt to delete the raw or the session out of tbl sessions where the session I d on the access talking much. We're not gonna be bothered about checking if the access talking's active, because we are actually looking out, we're not doing anything. You know, modifications to any deer that belongs to Ross. It is just looking out a session. So as with every database query, we're gonna run this between a try and catch, so try and then catch, and they will be pidio exception. And then the X and what will do here? Just gonna get rid of that White Spears. What will do here in the catch is to create our standard response. So just copy this one, and then Pierce that there, we'll change that to a 500 error because obviously, something's gone wrong with a query, you know, some sort of database error. And then we're gonna change the message to their waas on issue logging out. Please try again. And then within the try, we need to write the query so clearly and sorry, that's wrong. Query equals right db, and then it's pre here. And then we're going to write delete from tbl sessions where I d equals the past in session I D, which will add in in a second. Andi access token equals in the past in access. Talking within the http request had a just talking and then we'll bind the promptness or Queary bind. Haram. So the first warning is session I d obsession on I d and that waas the idea that we got from the session idea here. So session i d that session i d and it's PDO hopes Haram Indigent on Queary find Haram. And this is for access talking on and hopes on that access to organise the wall. Never received in here from the authorization http. Had a that was stored in this variable access. Talking on this is gonna repeat your Parham string. So now we need to try and execute its or Queary execute. And then we need to check the rule count. So rule count equals Queary roll count. So for do If roll count equals zero, then basic. This means that for the past in session I d on access talking, it's still managed to delete a roar. If it has to lead a rule, the rule can will be warned. However, if someone tries to, you know, log out of a session with an access talking that no longer exists or is invalid or they've just tried the look to the longer random session out. This is the hard life, all that era. So copy this response to save a bit time pierced it in there, and this is going to be a 400 error, and then we're going to change this message to feel too log out off this session using access talk and provided. So it kind of means that if the session does exist, you've used the wrong access to organ or the session may already be locked out. That's all that is. However, if if that raw count is one, that means that we've actually logged out with deleted the session. So we just need to send a response back to see, you know, you've successfully logged out. So the way we do that is used the return, dear. There don't obviously this In the previous lessons turned, Eder rear returned it. Uh, and then all the kind of going to return is the session. I d off the logged out session. Your session I d. And then this will be will make sure that it is an in the jet because we want to return an integer value back so so sexuality. Because if we look up here it doesn't really know what it is. You know, it might be text. Haven't really said. This is an imager at this point. So we want to return the indigent told to school down, so we just wrap it in the in felt So now what a naturally to set up our, um, response or response equals you. Response response. Set. Http. Status cord. This is gonna be 200 which is an all clear message because everything worked and then response set success. This is true response at a message. Then we're going to see Lochte out. That's fine. We need to set the return. There s or response and set. Did, uh, on that is that you return theater and then we need to send Never need to exit. Okay, we'll get rid of this white space tidied up a little bit. Okay, so hopefully that should work. I mean, we need to change the HD access file in a moment, but I'm just gonna quickly run through this or session. I d make sure on that route. Get the session. I d do some validation on the session. I d make sure it's not blank on that it is numeric. If it's not, then created a standard error. Try and get the http authorization head Earth Chord, which is our access talking that we're going to provide deuce validation or not Save it in a variable check TOC which request method we are using. We're dealing with delete in this video. We've created the school down. We've created the one for patch which will be done in the next video. Go back up to the top. Well, then try the database query, which is to delete from TBL sessions where the idea is the past In session I d on the access to organise the past in access talking. We'll check to see if it's successful, deleted a session. If it hasn't, we send ah response by to say field to log out of this session. Otherwise, we return the session idea the logged out session. So the client could, you know, if that's recorded the session that could clear that down. So now that we've done natural goto HD access file, which is there on, we need to create a route for the next one. So first of all, created here. So we will rewrite rule and it's gonna be sessions slash. And then all we're going to do is copy this format here. So brackets and then it's square brackets. And then it's not to nine. And then it's a plus. And they were going to end the regular expression with a dollar sign and that is gonna mop , too. Controller slash sessions, Doc PHP. And then it's session I d equals dollar one, and that is the last one. So we'll see if that that's what we're doing here. Is picking up the value after slash sessions slash which will then be a session i D. Which is in number that is going to map to controller slash sessions dot PHP, which is the file that we're currently using and then session I d remember the check for that that we've done in this file but school up slightly too far. So make sure session I d exists and get that value in that hour session. I d. Well, that session I d maps to this in the value is the value passed into the URL for the route. So the next thing we need to do is to do the fix for the authorization headed because, obviously, like I mentioned, a party disables that by default. So we need to enable it specifically for our use. And the way you do that is to right at the top. And you do set an environmental variable saw set E N v i f. And it's for the authorization you teach or our eyes said a T i o. M. Then what we do is dot plus and then each TD pay on the school. Authorization equals and then dollars zero. So we'll see if that Sobieski all it's doing is if it's sort of if it's passed in and then we're gonna use that. And Muppet to this header appeared to Peter pick up from that's all. The fixed does like to see a party disabled by default. And if you do want to use that, you just have to enable it like this. This is important that you have this in here. Otherwise, when we run our tests next, if you didn't have this Corden, it wouldn't pass the access talking in. So this is important tohave. So what we should be able to do now is to test this now for open postman. What we're going have to do is actually try a log in to begin with to get a session on a session I d. So if you do a post so each TDP local horse to port idiot it slash b one slash sessions and then in the body on the roar we need to set application Js on. We need a pass in a user name and password. So the using him if you remember the user that were created, so use a name. Waas Michael on the password is password 123 I think I created us. So if I know send that what we should get is a log in and an access talking. So you see that I was session ideas too, And that's our access talking. So I just quickly go back to PHP. My admin go into the sessions table, go to browse. You can see that was our session from the last video that we created. To be honest, we can actually delete that just toe make things a bit easier for us. So this is our new session. So you see there tell a session I d. That's our access talking. So what we want to do is actually log out of this session. So if I go back to post mine, I'm just going to leave this home because I'm gonna need these values, create a new request. This is gonna be a delete request. And it's gonna be http local coursed port idiot. It slash everyone slash sessions. But now we need to provide the session. I d remember going back to this one. The session ideas too. So it's slash sessions slash to so if I just send that No, you can see here that I've got an error in the sessions file, So if a quickly cause going double check that So it saying it's lying 25. So I'm going to hear called 25. You have made a bit of a table there, it actually is. Underscore, numeric Andi, I'll just double check this one as well because I've made the same mistake there. Yeah, that'll looks fine now. Saw it was just cause I made a bit of a type. Also is underscore numeric and just mitri changing the tune re operator as well for the message. So see if that go back to post mine and we'll try it again. So you see there because we haven't provide an access talk and you can see access talking is missing from the header and access talking cannot be blank. So there were two messages that we pushed in. So for one or authorization required, so it means that we haven't actually provided any authentication yet. So now what we need to do is provide the access talking. If we go to headers on the access to organ will be in the authorization. So authorization. That's what the header is called for The http. So now if I send that so it's it says it's missing because it you know it's not there. So if I quickly go back to this request up here, copy my access talking, which is that one there. Go back here and pierce that into here. So you see that? That's our access talking. It's in the authorization request. Http Header So the send that do you see now we have been logged out and we get data for session i d the session idea that we've logged out off. So now if I could appear to be my Artman for hours or refresh that. You can see we don't have an active session anymore. Have actually locked out. So if I just go back to Postman Andi, go back to the log in. We'll just send that again because I want to create a new session. So we've got a new access talking. We've got a new accent. Sorry. A session Ideas. Well, so now we're on session 93. So I'm just gonna copy that because I want to show you that the validation for the access talking is working. So go back tro delete Change the session I d to three. Because now we've got a new session. I d replace this value for the authorization accessed organs will put in our new one. And I'm just going to make a modification that this saw will see change the uppercase m at the beginning to a look. It's him. So now, in theory, this access talking me, you know, look the same. It might easily be missed, but this has just proven that the validation on over case and lower kiss is working. So what we should have here is an error message returned. So what feel till, like, out of this session using the access talking provided. So that means that our access talking is incorrect. So they changed Outback to an M. And just before I delete that score, do PHP my admin browse. That's our session that we're going to veto leading, which means logging out. Go back to postmen and submit that. See, now that I've logged out again on we've got a session idea of three. So that's our previous session. I d go back to PHP my apartment. Refresh that, and you can see that we no longer have a session in that table. Okay, so in this lesson, we went through creating the functionality to log out to use a session using the delete http. Request method in the next lesson will be learning how to refresher talkin wanted to expired and for that will be used in the slash sessions, slash session I D. And using the Patrick request method, you will see in the video 27. PATCH - Refresh a Session [Get new access token API]: in this video will be implemented, the functionally that will allow a client of refresh and access talking when it's expired or just before that expires. This will allow the client to get a new access talkin that would be valid for the next 20 minutes. Within this functionality will be performing a check on the past in refresh Talkin. This has passed in in the request body using Jason Format to make sure that the refresh talking hasn't expired. If the refresh talking has also expired, then we won't be able to refresh the access talking, and the user would be required to fully log in again. This is what makes talking based authentication very secure. So if we go back to Adam and we're in our sessions, no PHP file, what I'm gonna do is fold up the delete logic. So we've just got the patch one exposed, so just create some white space there, so we'll see where we are and then talk it through what we're gonna do here. The refreshed organ will be passed in using and the Jason body, so we'll also require the access to organ and that is stored within header and we've seen that in the previous video. That's all still relevant. And we do our checks on that within this route. Anyway, so that's already handled. Will get the session. I d would do the validation on the session. I d will then get the authorization access. Talking from the http header would do obviously the validation on that, Obviously, Then it decides which route were taken. The last one we looked at logging out, which was deleted. But this time we're looking at refreshing. So the first thing we need to do is to check that the content type is, you know, gs on. So if and then we'll use theseventies Global variable and then it's content type. And that's application slash gs on hopes. And if it's not sorry, that should be. If it's not application, Jason, then we'll send in every response back. So we'll copy this one here, pasted here. The 400 error, because the client hasn't supplied the correct header on will change this to content type header not set two gs on case a little first check dune. The next check we need to do is on the theater itself to make sure that the refresh talking exists on that it's not empty. First we need to do is to get it so raw. Patch data equals file. Get contents on it. Waas quotes PHP input school down and then we check to make sure that the data that's being passed in is injurious on format. And then it apologies on. So we do. Um, Jasan did treatise on discord on Rule Patched theater. So we've done this previously. Would try and record the raw data that passed in. If it's successfully Jason, then this will be valid or true. If it's not, follow Jason. The Jason did cords returned false. So checking for false Well, then copy this error handler, which is our response here. And that's also 400 error message on the message is content. Um, actually request body is not valid. Yes, on So then, if it is biology song, we need to perform some checks to make sure that the refresh talking has been provided. So another if statement. So we'll do, if not set on gs on data Hopes looked in the Robitaille gs on data on we're looking for refresh on the score talking. Create some space here. So if it's not set or if, UM S t all Len Jason did there refresh on the score talking it is less than one. So if it's if it's blank, then we will send ah, never response back. So copy that one piece that the to 400 message on Because we're doing two types of checks here. We're going to use the term the operator again to, um at the message where it's relevant. So we need to do this one. First of all, so is not set. Jason did a refresh talking, and then we need to put in our that message. So I'm just going to get rid of that because we're moving it up here. Otherwise, false will change his message so it's relevant, and we'll see refresh talk and not supplied. So I want a copy this test that below, and then instead of is set. We're going to do string length, and then we're going to say less than one. So if this passed in refreshed token is less than one in length and it's blank, soldiers say refresh talking cannot be blank. We'll see if that okay, so that's I would checks there. We'll move on to the next part, which is to we need to now create some database queries on so we'll need to create our try and catch demand. First of all, try catch and that PD your exception cause to do with a dead Bierce and then for the cops statements we need to handle incur response soldiers pierced one. And here it would be 500 error message because it's a server error or potential server era . And then the message would be there. Waas on issue. Refreshing access talking. Please try again. Um, actually, it will be pleased. Look in I can get to the white space, create some space here so we'll see what we're doing. Case. So now, hopefully our validations all past were no need to grab this refresh talking and store this in a variable. So that's what we need to do here. So, brie, fresh talking on will get it from Jason Delia Refresh talking. So we'll see that invariable there. And then what we need to do is create a database query to bring back It's not just from one table. Now we're no need to join two tables up, which is TBL Sessions and TBL users. The reason why I would do in that is we need to bring back the session details to validate the refresh talking and access talking and things like that. But we also need to bring back the users raw or the user details because we need to perform . Our user is active on day lockout attempt because these are still valid. If we want to refresh the talking, we need to perform them validation checks in the periods video. We weren't bothered by when we're looking out. We're not bothered if a user is active because all we're doing is actually logging out of session. We don't want to prevent people from logging out. If anything, it's safer to allow people to log out based on just a you know, Amelia and expired access talking or something. So we need to do here now is create the deer to be is query to perform our link, or I would join between the table and return all of the required user details back. So what we're gonna do is create the career e So queer Eagles Rights db prepare and this is going to be fairly long sequel query here because we're bringing back quite a quite a bit of details here, So we need to do select. So because we're bringing back an I D. Both tables, TBL sessions and TBL users do have an i D column, so we need to specify explicitly which table we're talking about and how you do that is tbl sessions dot i d. So that says, bring back the I. D column from the TBL Sessions table, not the users table. And we'll give this an alias off as session I d. The next field we need to bring back his user i d so will be explicit here about tbl sessions. Dr. Use that I d just so we know. Actually, when we're reading this where it's coming from and we'll give this nearly size user i d. The next field need to bring back is the access talking, the refresh talking and then user active. Blufgan attempts the access talking expiry, the refresh talking, expiry refreshed, open expiry yet and then from tbl sessions and TBL users. And then we need to link the two tails together. So we do aware tvl users dot i dy equals tbl sessions dot user I d remember, we're not Lincoln a session i d to a user i d. Because the two things are different within the sessions table we had we store a user i d and that links to the tbl users dot i d, which is the unique auto increment ing i d from the user's table. So the next thing we need to put in the condition is where so we need to do and tvl sessions, Doctor, I d equals a past in sessions idea because remember, would do in slash sessions slash i d So when they need to put a placeholder in here for session I d and the next thing we need to do and tbl sessions dot access talking equals the past in access talking Aunt tbl sessions dot refresh talking equals refresh talking. So that's how a sequel query. It looks quite long and to be honest it is. But all we're doing is joining the two tables together. So we're gonna link procession i d with the user. And then what we're gonna do is try and search for a session that has the access talking that's being provided, the session idea that's being provided on the refresh talk. And that's being provided. Just all three things have to match before it finds a validation. So we're now buying these parameters. So will be Queary. Find Parham in the 1st 1 waas session. I d session I d on this waas session. I d Because we get this just up here school up. They would go. So get the session i d sold out and that is PDO Haram Indigent. Next one is Queary Change. Haram. Oops. And this will be access talking look. Well, buying the parameter for access talkin That's his PDO Haram String on Queary find Haram. So we'll get rid of that. And then we'll put in refresh talking, re fresh talking on. And that is pidio Parham strength. So a person in the session I d, which would get from the U. R. L or the route will get the access talk in which we get from the http request header, which is here from the authorization request header. And then what we're going to do is get the refresh talking and this is passed in in the request Jason Body. So this is where we do the GSR name court. Sorry, D accord. And then we get the refresh talking. So now that we've done that, we need to do a raw count. So rule count equals Queary. Rule count. We need to do an if statement. So if rule count equals zero, then this is going to be an error. So we're gonna copy this response because we need to send a standard ever response back and this is going to be a four or one message, and we're going to see access talking or refresh. Talkin is incorrect for session I d. So we'll see if that so. What we're doing here is checking to make sure the past in session I d. Access talking and refresh talking, talking all much. So for this given session, I d the access talking matches on the refresh talking matches. We're not bothered about it being expired at the moment because all we're doing this to make sure that there's a session they that has the CME access talking is the past in access , talking in the same refresh, talking as the past in refresh talking. If it doesn't then send our 41 unauthorized every response back. So hopefully we will have a rule there now. So what we need to do is bring back that roar. And obviously this brings back quite a bit of theater. That's why we've had a link both both of the tables. So if we save that in raw normally, this would be in a while statement. But we know we're only gonna get one roll back because you can only have one session that has the same access talking because it's unique. So we will use Queary, and then it's fetch. And then it is pidio fetch associative Arria. So now what we're going to do with save these values from the sickle Cleary into variables . So we're just gonna call. He's returned on the score session. I d session on I d. On This is rule and then it's session I d. Because that's what we call the alias. Appear there. So session I d. So we're going to do this for each column that we returned back So returned user I d so rule and this was use a righty and returned access talking call an access token hopes returned Refresh talking refresh talking turned, um user active use that active, returned Morgaine tempts four loved in attempts. And then we get the to expiry because they were the last two columns We returned tops returned. Um, access talking expiry. Okay, Just talking. Expiry on returned refresh talking expiry the refresh talking expiry. Okay, so we'll see even all of the return columns from the sequel query into variables because we're going to perform some checks, such as Is the user active of the log in attempts greater than equal to three. And then obviously, we're going to check that to me. You know, the returned talking expiry from the database and hasn't expired. So we need to perform some of these checks now. So if we do, if we will check, is the user active to begin with? So is return to user active equals two? Why sorry. Equal. Not equal to a why Then we need to send a never response back to copy and pierce that. So we're going to see it's a 41 error because the user is not active. It's an unauthorized on. The message for that is user account is not active and then the next check we need to do so . I'm just gonna copying Pierce this because actually very similar school down a bit instead of user. Um, sort of is active. We need to check the returned Logan attempts on We need to say, Well, if these are greater than or equal to three, then you know the accounts locked out. So it is still a 401 and they were going to say user account is currently locked Groups out . OK, so that's our basic checks there. The final check we need to do is to make sure the access Sorry, The refresh talking hasn't expired. That's what we're gonna do. School down so another if statement and will be using a function called String to Time. So the obviously the my sequel database returns the time on we need to see so str two time take a date and time them convert not for a time. So string to time and returned refresh talking, expiry. So we need a work there cell to string to time. So if it's this time so the time stored in the database is less than the current time. That means it's expired because if the time in the database is a future time, that means it's still active. So we're seeing if it's less than time, then it's expired. So we're going to cover this every response. Here, paste that there. 241 error on. We're going to see Refresh talking hoops has expired. Please lock in again. So once the refresh token has expired, it can't be used. You most looking again that you only see if we're to do because otherwise you would potentially have a refresh talk and that never expires. So if I ever did get leaked doors, you know something happened, then they would have permanent access to this user account, which is not good. So now that's our checks are done. We need to regenerate an access talking a new one obviously said a new expiry time. But also every time you get a new access talking that also comes down with a new refresh talking, we need to generate the access. Talking on the refresh Hawkins now be used exactly the same method we used when we first created a session which is to use the or been SSL random, suitable bites on Generate basically a random string, so we'll be using exactly the same thing. So it was access talk and equals on. And then it was open SSL random, suitable bites. And then it was 24 bites, 24 bites. But then what we need to do because it's buying a really we need to convert it to Hex, and then we need to convert that to be a 64 in court. So we'll being to hex open the bracket, close the bracket, But we need before we convert this to be a 64 we need to so fix the time on the end to guarantee a total unique access talking. Obviously, I went through all this with steel talk ins and stuff in a previous video, so I don't need to explain it here so we'll just have the time. And then we need to convert all of that or in court that two BS 64 to make an intra usable format for us case will be 64 groups in court. Been to hex. Yeah, so that's fine. That's an access to organs, so I'm gonna copy that. Just underneath it pierced it again and call this refresh talking because it's exactly the same formula were using. Missile guarantee is too unique. Hawkins. We now need to set the times on this or the expiry times or access tour in expiry seconds equals 1200 it's on and refresh expiry. Yet on this was 1.2 million wasn't sorts 12 or 9 600 So that Ford India's on 20 minutes, it's another have said that's what we need to do is create a database query to update our current session. We don't create a new session here because we have one will refresh and access talking for this current session. So if we create the database queries or query equals right debate pre pair on the sequel query here, What we're gonna do is update tbl sessions and then we're going to set. So in that in that table we're going to set a new access talking a new access talking expiry, which is the current time plus 1200 seconds, then a new refreshed organ and then a new refresh talking expiry time. But it's where the session I d equals our session I d to the past in session I d on the user. I d equals the past in user i d that we retrieved from appear And then where the access talking much as the past in access talking Because that's still the current value on the refresh talk and equals the past and refresh talking because you can have multiple sessions or user can have multiple sessions. We need to make sure that we're refreshing the correct session. So this sequel query is going to be quite long. Eso bear withers, I will go through and explain it. So the first thing we need to do is to set access talking equals the blinded want or just placeholders in because we need a pass in the newly generated access talking from appear. We're just setting these at this point, um, Till set access talking. And then it is access talking, expiry. So this is gonna be remember we had to calculate this on the previous video where we created the user session. So we need to do did underscore out, and then we need to get the current time. So that's now I'm just gonna create some Spezia and then it waas interval and then we pass in a place. All this all this was access talking expiry seconds and then give it a definer. So second, um hopes second. So that's the date out for that. And then we need to do refresh, talkin equals, refresh talking and then refresh talking them expiry. And then that was exactly the same as just don't saw this would be DEET art Andi It waas have been now hopes and then we need to art and interval passed in parameter. So this was refreshed talking expiry seconds in second. And then it needs to be where I d equals passed in session. I d. Because we're gonna bind these. Surely on user, I d equals I use it. I t on access. Talking equals access. Talking on the refresh talking equals, please called her. I agree. Fresh talking. Actually, that's wrong. So what I'm gonna do is delete that. Yeah, I think that's right. Yep. If you just believe that on access to organ equals, this will be the returned access times. What's the current value in the database that we just retrieved? Previously returned access talking on and refresh talking equals returned. Refresh talking. Okay, so bear with us on this one because it is quite long. But it's up there in the Sessions table was setting a new access talking and you access talking expiry, which is the current time plus our in developed, which is here toe For the access token. It's 1200 seconds for the refresh talking. It's 1.2 million seconds So and then we set a new refresh tokens and then a new refresh talking expiry, which is the 1.2 million where the current. So we wear the session i d. Until the rule the i d. Is equal to our past in session i d, which will be slash sessions slash five and then the user i d would be the returned user i d. That we returned previously, and the access talking would be the returned access. Talking on the return refreshed talking. There is why I put returned two years because we've already got one called access talking. And I don't want to confuse matters. We don't have one called user I d because that's being returned. We're not, you know, we're not generating a new user idea, so go back and now we need to find all of these parameters. That's quite a lot of them. So Queary find Haram. So the 1st 1 we're going to do is the use of writing. That would be the I have not refresh or returned user I d. And this is PDO Peron. KinderCare because it's a number Cleary Buying Haram in this one would be this session, Heidi, and this one will be returned session. I d. Because this is what we've got just up here. Return session I d. So basically, some of these were, you know, we re using down here in the sequel query and this one would be hopes PDO Haram Imager. So, query find Haram in this one would be the access talking. And this would be, at this point, this would be the new access talking, not the returned one. So, access talking on this is PD or Haram. And it's a string. Queary hopes Baines. Haram, It would be access talking, expiry seconds. And this would be access talk and expiry seconds in there. Yep. That looks fine. I am. And there will be PDO Haram in the Jackal. The turn number Queary find Haram. And this one would be the refresh them Talking hopes Make sure put the call on the beginning. Refresh talkin And then this one would be the new one. So that's refreshed. Organ pidio rahm String Queary change Haram refresh Talkin Expiry seconds. This is the refresh talking expiry seconds. And this is PDO Karam in the job kiss or now we're on to the returns Access talking in the return. Refreshed organs just need to find these plain Haram, this would be returned Success talking. This was 10. Access to open pidio Haram String Queary find Haram. This was returned. Refresh talking pidio Haram string. Okay, so we've found all the parameters that we need. So the user ideas that were passed in, um, user, I d. That we got from the running the query. Just a both copia. So these were the return ones, so it just makes you were talking about the CME role on the table. So I got to see him. Session i d siem user, I d with the access talking and refresh talking much. So it's just a case of quality in the data, really? Just being sure, working on the CME role here. So now the abound. Then we need to query, execute, And then what we need to do is to check the rule council rule Count equals Queary Rule count, then an if statement. So if the role count, um zero. Then we need to send an era back. Copy. This one pierced it here for a one error because there's been some sort of unauthorized ation issue. One of the access to organs is wrong or there's nor session anymore or something like that . Something's happened. So it's unauthorized for this session. So the message will be access. Token hopes cooch not be refreshed. Please log in the camp. Okay, so hopefully for school down, that should be warned. And if it's one we need to send our response back, which has the session i d. The new access talk in the new access talking expiry in seconds, a new refreshed organ, a new refresh talking expiry in seconds. So it's exactly the same response that we send back when we create a session. So when someone logs in, it's exactly the same response that the client gets back consistencies. Good saw where does match up with what we sent back so well to create the return data in order to stall these details. So this isn't a ria return? Did a The 1st 1 was Session I d. In this all equal return session return session. I d. Because this session i d it's not a new one to see him session. So we'll just use the return session idea that were originally queried based on the provide access talking and refresh talking. The next one turned it would be the access talking itself. All this would be access talking, which is the warm that we've newly generated up here on, obviously the time and seconds. So we'll go down and up. He said to return data, um, access talking, expiry three seconds and then return. Deanna refresh. Oops. Talking. I have not turned be refreshed talking on then return data refresh talking. Expiry hopes expiry. This would be, um, refresh talking expiry seconds. Because these are the prominence here. Andi, um, we need to create the new response response set you TDP status court. It's gonna be a 200. Okay, response set success, true response. And then what we're going to do is to add a message and we're going to see um talking refreshed and then response. Set the theater with hopes this is the return dealer and then the response send and then exit. So what we'll do now is clear that white space and to see a bit of a school back up. And we'll just review what we've written here. Start from the top. So I've got the patch. That's what we're dealing with here will refresh in a session. So the first thing that would do is obviously check that the content type is application. Ji Hassan. If not, send an error response back. Well, then get the patch data, which is sent with the request body. And this is basically the refresh talk, and that was sending in the genus on data. We're trying Dick ord it to make sure it's biology. Asan. Save it in a variable. If it is, so, do some checks on this refreshed organ and the jets on data to make sure that it exists. On that it's not blank. School down would then see if the refresh token invariable with an perform is select, which joins two tables together to make sure that we get the session de deals as well as the user details because we need to check that the uses active and things like that. I've just noticed I've missed out execute here, so I'm just gonna put that in. So Queary execute because that wouldn't have worked once have tested it. We'll see if that school down with double check that the years of rule, um should be if the rule is zero, basically that we haven't provided the correct session. I d access talking and refresh talkin. So one of them is incorrect. So we offer scared that by just see an access talking or refresh Torn is incorrect for the session. I d. We don't give exact deals. You know, the access talking's wrong, but the refresh talking is correct. So office scale that well, then get the rule from the database and then we'll see if the details that we need to check in variables so prefix out with returned. So I've got the session i d the user i d, which is the internal user. I d access talk and refresh talk and get the user active and log in attempts. And if a school down, we check that the user is active, so if it's not active, was sent in error. Back to say the use is not active on we check that the accounts not locked out well, then check that the returned, refreshed talking expiry is not expired because obviously a refresh talking will only last 40. India's in our case, so we need to make sure that the refresh talking hasn't expired. If it has expired, then the user will require toe log back in again. Well, then generate our access to organs. So we used the open SSL sued or bites on. Then we so fix it with the time I just noticed that I've actually put the time in the wrong place. So for move that just to one bracket out on the same with the refresh talking because actually we want to upend the time once it's gone to hex, so we don't find the time to the bite. We want to spend the time to the hex to then in court as being 64. Then we generate our expiry times. So 1200 seconds is 20 minutes and 1.2 million is 40. India's well, then updates the session with the new access talking, new access talking expiry, the new refresh token and the new refresh talking expiry. Then what would do is make sure that it has successfully updated the rule. Well, then, create our return data which should return the session. I d the access talking. Obviously these are the new details here, and obviously we get a new refresh talking every time there's a new access talking generated. So we return all of these new details yet. So this is exactly the same response that we get when we log in to the system. So it's all about consistency. So the refresh should be exactly the same response as the log in. Okay, I saw them return the message about talking refreshed. So now we should be able to test this. So for open off, postman, we first need to log in. So http call on and local horse trips forced port it. It it it slash b one slash sessions and it's gonna be a post request because we're logging in first. Before we're gonna refresh your talking, go to body roar and then application Js on will create some GS on here on. We need to supply using them. And the use name was Michael on. We'll need to supply the password and the password. WAAS password 123 So submit that. Well, then get our session I d which is four in this case with Then get our access talking which expires in 1200 seconds. We're then gonna refresh talking on I'm just going to quickly go to PHP my advent and refresh that. So you see now we've got our session. We've got our access talking expiry, which basically is 20 minutes from where we've just created this session. So what I'm gonna do now if you know what this access talking, I'm now going to refresh this and you can see here it's an M y and refresh Talking begins with said WF Now I'm gonna try and refresh this. You obviously used in the end point that we have just created so called about a postman will create a new request This time it is a patch because we are updated in a session to refresh So http local horse supported it slash b one slash sessions and this time we need to put a session idea on the end. So that four in this case, because that's our session. I d here. So we don't create new sessions when we refreshing access talking, it's still the same session. It just gets refreshed. So go back here, Andi. First thing I'm gonna do is just submit that because I want to see to make sure that the logics work and that we've courted into this. So the first thing is asking for is the access talking is missing from the header. That's correct, because what we need to do, we need to provide the access, talking in the header. So we click on headers and then it's under authorisation. Remember that where we put our access talking the http header for authorization. So now let's provide. I'm going to submit will get the CME error message back because it's, you know, it can be blank. So what we'll do now is copy our access talking from when we logged in. So copy that. Go back to this request to refresh, and in the authorization we need a pierced our access talking in this value here. So now that that's their what we should be able to do is submit that, but we'll should get another error. So now you can see that the content type header is not set. Jasan, That's correct, because we are providing Js on court. Teoh, supply our refresh Talkin in the http request body so a bit like how we looked in we need to create a body. So go back to you the patch click on body click on Raw and will set this to application gs on. Just gonna lift this up slightly. Submit this. In theory, we should still get an error message because the rest request body is not followed. It's no follow, Jason, so because it's blank, we will create some Js on body here. So that's an empty body. Now, this is the next check we're doing. This will send that again. So we're seeing the refresh tokens not supplied on the refresh talking cannot be blind. So now we need to create the Js on to have refresh underscore talking and we need to put our refresh talk and inside these court yet so go back to our original log in request and will copy the refresh talking copy that Go back to our patch request and will pierced in our refresh talking. Now this should refresh it s o for go back to PHP My admin remember it was n m y on there to be wife of the begins Onda. Obviously it's 12. 13 was one that the access talking expires. Now we can refresh it now. It doesn't have to be expired to be able to refresh. So will now submit this refresh. So you see here that talking's refreshed when we'll have to see obsession I d because remember, it is the same session will refresh in. But now you can see we have a new access talking and along with a refreshed open. So if I go back to PHP my admin and refresh this page, remember? And am why So you see now that our existence session now has a new access talking on a new refresh talking, you see there the expiry is also being updated. So now this talk invalid for the next 20 minutes. So if I go back to postman Andi, then what I'll do is try and submit this same patch request. But these are all details. Remember these are the deals that we got when we first locked in. So I'm just going to send this again. It should feel because obviously, these are our new deals here. So I'll just send that now and you see their access talking or refresh Talking is incorrect for the session I d. So that part of the logics also working because we're using an old refresh talk and and access talking so that proves that that bit work and find So the next bit I want to test is expiring a refresh talking to make sure that part of the logics working. So what I'm gonna do is quickly go into the sessions and I'm just gonna tell it this. So I'll delete that session there, make sure it's gone so well after logging again. That's not a problem. We'll do that. Now go back to our original log in request and just resubmit that this will create a new session. So Session I d five. And this is our new access talking. So I'm just gonna copy that, because what I'm gonna do, I'm gonna set the refresh request hope, but I'm not going to submit it quite yet, so replace our access talking with the new one andare police replace this refresh talking with this new one as well. So if I go to body on changed that to the new one not gonna submit that yet because I want to go back in to PHP My I'd win. Refresh that, and then you can see it. This is our new session, but what I want to do is actually change this refresh talking expiry. So it's expired. Remember the refresh talking last 14 years from when it was created? So I'm gonna do I'm just gonna make that. I mean, it's a 24th today, so I'm just going to see Well, it expired yesterday. That's fine. Have changed out of 23rd. So now all should get is when we try and patch this session. So refresh this session because the refresh talk and has expired. We should get near a message. Actually, what we've got here is because I forgot to change the patch number here because obviously will create a new seven sort session. I d five now by mistake. So we'll click send again. This should work. So you see, now that the refresh talking has expired. Please log in again. We'll go back to PHP. My admin. He can see here that this is our existence session and you know it expired. So the user hasn't logged back into their device within the past 14 years, so you'll automatically be locked out. That's kind of where I'm getting to with this. You probably thinking, Well, what happens to these rocks sessions in this table? Quite rightly. Because we're not handling these once that expired. Now what you would do on your server, you were created like a scheduled script that would run every day every two days, whatever to clear out any sessions. So delete these session Rose where the refresh token has expired. OK, so that's our authentication. AP I now created we're gonna log in, we gonna refresh the two organ weaken, log out that all we need to do now. Obviously, the whole point of this is to link this to our tusks FBI that were created in similiar videos. And what we need to do is convert that now to look at the user I d saw in the end, we want to just be able to log in and get our tasks that includes, you know, update now ruin tasks. Delete number one tasks, things like that. So at the minute, it doesn't allow you to log in. You know, if you if you get all tasks you just get, you know, a list of all the tasks doesn't matter who's created it or anything like that. So in the next video, we're going toe change the tasks E p I in the tasks database toe handle this new functionality. So we'll see you in the next video. 28. Update Tasks Table - Add User Assignment: Now that we have our authentication FBI set up on working where users can log in and log out. We now need to adjust the tasks table in the data appears so we cannot a user i d against each task. This will allow you to have seen the task to a user. So when our your p I calls get tasks, it will have a context of whose tasks it should return. So the open PHP my admin for Go to the Tasks table N. C. Colonel, you've got I d title description deadline and completed. We need at a new field to store the user righty So recorded users and bro's we need to stall this. I d. Here we do this very similar. In the Sessions table, we were store the user I d. So this is how we link tasks to use us. So for Gorda at one column and we just want added at the end. So after completed click Gore, we'll give it a name off user i d. It was a big in because that's what was stole the user I d. In the year the tables. So if a scroll to begin and then we move along on its mandatory because every task must have a user. I d associated with it now, So we're not gonna take the yellow and not allow knowable. And we're just going to give it a comment so it will be user I d off owner off task thing. That's fine. So the click save on that, go back to structure and you could see now I've got a user I d Tony. To do now is to add a foreign key associated with this user I d field. So this basically means that when it tusks created or added into the database, it must have a user. I d Now that user I d must exist in tbl users. We did this in the sessions, if you remember rightly so the user i d. We can't create a session for ruled user or users that doesn't have you know that that doesn't exist. So that's what we're gonna do in TBL task. So it must be a valid user. But before we do that, what we're going after do is delete all our task out of our tbl tasks table. Because if we try and put a foreign key on this. It default to zero for all of our tasks. Now the user with the user idea of zero doesn't exist, so we want to clearly is down. So what we do here is within tbl tasks. Good operations school down to the bottom and you'll see empty the table. The click that I couldn't take, enable foreign K checks and then just click. OK, go back to Bro's. You can see that I would. Tbl tasks Table doesn't have any tusks in there? No. So now if you go back to structure, relation view and then we'll add in our foreign que so it's task user i d. Underscore Care for foreign key on delete Restrict on update Restrict because we don't wanna be able to delete a user that still has tasks. So column will select user I D databases tusks. TB table is TBL uses cause this is the table that will Lincoln, too. On the column will be I d. So the click see of that's now added. So if we go back to table tasks go to browse, it's empty. We try and go to insert Andi. If we look at the user idea. You can see now that our users in there, you know, we just have one user at this point so that shows at the Lincoln between the two tables is working fine. So in the next video, what we need to do is adjust toe a tusk stop PHP file, which is our task e p I. To take into account these changes. But also, what we're gonna have to do is check for access to organs and everything like that. So we'll do the authentication. And then we'll modify each sequel query and each bit of functionality to take into account this user i d. Because of the minute the way that it's built, he would just return all tasks. It doesn't really matter about the user. It doesn't care whether users logged in or not. So obviously, we'll update that in the next video 29. Add Authentication to our Tasks API: in this video, we will be integrating the user authentication into the task. C a P I. The logic for this will be to perform a user and session check based on the provided access talking. This will be checked to make sure that it hasn't expired, that the user is active and that they're not currently locked out. The FBI will then proceed based on the route that the client is using. The sequel, Cleary's will be changed so that the only performed the tasks based on the newly added user I D Field, which is held against the task. This prevented users from being able to retrieve or modify or the user's tasks. So let's start by Open and Adam and not in the user access talking trick. So this is our sessions, E p I. We're just gonna close that because we're not going to use this anymore, and we're going to open up our task ap I hear. So this the task controller. So what we're gonna do is before it then decides on which route that were taken, we're going to add in the authorization script here. This will be used to check the access talking just to make sure that it's followed it hasn't expired and that the user is valid. So for just create some space here. And I'm just gonna add a comment to see Begin both script. Just so we know what belongs to the authentication side on what belongs to the task C A p I and just be law this, I'm just gonna add another comment to see end or script. Okay, So the first thing we need to do is to get our access talking from the http header which is for authorization. We've done this in a previous video regarding refreshing and access talking, so it will be doing the same sort of check. So we'll first need to make sure that the access talking has been provided and that the access talking, you know, is not just an empty string, just blank. So we'll do that now to school down to sort lifts it up. We'll do the if statement, and then we need to check if it's not set and it Woz thesis ever global variable. And it was for the each TDP authorization header. So if it's not set, but also we need to or str Lynn is less than one, and I'll just added in here. So server groups http authorization then. So they saw a if statement so checks to make sure that the authorization header is present and that the authorization had a does contain a value that is greater than zero characters . So it's not empty. If it's not, we need to set up. I was standard every response so clear that now it's a new response and then responds to set http, steer discord and this will be a four or one because it were not authorized at this point. So we do obviously the authorization check. Before we do any other logic in the FBI office, you're gonna have the database connection created here because the authorization logic will be queer in the database. So we must do the connection to the database of the beginning. So response set success that's false. And then response. Um, what we're gonna do here is to use the term re operator to provide a room Esther's based on . If it's not provided off, it's, you know, if it's blank, so we will do the is set, and then it's underscores. Ever And then it is http on the score authorization. So if it's not set, then we need to response that message. Holmes and the message will be access. Talking is missing from the header. Hopes not form from from the head up. Oops. Too many courts there. But this back in courts, otherwise false. Okay, so if we copy this because the next check we need to do is for the string length. So for just change this or testy all Len and then it is server http on the score. Authorization on if that is less than one. Change this access talking. Oops, access talkin cannot be black case or response. And then we need to send and then exit so handle at exactly the same way. Obviously, we're just checking to make sure the access talking has been provided and that it's not an empty string. Get. The next thing we need to do is if it has been provided, then we need to stall this in a variable. Will call this access talking on, and we will get it from the server. The city paid authorization had a kiss. So we've got that on the next thing we need to do is then perform a database query based on this access talking to bring back the user deals and a session details so we can check that uses. Active on that the access talking and stuff hasn't hasn't expired. This is very much similar to what we're doing in the refresh access talking the a p I where we do some basic checks before we then proceed with the rest of the logic. So we need to create the query hopes Queary spell it wrong again. Equals on because it's authentication will always do it against the right DB. I'll see you think you've got that message now. Pre Hair on will create the sequel query. So we want to bring back the user i d. Because this user I d. We're going to use in the rest of the sequel queries in this script on That's how we a portion tasks to set ownership of tasks to users. So we need to bring back the user i D. Based on the provided access talking, because we need to make sure that the user I d matches throughout this the rest of the logic. So, user, I D access talking, expiry user active on looking attempts. And then that's from TBL sessions on T B l uses uses where tbl sessions dot user i d equals tbl users dot i d. Because we need a link the two tables to make sure that will bring back the right user for the you know, the access token that's being provided. Aunt Access talking equals, um, access talking. So obviously that's a place all that no need to bind the parameter Sor Queary find Haram on it will be access talking. And this will be the access talking that we have received in because you need to do the check on the one that the users provided on. This is PDO Haram. It's a string. So now for execute that Cleary execute, we need to do a raw count because they still see well, the, you know be is no user or session for that access talking that's being provided so someone provides an access talk and that's not valid doesn't exist. This is the era. Handle here for that. For the rule count sold the rule count, quotes Queary and then on his rule count, normally do in if statement on that sort of raw account equals zero and what we need to do here is to send a response back. So I'm just gonna cover this one. Appear to save some time pasted in here. Andi, it's still gonna be a 401 error because we're unauthorized. You've providing access talking that's not followed. Success is false, but I don't need to wear a masters. I just need one. So I'm just gonna get rid of these territory operators here and then just set a message, because that's what you want. So our message groups on we'll see invalid access talking. Okay, so that's the first men check, really To see if the is a session for that access talking. So if he is, we need to return everything that we have retrieved here because I need to perform some checks. Like I say, we're going to use that throughout this anyway, Obviously, we need to check that the access talking has a you know is still valid. We're not really bothered about the refresh talking at this point because I'm not handling Nash. That's what the authentication FBI does when you check that the uses active and that they haven't exceeded the log in attempts. So if we return and the rule saw rule equals Queary, fetch. Oops. And then it is PDO Fitch, associate of a rear. So we're returning one raw because the only should be one rule for an access talking because we put the condition on the database to see if they can only be one unique access talking. So we'll bring back the rule. Were no need to see if the details that would get from the sequel query invariable so can use them. So returned user i d not from the rule user. I d and then returned. Um, What was it? Access Talking. Expiry. That's that is from rule access talking, expiry on the next one. Was the user active So it was use active? Yeah, And that was from the rule. Thieves are active. Returned Blufgan attempts from the rule looking poops, looking attempts. Okay, so no need to do the checks for user active to begin with, So we'll do that now. So do if returned user active is not equal to why hopes And then we need to send back a response. So copy this one. Um, it's for one error. That's correct, because there's an authentication issue and we'll change this to user accounts, not active. That's okay. On the next check we need to do is to make sure the log in attempts is not equal to three or Greta. So we do not know if returned Logan attempts is greater than or equal to three. Then we're gonna copy this response again for one error, and then we're going to see user account is currently locked. Act. Okay, So the final check we need to do is to make sure that our access talking is valid so that it hasn't expired. So school down on Differ, do if and then we're gonna need to use string to time and then compare it with the current time. So in one of the previous videos, we done this very similar check for the refresh talking to make sure the refresh talking walls still valid. As we're trying to refresh the session this time, we're going to be working on the access talking. So we're gonna obviously use this against the access talking this time, so str to time and then it is returned access talking expiry. And if it's less than the current time, then that means it's expired. So, for copy this and pierce this response here, Still a 401 error. Um, and then we just change the message to see access talking expired. Now, if the user does get this a Z use now e p I, then that's when they then have to submit a refresh talking to get a new access talking. So this is the response that the client will get once, you know, once the 20 minutes is up for the valid access Taurel then have toe call the refresh your P I with a refreshed organ to then get a new access talking to be to be able to still continue using this. Okay, so let's have a quick check it This all right? I forgot something here because we're doing a deer to be is query. What? Haven't actually put it in our try and catch damage, So try scared of this. We just need to put this in our try and catch, so I'll just in dent this slightly. Um, just go down to the and then we'll in dense. Oops. Um, yeah, That should be fine. Okay, so at the end of this script obviously will start. I will try at the top. They we need to end. I would try after this string to time checking the access talking, and then we need to perform the catch, which is PDO exception the ex cops. So forgive me for that. I just forgot. Added in there You think I would know by now, after all the database queries have carried out? Um, so in the catch statement, what would need to do is send in every response back if there's ever a database problem on , um 500 era, because obviously be in some sort of server issue and then change this to there. Waas on issue authenticating. Please try again. Okay. And that sends that that. Okay, so I think that is it. That's the beginning off the authentication script. So first of all, we are double checking to make sure the authorization or access talking has been provided in the authorization http. Header that it's not blank if it is were sent an ever response back. Well, then get the access talking, See? Even in a variable will then perform a query, a sequel query on TBL sessions and TBL users. We'll link the two tables together based on the user I D on would check that the access to organ the one that's provided is, you know, that matches to use a session when I bothered about being expired at the moment, we just want to make sure that it's much as a user session. If Theisen recession that is much, too, that access to organ would provide back invalid access. Talking in the script ends. Otherwise, we get the rule from the database, which has the user idea in, because we're going to use that in a second. And then we get the access talking, expiry, the user active in the log in attempts because now we perform these checks here so may actually uses active. Make sure the log in attempts under the three. Because once they hit three, then the locked out and I have to be manually unlocked. Well, then do a check on the access talk and expiry to make sure that hasn't expired. If it has expired, we send back on our response to see access. Talking has expired, and then, obviously was gotta catch statement the bit I missed out before. Okay, so now that we've got that bit, what we need to do is for each of the sequel queries for each of the roots that's in the rest of this script. We need to just make sure that each warn is taken into account the use a righty. So we're not doing any further checks on that. All we're going to do is update the sequel queries because at the minute, what's this one? This is just This is getting a single task here. So we're providing the task route on, gets to get request. So we're just getting a single task. Now you can see here we return the testy deals based on the task I D. So if someone knows the task I d, then it's just returned. But what we want to do is add a for the condition to the sequel queries to see Andre, where user I d. Is the same as the one that much as the access talking that's provided this will stop people from trying to guess task i ds that they don't have access to all that, you know that doesn't belong to them. So which is gonna with through this script here and just update this as we go? So, like I say, this 1st 1 here is to get an individual task based on a task I d. Because it's under the get request. That's all we're going to do. Is school right to this on what it says on ID equals task I D. Which is going to put a further condition to see on user I d equals Clearasil, the user i d. So it's just come, you know, constricting. That's that's equal creamy down. So because we're provided another placeholder we need to find available to that here. So after Tusk, I d. We will create another query. Bind, Haram On it is a user I d. So like a seer. We've already retrieved the user I d. Based on the access to and that's being provided the school appear. Obviously we're doing that check here, so we need to use this this value that's stored in this variable throughout this script. I'll school down to use your i d. And it needs to be returned. Use a writing hopes and that is a PDO Haram in the job. So that's the first endpoint or root adjusted to take into account our users. So what we're gonna do is just scroll down. We don't need erupted it any any models or anything like that because the user or the client is not interesting a user i d. This is only internal to the system. The user is normally just aware of their user name, which is either an email address or just, you know, a general unique text court for something like that. So we don't need to adjust our model to perform, um are to allow the user i d to be stored is a task or anything like that. We literally just using this for validation in the back end of the system. So what we're gonna do is just scroll down, thes this court here and just double check where there's a sequel query so I'll just keep school and down. So this one here, we're working on the delete, so this is to delete a single task. So you see here that this this sequel query here is very generic. If you've got the task I d. That means you can delete it doesn't matter if it's yours or not, it will just delete it. So we need to constrict this slightly on Just put on user I d equals use a righty, and then we need to bind us to the query. So, Queary find Haram on it. Waas User I d And remember, it is three returned user I d on that. It's PDO Haram indigent. Okay, so that's the delete one now modified. So it only takes into account tasks that you have access to all that belongs to you create . I'll scroll down again. Okay? And I were looking at the patch, which is to update a task so I'll scroll down to that sequel query. This one's a little bit obviously complicated, cause we're doing some dynamic query generation here based on what field to be in a theater . But if you scroll down, it still has a sequel. Query here. So this one here because this has got mobile ones, we fetch a task back. So that's the select. So we still need to update this one to take into account our user i d so and user I d equals user I d because otherwise it would allow a user to modify someone else's task that doesn't belong to them. So we don't want that you will find a prominence or queary um, find Arab. And this is for user I D. And returned user I d. That's PDO Haram in the jet. So we'll school down again till we see our update. So because we're building this dynamically, obviously the query field is being built up dynamically, but it's still the same kiss way. Obviously, we're focusing on the task, but we also want a task i d as well as making sure that the user i d is the same flat task . So on user, I d equals user I d. Andi, we need to bind this. But the bind for this one is further down. If we go down, keep going down. You see that we were binding the task i d. So it's directly after this one query bind, Haram. And it is your hopes. Use that I d On it is the returned user i d and that's PDO Haram in the job. Okay, we're getting there, so keep going down. And this one here is still part of the update task because, remember, would get the task originally will perform the updates on the task that were retrieved and then send it back to the database. And then we retrieved the new task again. All the update, the task. So also need or just this sequel query. So right at the ends on user I d equals user I d And then we need to bind the parameter pops. Queary, find Karam user I d returned. Use a righty. Okay, Them hopes pidio Haram indigent. Okay, so that's the task or d. It looks like it's complete small school down. So the next one is too. It was get all completed tasks. Remember the root for that, which was slash task slash Completed. Um, so the sequel career is here, so we'll just move to the right of that because only wanted list the tasks that belonged to us that's completed. So and user id equals user i d. I need to find the parameter. So find Haram user. I d returned user I, d. P or Haram into j scroll down. So basically looked in all the sequel statements. Um, so this is the page roots now, so this will have it here saw. This is the count of how many tusks. Because remember, this is the total number of tusks for our user now. So we need to do way, user, I d equals user I d this men. Obviously this one doesn't have any parameters, but we need to buying the Haram. So when you do a query, find Haram User I d returned user i d PDO from interfere. Obviously, this is where it works out. How many peerages is needed for all of your tusks for this user, right? Do you know it's a school down? And then we need to retrieve the tusks. So right at the end of this, um and it's this one is before the limit because the limit must come after the where clause . So after we've done from tbl tasks, we need to put where user I d equals user i d. And then it's the limit clause which restricts how many results has brought back based on obviously appeared offset. So at that in when you do bind the parameter. So we're just added in just a both this It's a query bind, Haram. And then we're Teoh user I d turned user id a PDO Haram in the job school down again. So the next sequel, Queer fee Keep going. So this one will now won't do the empty which is the just slash tasks. So this one gets all tasks So we need to get all tasks for we user said the minute this will just get all tasks. Lindy it appears so the end We need to change from tbl tasks where user i d equals place all they use a writing with a need to bind the parameter. So, um Queary, find Haram use that i d you turned user i d PDO Karam into j scroll down again. And the post one is used to create a task. So this exactly same when we create a task, obviously you still need your access talking and we're just going Teoh upend that on the end of the insert. So if a school down to see here, here's our insert. So this one sided different cause obviously, we need to add an extra field into here because this is what we're telling which columns that needs to be inserted. So this one was user i d if remember, because against each task is now unassociated use variety. So user i d And then we're going to put the value right at the end before the bracket, so comma and then it's place all the user i D. And then we need to find this parameter so just unleashed, completed. So it's Queary. Find Haram use their i d returned user I d p d or Haram in the draft case will scroll down Andi, that's obviously the creation. But now we need Teoh. See, that's the retrieve int because when you create something, you should always return it back to the client. So we need to now, did it? This sequel statements or way idea was task I D on D User. I d equals use a ride it, and then we'll need to bind this parameter. So Popes Queary, find Haram Minute user I d returned user id ap or Haram in the job Que school down. Keep going, Andi, That is it. So now our tusks ap, I should now be use a centric. So this should I was to create tasks off their tasks, daily tasks based on users. So what we're gonna do is no test this out. So, um, school back to the top, and then what we're gonna do I just want to start fresh here. So I'm gonna go into PHP my admin, and you can see that we've got some deer there in here, but I just want to start fresh. So what we do is go to TBL sessions. I just want to empty this outs or tibial sessions operations school down and we go on and be the table. We're gonna disable foreign key checks and click or care. We're gonna do the same for TBL tusks operations empty the table on do foreign K checks. Okay. On the same for tbl uses. TVL uses operations. Scroll down, empty the table on tick. Okay, so now if we go back tasks db we've now got a brand new clean database for us to mess about with. So if I go to postman And if we think about this logically, what I want to try and demo here is Logan in as a user, get our access talking, then want to create a task for that user and then want to retrieve the task for that user. But then what I want to do is create a new user, create a totally different task, and then show you that that the tasks independently retrieved based on who's logged in, So the first thing we need to do is create to users. So, http local Horst Port idiot idiot slash 31 slash To create a user who use users and this is a post. Andi got a body roar change two gs on because we need to provide some user deals here to create the users. So the 1st 1 waas full name for a user. And I'm just gonna call this Michael Jones. When you create a user name on, we're going to call this one Michael on. We need to provide a password. So the password for Michael is going to be password with one. So we'll create that's or we'll send So you can see now that we've got a user has a user idea of warn the user names Michael, I'm just gonna keep these tabs often because I might need to refer to them because I might get mixed up where we are. So I'm just going to create a new top because we need to create a new user again. Um, from our history here. So local horse supported it It it slash b one slash users to post request. We need to provide a Jason body, so that's going to be a full name again. Andi. This one will call this person. I don't know, something like John Smith. I think that's fine. And then using them and we'll just call him John. I mean, a year's name could be an email address. It could be anything you want, as long as it's unique. So then password on. We'll call this password to Just so it's different to the Michael user, so we'll submit that. So now we've got to users. And if we go into aware PHP my art Mann Cordy users. But I was you see that we've got to users using here, Michael using him. John. Two different user ID's are hashed password. Both users are active. Both have zero logging field log in attempts, so that's good. So now what want to do is go back to this. Now we've got a user's. I just want to show you what happens if we try and use the task c api i without logging in . So create a new request. And what we're gonna do is just use http slash slash local Horst Port idiot idiots like 31 slash tusks. Now, remember, get slash tasks should get all tasks in the database. We don't have any of the moment, but what you should see is an authentication era. So for send that you can see access talking is missing from the header. So now that you know this is different, it's now taken recount that we must log in to be able to retrieve our idiot or, you know, daily tasks, so we'll get an access talking. So now if we create a new tab across the top like I say, I'm keeping the zone because I may need to refer to them the HDD pay local. Horst it it it it's like 31 slash one a log Insel sessions and this one's gonna be opposed because we're creating a session. So we're locking in. Obviously it needs a GS on body, so body roar application Js on on. We need to provide a using them. We're looking is Michael to begin with and a password, and Michael's password was password one. So if you send that what you'll see now we've logged in. We've got an access talking. We have a valid session. So a cup of the access token. And like I say, we only send the access talking on requests we only ever send the refresh talking when we're refresh a session. This is why access Talking's have a smaller expiry time than what the refresh talking is because there's actually more chance of again compromised or leaked because of send it on every request. That's why you have a short duration. So I've copied the access talking. We'll go back to our get tasks. E p. I go to headers. Remember tune http header for authorization and this is where we provide our access Talking pierced it in there and we'll send So you see, now that it's it seems to be working, you know, we've logged in Thea Access Talking's valid success is true, but obviously we don't have any tasks at the moment. So that's what we're going to do. We're going to create a task for Michael, so create a new top and then http cool on slash slash local horst 40 dd idiots that b one slash tasks in this time it a post request. Now remember, we've got to provide our access talking because this is like this is what identifies forces the user. So in headers authorization pierce our access talking on because we're creating the task we need to provide some task deals. Remember in the body of the task so we could roll and then we'll create some chase on body here. Hopes Never got a select yes on application Js on from here. So the tasks need some monetary fields such as test title and things like that. Soldiers say title. And I'm just going to say something like Michael's. Um um yeah, Michael's Tusk to clean the kitchen. You know, something like that. We're not going to provide a description of the moment cause it's not mine. A tree need to provide the completed status so completed and then we're just going to say no, that's still outstanding. So in theory, they should create a task for user Michael Click, send school up and say that we now have a task. So task i d warn Title Michael's Tastic Lee in the kitchen and then we don't have a description is not completed. So I'm gonna do I'm actually going to create another task for Michael. So we're just going to say Michael's task to, um, cook the lawn and that's not completed, so we'll send that. So now, because I access talking a still valid because it's valid for 20 minutes. We can do sort of whatever war one with this access talking against tasks up along, tow us. So we've now got to task. So now if I go back to the get all tasks for my logged in user, we shall have to see when will previously tried this. We didn't have any click sent. See, now Michael has to. So what we're going to do now is log in as John, and just to make sure that we don't get Michael's tasks so far, looking is John. So if you go back to our, um, I never find us, uses tasks, sessions. So now if I look in as John so I'll create a new one toe post request and it's against the http on then it was the sessions, E p I, because we create a new session, body raw and then application. Jason. And then we need to provide a user name which waas John on a password. Which waas password, too. Oops, I misspelled right So password to send that. So you see, now John has a session with us. So that was two sessions. Is Michael and John. So if I go back to Michael session here on send, we could still get Michael sessions. However, if we copy John's access talking, copy that creating you tap and we want to get all tusks that belonged to John, it's a local host and then we'll use slash b one slash task. So this should list all tasks. Remember who need to provide John's access talking so on the authorization, provide John's access talkin and send that. So you can say that for the get all tasks, it's per user basis. Now saw John doesn't have any tasks, but when we go back to Michael, which is his access talking here, and send that Michael has tusks so you can see there that this is now hooked up on a per user basis when you log in is Michael. We wanna get Michael's tasks and being able to have dear Michael's tasks. And if you log in, is John. When you get John's tasks now, if I quickly create a task for John create new Top paused in all the http call on slash slash local Horst Party Idiot idiot slashed The one slash tasks will create the task. Don't get we need at in the authorization for John. This is John's accessed Open on will create a body to create a new tusk so the tusks needs a title on what we're going to call. This is Johns Tusk to pin the fence planned Tusk need to complete its status. We're going to see what's. We're going to see John as incomplete at this, so we'll send that. So you see the tusks being created. John's task depend the fence, and now we go back to get all tasks for John. You didn't have any. So for send that now, John's got one task more difficult back to Michael's, which is this one here. And then send that you know David Gore saw. Even though John's got a task, Michael can see them tasks, which is how a system should work the user should only be able to view their own tasks. So for quickly go into the PHP, my admin and click on the tasks table go to browse. You can now see Michael's tasks here and then John's task. But the important bit that differentiates who these tusks belonged to the ownership is the user idea. The end. So you can see that these two tasks our belonging to use a one which it just happens to be that that's Michael in our users go to use his table that belongs to Michael. Obviously, Number two is John so vocal about tasks, Brows number two that belongs to John. Now what I want to do now is to expire an access talking. So the gore two sessions and then browse. And I'm just gonna force Michael's access talking to expire. So if we just change this and we'll just change the hour, that's that Access talking should now be expired. So now if we go to a postman and we this is Michael's, so now, because that's a world access talk and that's expired, although the user might not know that. So we try and get all tasks for Michael, send that. You can see the access Talking has expired. Two for a one Eris. What we need to do now is to call our refresh epi. I So if I create a new request here, remember to refresh you patch a session, you will Did a session. So http local Horst port headed idiot slash the one slash sessions on We need to put our session idea the end of this because we're refreshing a certain session now, Like I say this why I kept thes tops often at the top because I can't remember the session number. It's probably is one just because we don't have anyone really using this system. So if I just find it, that's how he uses. That's I would get tasks. This is our create session. So the access talking is this on the obviously the session I D in this case is one I mean that that's not always the kiss. So we'll copy the access talking I am. And we know that it's session one because to refresh a session, we need the session i d. The old expired access talking, but also the refresh talking. So if we go back to the patch and sessions was session i d one Remember John, session is session to so if you refreshing John Session, this is where you need put with two. So in headers we need authorization. And this is where we're pushed Michael's expired access talking and then in the body we need an application Rauff and application. Jason for the raw. And then this is where we provide our refresh talking refresh talking for. Go back to Michael's log in session on a copy. His refresh talking That's still valid. Go back to this on Pissed in the refresh talking. So for submit this. We now get school up. We now get a new access talking over. Copy this And then if we go back to our get tasks for Michael where the access talking had expired and replace our old expired access talking with the newly refreshed one and then submit the same request you can see that we successfully allowed access again. So we went through the whole procedure there of, you know, log in in. So we created the user log in and getting tasks, creating tasks, you know, doing the CME for another user you can see the differentiation between the users on the you know, the tasks will then expired a sessions off the session's older than 20 minutes. Um, we've refreshed the access talking with now, obviously reused that new access talking to continue. I will use the session now. Obviously, Michael can have multiple sessions that's active, and this goes back to very, you know, the begin of the course where mentioned that a user might be logged in on PC, but they also may be logged in on ah, Foreign as well. Now, if we didn't create user sessions, we would have to store that same access talking against a user so users could only have one current access talking. Now, that's no good, because if you looked in on a phone on you already logged in on a PC, that means that the access talking would be replaced when you look in on a phone. So then, if you go back to the PC, you would then we have to log in again. Now let's see, that's not create from the user experience. You want to be kept logged in where possible, on you can have multiple sessions so that's the whole concept, all of wrapped up there in order, probably a little bit to get your head around. But if you you know if you have a mess about with this, you'll be able to see exactly how it works and the logic behind it. And now you can see that actually, this is the whole concept that's used amongst the industry, access talking's and things like that. So I'm hoping this is being helpful, you know? That's it for the cordon. And in the next video, we're just going to sum up, sort of conclude this course. And I'm just going to show you a symbol for implying that I developed just for the basis of this course just to show you that actually, how we can log in in your in end use and me used this E p I with the client application. So I'll see you in the next video 30. Course Conclusion and Demo Client Application: Now that we're at the end of this course, I just wanted to show you an example Application which have quickly put together to attach to our FBI. We've obviously created in this course. This will give you an idea of how all of the endpoint we have created and how they may be used by a client. The one thing I should point out and I forgot to mention in this course so far is that if you wanted to create an A p I and make it available to the world, you must add SSL encryption to your server. So this is basically http s You've probably seen this on websites that you visit where you provide credit card details and things like that. This makes a server connection with clients securing encrypted. Otherwise, when we submit theater like a user name and password to the server using the A P I, he would be sent to the servant plain text Arden. Https to Apache is trivial and there are plenty of guides on the net that will show you how to do this. Server configuration is mentioned at the beginning of this course is out of the scope of this course, but I just wanted to specifically mention this as it would compromise the work we have done to teach you how to create a secure, talking based authentication system. So I've mom violent along with PHP, my admin, and you can see that we've still got the list of tasks that were previously created in the course. So what I want to do is demo. Um, the up that I've quickly put together ensure you how some of the endpoints that we've created will be used from a user's point of view. So we have an iPhone app here, have quickly developed like a say. It doesn't look create, but it's just to prove the point that the functionality works. So what we can do, we can log in if we've already got a user account or weaken sign up. So we'll just try the log in with the use of deals that we've already created. Throw this course and savory trees are tusks. So we'll look in Is Michael because we know this account exists. So use the name is Michael and will use the password, which was password one. Well, then, look in. Remember log in. You can see that our list of tasks listed here for just move this to the side slightly. Yeah, I'll do there so I can see. Obviously, my two tasks it in Michael's tasks. So Michael's task and Michael's task see? And you can see they Dutch Michael's tastic clean the kitchen. Michael's test to cut the lawn. Now obviously, the user experience, you know, for a nap differs books. I've created something where you slide the task to the left and you get some options. You can delete the task or you complete the task. So at the moment in the database, just move this to the right slightly. All of our tasks are currently not complete, so I'm going to complete this top on. So from real end user's point of you let using the up, we would slide to the left and click complete. Now, what this is going to do in the background is do we patch? Remember that a patch is an update. So this update to the task Onda updates the completed status to or why it's of a click complete. You can see that you know, I've made this a little bit fancy where it changes colors to see, you know, tasks complete. But if now, if I refresh the date of this, he can see that this task is now completed. So if I go back on day one, complete it off a slide back to the left and then click on complete and then refresh the data base, you can see that now it's gone back toe in. Or so you see that I would hear P I and Blake A. C. This is using all of the FBI's that we've created in this course. Nothing's being changed. We've just created the app to plug into this E p. I. Now you can see this will be used in the patch. Now if I wanted to delete, so we'll delete the Michaels tastic. Cut the lawn. So the scroll, the left and click delete. So that removes from our list on the client application. And if I refresh this task list, you can see that it's disappeared. So it's still eating the task for us. So if I go back into the up and create a new task, so on the new at a new task, so we'll give this any M such as Michael's task to, um I don't know, clean the car, give a description just to show you that all the fields actually populate its or clean the car, Give it a deadline. So we'll see. I don't know. 05 slash 03 slash 2019 and do it by five PM and then complete. We're going to see in north of the time being so see if that you can see there now, we've created a new task and that's being updated on the client device. So we go back tro tasks table, just refresh it. You can see that it actually created a new task. It's assigned our user. It's updated, the description, the deadline and the completed status. So this was the post on the slash tusks MP I So you see that actually, it may look complicated when you use nets using postman. It was a lot of a lot of fiddling to do just to get to do something, but actually, the client application can be very easy to use. So what I'm gonna do now is look out of this application ups and take a look out at the top . But first, before I do that, if I click sessions go to browse, you can see that we have a session. So obviously, when we first logged in using this application, it's created a secession for user I d. One, which is Michael. So if I then log out, that is the equivalent to running a delete on the slash sessions slash idea of six I'll just click. Log out, takes us by the logon screen. Refresh this session's table and you see there's no current sessions anymore. So I'm going to do. I'm gonna look in as Thea the user, which was John and then the password for that was password, too. So for click log in, you can see that now we've got John's tasks. So you say that you know it doesn't know anything about Michael's tasks. It's now, you know, user centric. It doesn't really care, doesn't need to know about any you. This to any other uses tasks. So we do. The Syrian wouldn't create a new task. That's a refresh button. So we've been refresh the tasks. Now, one of the things I did want to demonstrate and well haven't really demonstrated this in this course yet is the the Kachin type stuff. Now, I know we added it into certain in points and routes, so we will read or cash some data on the application on the client. So that means that every time you click refresh the application will check the cash saved, the cash is expired. I think we set this to something like 30 seconds or so on. If it you know, if the last previous called to get this data was within 30 seconds, Eldest retrieved from the client's device because things like Tusk title and stuff like that You're not too bullet whether, you know, it takes 20 seconds to get an updated version of that. Like I say, we don't use cash in on anything to do with authentication or when creating tasks. We need that data straight away. So what I'm gonna do is actually update this task in the database. And what you should see is the task not updated on the client until after about 30 seconds . So I'm going to do is just refresh that and then go to tasks. Go to browse, and I'm just going to change Johns to see John's task. Um three. So now we've updated that to say John's task three. Now, if we go quickly back to the simulator to say here that Shaffer, click and refresh, we're not getting that task. Three toe appeared at the moment, so if we give it a few seconds, I'll just fast forward this little bit. I'm a click. Refresh. You can see now that's task three. So you see that that took a little bit of time to pull through. So that's what I'm seeing, how you can handle cash in. So because it's updating the database doesn't necessarily mean that the client device should get an information street away. So in order to get that information that would have to call back to the database on the server and then obviously Pulis did back down. But because we set a cash in policy, we can see well, don't go back to the server until 20 seconds or 30 seconds has ruled passed since your last got an updated Like I say, you don't use this for all endpoints, but sometimes it can help to sort of help the Lord on the server. It's what we'll do Now we'll look out again. That should delete our log in sessions off global recessions. Quarter browse. You said that sessions gone. So what we're gonna do is create a sign ups, or we're going to create a new user. So we'll give them a full name. Mary Smith. Give them a year's name of Mary. Give them a password off. Password three and click. Sign up. So you say your account has been created successfully, so we go to the users table, quarter brows and seeing that now, we've got a merry with the sort of a hashed password uses active. So I'm going to do is go back. Row simulator. Okay, that come back to our log in screen for just trying log in as Mary. But if we type in the wrong passwords or retirement password warned here. Passwords password three. But I'm just going to tie tried password one. So if you look in, it says there was a never Logan in click. OK, so if you go back to browse, you can see that our log in attempts is now incrementally to one. However, I'm gonna take a password incorrectly this time. So it was password. Three Sat log in. It's now looked in. Fine. So for just refresh this, he can see that because of locked incorrectly, I would log in. Attempts has been reset back to zero. Go to sessions, browse. You see that there's a new session for Mary User I D. Three. But Mary can't see quarter tasks Mary Kansi, Michael's or John's tasks. So that's that's just a bit of a demo. They had to show you how a client application will work. Like I say, it doesn't look too jazzy. But it was just a proof point that you can plug in a client application now to the FBI that we've developed in this course. All click log out. Okay, so that's the end of this course. And I just want to say thank you for purchasing this course. Hopefully, it's being useful to. Yeah, but if you've got any questions or anything like that, just feel free to message. May. Thanks again 31. BONUS Section 01 - What is CORS And How Do We Allow This On Our REST API: This is a bonus section, which I've added. I was receiving a few questions about getting the A C A P I toe work via front end application, which was hosted on a different demand. For example, the FBI was hosted on example dot com, but the front end was hosted from Sight 123 dot com. There were some building security within browsers, which tries to prevent sending data from one site to another, as he wouldn't really want data from one site to link to another. This is known as cause or cross origin resorts share. You may have a need to do this, and they are valid reasons why you would do this. You need a little extra set up, and in this video I'll be sure knew how to get this settled on working. It's not always the kiss I need to carry this out only if your friend end his horse on a different demand to the FBI itself, or if you're FBI. That you're creating is for public consumption, where you don't have any control over the front end demand. So what is cause causes? A. Were to instruct Bro's replications toe allow resources to be accessed from a different origin. Different origin is basically a different demand. So example dot com or say to dot com a protocol, which is things like HTTP and https or a different port number. An example for this would be to allow a friend and application hosted on https. Call on slash slash ST one dot com toe access resources from https Call on slash life, say to dot com slash z a p I slash users. Brose is by default will restrict this behavior for security reasons by using the CME origin policy. If you find that you can't get your front end to call it a P, I was bringing up the browser development tools in view on the console that all sure, you basically a lot of information, which is helpful to troubleshoot mint. And if you do see stuff in there to do with cause or pre flight, which will go on to his next, this is going to be a solution, really. The configuration and additional court Hanlan we're going to go through now will instruct the browser to allow cross origin, either by ordinate upto all origins or just a selected warn origin you can't actually specify the is if he is a few workarounds with generally, you can only specify either one origin or organ it upto all origins will be adding additional headers for an options method response, which will instruct the browser. Which http methods. Additional headers in origins can be used. The options method is very similar to something like get or paused or patch. It's just another were of sending data to this server. Busy options is is more the control method it's used for clients to see more information about the server itself. The browser does this automatically for us for a cause request, and this is what's called pre flight. The Broza will first preflight a request, such as if we send something. See, it's create a new task using post before actually that post request is submitted, it will actually do a pre flight to server to see if it is actually load. To send the dealer from where you know, from the origin on using the head is that we specify before actually sending the request. Some requests won't actually trigger preflight these air Nona's simple requests The simple request is to find his below. It's either one of the following request methods get head or paused. But this will get a bit tricky because if we are using paused on, we also using some or the request header from what listed down here below. If we're using something else, then it will always do a preflight check. So, for example, a good example of this would be we send an authorization header. And that's not in this standard list off headers saw. This means that any any requests that we make, which has an authorization header is then not a non simple request. The other thing is, if we use content type, the only ones that classifies a similar request is application extraterritorial for mural accorded, multi part form data or text plan. But a lot of what in this course will use application slash gs on. So a lot of what Actually what we do will require a pre flight. So pre fight works a bit like this saw. We've got our client and I was server it in all this bid for the time being the preflight check. But generally our original request is what we would normally sent to the server from the client. So if we want to create a new task, we were paused to slash tasks and then obviously we got allergy. It's on body here and we would send two headers an authorization, which is our access talking header on content type, which tells the server what type of data we're sending. Generally, that would go through and if everything's OK, it would send two or one created and then we'll get our task back. However, if we send this from friend in that works on a different server, for example, what we'll do is we'll get a preflight check. The browser automatically does this prior to our request actually going through. So what this does is actually send options. So this what would turn over before it's just a different request method. So options to slash tasks saw to our endpoint. It will have some headers in automatically and these are origin which is the site that way . Send in this from so you front end site access control request method. So this is what actually were carrying out is that it get are opposed. It actually opposed on access control request headers on what this is is authorization and content type. So these are the ones that way sentence or this is almighty bill force from the browser because we're sending authorization content type. So basically, this is asking the server if this can be sent and we'll show you a little bit later about you can actually tell the server to see well, don't accept delete, don't accept patch only accept post, for example. Not in this case, but you could restrict what you're allowed to do to this end point. So then the server looks at what we're going to court Next on will respond back to the browser with the relevant head is back. What this does is access control, allow urgent. So it's saying that we're allowed to receive requests from sight one dot com. That's okay. Access control. Allow methods to this end point. We can actually send a pause to get an options a patch or delete access requests. Allow head is well, this is Sears. We will accept unauthorized yet another content type better, which is what we're sending here on access control Max age. Now what this does is that's currently set to 24 hours. But you kind of just that of. What that will do is if the Broza sent another post request with the CME header on endpoint , it will actually cash to the preflight check so it doesn't actually have to send another request to your server to see what it can do. Now you can change that to see a well only want this valid for 12 hours, or you can make it two weeks, for example, story up to you How long you want to catch that responsible. So once it's done that it then and everything's okay, you've got to send a 200 state is caught back to tell the browser that everything's OK and you're the stairs court will then feel on your request, will then subsequently feel so. If that sends back 200 back to the Broza, it then goes under, send your original request to the server and just performs normally. The options method. Basically, you put that on each of your end point as well, because each endpoint could have different options that you want to allow. For example, I think I would use is endpoint will allow post only I think it is. You may not want to allow these other options you might not want to lower, get or delete. It depends what you're endpoint actually does. But you would put in there. It's more for security. You would put in the response back to the client Watch the endpoint can accept. How do we do this? The first thing we gotta do is change some Apache conflict when he tied a new line into the HT access file. And that's the file that we've been doing our you are, well, rewrites to allow you to prettify the U RL's. So we do need out of one lane option in there and you can see here there's two different options going back to what I was saying before, You can actually, you know, specify specific origin. This is the see if this were to do it, to be honest. But if you're using a public epi, I Sorry if you're writing a public FBI, then you will have to allow any origin at all because obviously we have no control over who is going to be using this FBI and from which to me and but that obviously depends if this is gonna be a private API I off. You can't actually open it up for the public to use. So what we've actually got to do is set the headers in the HT access file to rely with the origin. So what this does is we've got a website here called your front end site here dot com. And if that's where we have all snow for an end from that is the girl that we put in there . So what we'll do now is actually going to just that in Adam to have got Adam Oban on. We want to go to the HT access file and you can see this is our current completed actually access file. And we need to add in a new line just of the top here. What I'm gonna do, I'm going to just put a comment here and just type cause options going back to what I was saying before we need to specify hitter on and setting it on. It is access off control, allow origin, and what we're going to do here is actually just put a star and that below your i p I to be called from any front end demean, such as example dot com site one dot com se to dot com Whatever legacy before, if we were to specify warn front end demand, we would actually taken into here and site one dot com. And what that will do is actually allow only cite one dot com to access this resource. But for this purpose, we're just gonna put star and just see of it. So that's all you need to do in the HD access file. And this is sort of any endpoint that we've created in this course that now allows any origin to access it. Obviously, there's a further step which we need to do next, and that is to allow each end point to respond to the options request method. So now that we don't know, Apache conflict will just move on to the PHP endpoint change. So within your rest, endpoint controller will be alone. In this example. We rely when slash users to be called from a different origin. In this case, slash users to be called from a client horse did at https force that forward slash your front end site here dot com. We'll need art. A new handler for the options request method. This is what the court will look like we're checking to see like like, if you remember what we're doing. Previously in this course we checked for the different request methods and then handled them depending on what the before. Now, obviously this request method is options. It doesn't do a lot, but it needs some minimum things that we need to do to get this toe work. So the 1st 1 is to add a new header. If you remember going back to our floor diagram. If you look here, we need to add a response. Yes, or we're already doing that. So access control allow origin because we put that in the HT access file. So the ones that we need to do is add in access control, allow methods on access control, allow hitters on obviously the max age. So what we're gonna do is open up or close each day access for the time being. Because I don't need that up. It's don't on this example. Obviously, this is very similar for the other endpoints that were created, but for slash users, what we're going to do. We're going to put it in. Andi slash users does work in a slightly different were to the rest of them. Basically, I'm just making sure that it is actually paused. If it's any of the request method, then would get a standard response for four or five. Request method not allowed. So, actually, what we need to do is kind of copy this. Andi put it above where we busy put it above this because we want this check to come after the fact that a preflight has occurred. So it must come for both. This just pissed in there for the time being. And I'm just gonna put a comment to see handle options, request method for cause. So for change this to if the request method is options, each deep he stayed, his court must be 200. Remember? Must be 200 Will set the success to True. On what? Just gonna get rid of the message. Because we don't need to send a message back. However, we do need to add in to well, three additional headers. Sorry. So we'll do that now. The 1st 1 is access control. Hello methods. And for this particular end point we actually want to include paused on bond options only because these are the only ones that are relevant to this end point. So what caused? Which is obviously what we're doing here. We're posting Theis nor delete on users. I mean, the is on task on sessions, but there's not on users, so we'll just allow posed in office. You gotta allow options because that's what we're sending here anyway. So the next one is access control. Hello, Hedda's. Andi. For this, warn users one. It is only content type. However, on the other ones, such as task, he would hard content type comma authorization. Obviously, that's where our access talking cause. But we're not using that in this case. So it's just content. Type on. The 3rd 1 is had a Andi cool access and spell it right. Control max. Age on. We said this to 24 hours, which is hit 6 400 So I've done here is actually allowed a request for creation of a user to be called from any origin. Eso you friend then could be hosted on example dot com, and the FBI is on site to dot com for example, all we need to do is obviously at thes three headers here and obviously remember the HT access. And that should allow you to call these FBI in points via the Broza if it also in a different port or a different protocols such as https. This is Http on obviously a different origin or demeaning him, so hopefully that will help you out. Obviously, the were that you'll deal with. This is different for the other endpoints. So in the tasks, we have things like, um, just find one request method, get so if you just minimizes down, you can obviously see that way. Allow. Get delete patch. Andi, if you wanted to handle this or allow cause to be enabled on this, you'd also have to handle the options method. And obviously, the options method is just what we've implemented here. So you'd use this CM set of court here. Okay. Of all that helps any questions, feel free to drop us a message. Thank you. 32. BONUS Section 02 - Adding Image Upload Functionality To Our API Intro: This is a second born, a section of this course. I've been receiving a few questions about how to upload files and images to a task using a rest API I So I've put together this section on how we can achieve this. There will be a little bit of theory first, but only a small amount is this is a little different Watery of previous have been dealing with in this course will be sending a binary file rather and send energy s on request, obviously for the file up Lord. So let's get started. So you're probably asking what's different and how we're going to do it? Well, we'll still be using get paused patch and delete HDP methods to follow the obviously. The rest for printable will create new routes, toe handle images against the task and amend our current task FBI to take into account the images against the task. The new routes will be added as follows. So I've got to get and what this does. This gets a particular image. Obviously you'll see slash task slash task i D. But obviously we now create a new route for slash images slash image tidy so this actually gets the image itself. So you're probably thinking, What does that mean? The B two sections of an image one will be attributes or things like metadata, such as a description or a title of an image. And the other things Actually, the image itself, the image file. So that leads us nicely on to the next part so we can get the particular image attributes or slash images slash image i d slash attributes In this election, return urges on response. Just came to what was being used to in this course. The next method is patch, and obviously, as you know, patches now to update something. So what we'll be doing here will actually be updated in the particular attributes. So, for example, we may want to ditch the title or the file name we send. This is a genius on request on. We get a Jason response back with the new attributes, so nothing really that much different in their compared to update in the task. Then we'll be looking at paused and obviously, as you know, Post is to create the image itself. This has an end point of slash images, so you can see here that we associate ID with the task. Particular task I d. We're associating or creating an image against that task. I d What? They stores this uploads the file itself and then returned to GE Asan response for obviously the attributes that we've provided. And then we've got delete. So now you delete a particular image, Onda. Actually, it it returned the Jason response to see whether that was successful or not. And then we'll actually also go on to edit the current functionality of the task a p I to allow it to incorporate the image. So this is not just stand along will actually be merging the two together. So you're probably thinking, What does that mean? That means that when we get a task, the Jason response that will get will actually includes the Jets on collection of images. He's don't actually returned the image with it with the task e a p I. You actually just returned a list of images because if we actually turned all of the images associated with a task that will actually slow down everything, So if you just wanted to get some task details, you wouldn't want it down, Lord every image just to get them task deals, you know, in some images. And you know, we're talking general images that to take it on an iPhone or some sort of mobile device, they're usually about three or four megabyte and size. And obviously, if you've got 10 of them, you don't want to be down Lord and 40 megabytes just to get the Tusk T deals. Now what you normally do on the client side toe handle these tasks. Details on obviously the images themselves. You do a first call to get the task deals. You would then populate your client application, a website with the task deals and then actually you fire off separate requests, separate get requests to get the particular images and image attributes so there could be actually down Lord in the background and obviously wants that downloaded. The your client application could actually just pop them images in to say, Well, I've downloaded that image and now it's associate ID. With the task on, now you can see it. So that's that's the reason for doing that. You don't actually return the image file itself with the task itself, so you just return sort of a link off some attributes regard in that image. So how is this different? The 1,000,000 differences are the content type that is used on the request body that is sent on the post, which is the create slash upload image. Previous in this course, we have used a Jason content type for the request on the response body, but this time will be dealing with binary files such as images or documents. So we must use a different content type by New files. Don't contain asking characters such as alphabetical characters on certain symbols. It's actually buying the re theatre so it can't send the image. Is part of the GIs on request? Well, actually, that's not particularly true. We can send a binary file, but we'll have to in cord it using the base 64 algorithm. What that does that take the buy new file and create a textual representation off that file itself? But it does come with its cons. Basically, and not an overhead saw, larger file size of about round, about 33% larger. You can do it. There's nothing stopping you do it, but it's generally not best practice to do that because it would mean all of your file sizes would be 33% larger. Now the way the world is at the moment, a lot of people use mobile devices, the data connection. So, really, the down lords should be a smallest possible without obviously compromise on the quality. So we will ignore this method and just use the best practice instead. The content I would not be using this time instead of applications. Last Jason is multi part slash formed era, and it looks a bit like this. It's probably familiar if you've done any Web development in the past and have used an image of Lord from a Web form. Basically, when you submit that form generally it which structure the request like this and you can say that it looks completely different to Regis on request. Basically, we've got the content type of the top. Now you're probably thinking, What's this boundary? So what boundary does because you can actually send multi parts in the same request. Hence moly part. So the boundary actually is a random character string that's used to separate each individual part of the request so we can actually send different types of data with this content type. So the first thing that you'll notice is we've got some form dear to here in the name is attributes. So these are our image attributes Now, this name can be whatever you wanted to be. It doesn't have to be attributes. This is the part that you would change if development a system that's not really a two tasks or images. This is where we get a little bit clever with this because we're actually going to send Jason Request or Jason Body within this attribute. Now, this attributes is just a text attribute. You could just type in a title off my selfie, and you could you could use that is your request. But we're going to use Jason because it allows us to pull multiple different types of attributes in a structured way that we can send along with the file itself. So, as you can see, we've got the boundary at the top here. So that's the boundary that we set. Whatever set in this part most equal, see him throughout the request body. You put the boundary where you start and the boundary on the next part, So it's kind of where it ends in a week. So start obviously separation and then the end off the request itself. You can see here that this looks slightly different. We've got to dash is at the end. So Dash Dash one part of the request Dash Dash, second part of the request Dash Dash and part of the request, but got to doctors at the end to tell the system that it is actually the end of the request body itself. So the next bit from the attributes, we've now got the file itself. This has a few different types of things that we send along with it. Now, you're probably thinking this is a little bit tricky in what does all this mean? A lot of clients, systems or client frameworks have this sort of structure built into it. So, you know, there may be a method in your client and framework that has upload file that would actually set this format for you, but if not and you're actually creating the request itself, this is how you do it. Content, disposition. All this means is what? What? Actually is it What is it? Form data such as fields, or is it a file with the file near? So obviously you can have multiple form data. He actually could have multiple files, to be fair, but it just has to obviously separated out using this type of structure here. So they were seeing it form data. And now down here was saying this is the actual file itself. And the file has a file name. So obviously we can use this file name on the back end or whatever like that, so we can name the document. The CME is what we are lorded. It does. So the next thing is content type. We're going to upload an image here. It's actually J peg. Obviously, there's different content types for different types of images or even files. Actually, we have. This one is an image DJIA pic, but it could be image slash PNG. There's a massive list of content types out there. The next thing is the content transfer and cordon. Now, because we actually send in a bind. Refile. It is a physical file. It's not just text. It is a physical file. We have to set. That is binary. Now, here is where Once you've uploaded the client or the browse Airil, whatever device you're using will automatically convert the file itself to data, binary data and all that. You know, it could end up massive in the but it's kind of non readable, non textual contents. So that's why I just put a placeholder in here pathetically. That's where the contents of the file will end up all in this request. And then obviously we got the end boundary here. I know this looks, you know, a little bit difficult to understand, but actually will totally make sense once for sure your demo. So from here, that's the theory basically finished. It's just a little bit of background because I don't want to go over what patch and delete . And, you know, all that stuff is because we've already covered in this course. So I'm going to do now is actually Dem or using the up Lord system and just to show you how it works just so we could get appreciation of what we're actually doing in the course and how we're actually building it 33. BONUS Section 02 - Demo of Image Upload API: but I'm going to show you in this video is actual dem or off the image upload MP I from start to finish. So what you'll see is me actually applaud in an image file to then view and what you see when you retrieve a task and then obviously get the image file itself, get its attributes, update its attributes and then finally delete the file itself. So let's get started. I took a course mind over money, and the first thing I need to dio is to log into the system. So I'm just create a new session or see with me using your password. Copy me access talking. Go to the get tasks MP I saw. I've already created three tasks Task on Test two and Tusk three. You can see here. That thing that's different from last time is we've now got an images array as part of the task de deals. So this is like a sane way you'll return the image attributes involved in the image file itself. So I assure you this work and the first thing you need to do is to create a new request. Remember, it's a post request so we actually creating the image we want to put in our month in points or http, call on slash slash to local Horst scared of that. And then it's the port slash b warne slash tasks. And then remember, it's the tusk i D. Member, the route from the previous slide And this is how we associate what image were applauding with the particular tasks. So we're just gonna uploaded against task I d one Andre. Remember, we're post into a new route and it's slash images. The next thing we need to do is to go and put authorisation, access, talking in hopes, the wrong one. I've got a copied still, So I'm just gonna pistol in there now we're going to the body of the request Now, what you're probably used to, obviously in this course is click and raw. And then, Jason, this is where we click formed it or instead. So this is where you have your different pieces that you're sending in the request. So I remember from the previous slide we have the attributes on the image file, so attributes aunt Image file, folks image file and if you hover over them, you be able to see the different types. So we've got text or file now. Attributes is text were using that to put Jason Cordon. So weaken Dick, order it on the other side. But image file, we need to change out to file cause it's an actual file. So the first thing I'm gonna do is type some attributes in their injury. It's on four months. So we have a title. I'm just gonna call this image file, warn. And then what we're gonna do is give it a file name on and we actually going to auto determine what the Image X are. The file extension is when we upload the file, so we're not going to provide an image extension. Here are a file extension here, so I'm just going to call this image one. For example. You could change your solution to allow you to put in different file types, but I think we've done a smart way here, So we actually order detail and based on what type of file way up Jordan. So the next thing you need to do is click. Select files have done ordered three files from the Internet royalty free ones and so there's no copyright issues with these files. I've got a PNG file and then I've got to JIA Pict files a piece of water with the tree there sky with a flower there on a car. So the 1st 1 ongoing upload his sky doctor, you pick. So open that and say that is populated that. So what I'm gonna do is send that's office, submit that you can see there. That's where you get address on response back with stairs, quarter two or one, which obviously from the course created We'll get a message back. See, an image of Lord successfully this time would get the image attributes returned. So image i d. One title file name and you can see there that it has automatically put the file extension on it. And then we've got mind type, which is how we determine what type of file it is. So it's an image DJIA pic file. You can also see what task it's or socially it against. Remember that task i d is in the root. So got tasks, slash task I d. And then what we've got here is an image Warrell, which actually takes you to the root to actually get the image. We can actually see that the Rudy is very want slash tusks. Last task I d in the images slash image i d. So Because this is the first image revolt lorded This is image I d one. So what we'll do now is quickly go back to get all tasks a p i and will not again. So now you can actually see that we've got images and it's actually got one image in there , which is a kind of like, obviously the return dealer that we saw before. Now what I'm going to do, I'm just going to add a second image in there on Will, Lord of P and G this time toe open that, um I'm just gonna change these just for demo purposes, and then we're going to send that. So you see, that's been applauded. We've got an image idea of to this time. We've got obviously the new title and now you can see the file name even though we call that just image to the final name is now a PNG file in the main tables. PNG still associate with Task one, but now you can see we've got a direct route. They fall the second image to go back to the get task route. You'll now see that we've got to images, image, warn an image to and obviously task to and task three. There's just blank images. Still don't have any for that. So the next thing I want to do assure you actually on the file, sister. So for Got a finder have created Fuller called task images will get into this obviously, as we start implement this, but we create a folder which has got the task i d as its name will go into that. And now you can see the to file that we've got your image worn, Dr J. A pagan image to dot p and G. If you open there, you can see that it's actually the images themselves. So the next thing I need to do is to show you how to or how to get the image attributes on the image itself. So you can see you have got a direct link to the image. So what I'm just going to do is just copy that for the time being, create a new get request piece that in there to see it slash tasks slash task i d slash images slash image i d. I want I want to do first is copy the access talking because obviously will have to be loved in authorization Piece me talking in there. And this is just a blank get request because we're getting the image itself. So percent that he can now see we'll get 200. And actually, we've got the image file itself. So this is what your client would call to get the image itself. Just that simple route there. Now, obviously, because we can't return Jason on the image file in a sort of response. I mean, you can open obviously, as I mentioned in a previous slide, that would have to in corded in beer 64 in Cordon. And that would allow you to then embed the the ask a representation of the image with the Js on, and there's nothing stopping you doing that. But obviously there's that 33% overhead on image size. So instead of being 400 kilobytes, they would actually you know, it would be 33% larger. So you say they're not tell you call the image. So now if we the new route for attributes, is obviously slash images slash image, i d slash attributes. It's not attributes. And if we get that, you can see we get a Jason response and we get actually, image attributes itself associated to images with a task with called the image itself on was actually viewed the images. Sorry, the image attributes. So if we just change the image attribute I d to two. You can see now we're getting file image file, too. Um and obviously the direct link to that. So if we just take attributes off the end there and then call just the image I d to you can see that we're actually getting the PNG file this time. Obviously, it's a different image so we can switch back between image warn Andi image to. So what I want to do now is updates the attributes of image one. So they get request. Currently, it's called image file One Doctor pig on the title is image file one. So if we create a new request, remember an update as a patch If we type in the month. Hosni um aunt, if we go for such B one slash tasks. Last task I d slash images slash warn and then slash attributes because, actually, way Obviating attributes here were not updated in the image we haven't actually implemented . Replace an image, but you can follow what we're going to go through in this course and actually implemented if you want. What I like to do, though, is actually delete the image in which will show you in a second to leave the image and actually recreate the whole image. So re upload an image of who would change the file itself. You know, it's it's your choice and depends on how the application works. So what we're gonna do, we're going to do a patch. We need to copy the authorisation access talking. Make sure I do that. Authorization pissed it in there on what we're doing this time is obvious. Good Lord and Jason Body for the attributes or GS on Well, let's create some Jason in here. So we're going to update both the the image title on the final name itself. But you could just do, you know, just like whatever tasks, it's up to you. Which attributes you want talk to you Don't have to help their them all and still call it title hopes. And we're just going to say new title here on if we give it a new file. Name is Well, like a seat won't have to do this. We'll just call it new file. Warn Don't put file extension on the end because war already determined that. Thought I need to do now is Teoh. Run that. So you can see here is gonna move that up. Image Attribute Updated. We've got the new title there in the new file name. Obviously, it already still knows what the file here saw it. Almighty puts the file type on the end on obviously a link to the image itself to go back to get tasks and obviously before refreshing and still see that see his image file one so over refreshed that you can now see that the new images or the same image has the new title and file name the And if you just quickly go back to the file system, you can see that the new or the file our heart, the file name of the actual file has been updated as well. So they adopted obviously the database itself, but also the file actual file itself as well. So the next thing I need to do assure you to how to delete So weaken Delete an individual image by passing in the image I d or we can delete. The task, which would also delete all of the images associated with it, is part of the delete task. We're just going to delete the image itself here, so we'll do it Should U P and then we're just gonna pick image one. And remember with deleting the image itself, not the attributes, or it's just slash images slash image i d. We're going to get the access talking. Put it in looks. I don't have to provide a body for this because it's just a delete. So what we should be able to do now is delete image with image i d one. So we'll get a 200 response. Success is true and the message image deleted. Now, if we go back to the file system, you can see that the actual file called New File. One thing we're called it has been deleted, so it actually deletes the physical file, too, if we go to get the task details so you can see now task i d. One when he has one image. Obviously that second images. Still, because we didn't delete all of the images. If we try and get the image attributes for image, I d warn you can see that we get a 44 an image not found the same if we try and get the image itself. So the image is not found. So that's following the same restaurant principles for the Steelers courts have returned. So what we gonna do now? I was actually delete the the whole task, which actually deletes all of the images as well with it. So we'll just go delete and then we'll go to, um so it's just slash task slash Wonka's Rock Creek deleting the task we will copy across the access talking authorisation, access to open. And then, if we submit this, what you'll find is just got back a folder. This folder with this task idea because we're deleting the task itself should disappear that under file. So I delete that you can see now let's get to understand is called task deleted so that's no different to one. Obviously will harden enormously that the previous sections of the course what you'll find is actually now the task images folder the is nor task warn folder and office of the actual image itself is gone. So if you go back to get tasks he would want have task one anymore. We've got task to and I just quickly want to show you how this looks in the database will quickly upload a new file against just find opposed against task I d to cause we've already deleted one. Um, I'm just gonna blow with Sam file again. You see the images uploaded. We've got obviously a new fallen. Now when the task images for the task I d. One and we've got obviously that file that we've just uploaded. So it just show you're in the database. We now have a new table called tbl images, and within that, if you go to browse, you can see that we have title a file name and mind type, and obviously the associated task I d. And obviously a majority. So that's kind of all you get in the table. And obviously that's how it relates to the specific task. Just open postman again. So I think that's basically it covered. Creation of the image, the update of the image attributes on the delish in of the image both by deleting the single image on obviously deleting the task, which then goes through and delete all of the relevant images to laugh task. So know that would then what? That will actually get on Teoh implement in this functionality. 34. BONUS Section 02 - Implement Folder Structure To Store The File Uploads: never will actually go through and implement this image. Upload the A P I. First thing we need to do is create the Task Images folder. This is the folder that will contain all of the images that we applaud. So what we got currently is the month folder HT Docks, which is our what's called the Web root that basic when a Web server serves to the public. Well, then, Harvey One, which is obviously contend that were currently a P I stuff in there, then have the control and the model. But this is the new full of stocks that were just about to create. You can see here have actually inserted the task images faller Bush you probably singing Well, why isn't this folder within the Webroot or the V one folder? Well, the color reasons, really. If we put the task images folder within V one, if we then create a version two of the P I, that means we'll have to copy all of the tusk images to the V two folder. So that means duplicate and images. And then obviously the the images themselves would be different. Biest, on which version the FBI, the client caller. So for consistency reasons, we take this outside of the V one older V two folder. So you probably still thinking, Well, why isn't it's just in the HT Docks folder? Well, this is the most important. But to be honest, what we've actually done here is put it outside of the Web root. So the web of route is the folder that Web service serves to the to the public. So all of the files within here are accessible via a Web address. So in our case, it's local horse supported idiot slash. And then anything after that slash is within this HT doctor folder now, because we're actually stored physical files for obviously client up Lords, then we don't want these physical files actually being publicly available to anyone that can just, you know, give giving. You are l direct into the task images folder. Now you could mess around with folder security and things like large but actually best practices to move any image up lords or even file a blood fallers outside of the Web root. This means that no matter what what the client tries to type in, there were Broza. They cannot get physical access to thes tusk images. All this fold outside the Webroot people. Try and upload, execute herbal files and all sorts of things trying to sort of take your site down or, you know, create a malicious sort of environment for you. For your users. Obviously, moving this outside of this allows anything or anyway, address that you type in to not be able to execute any file within that folder. So basically, it's belt and braces it Good security practice to do that industry standard. There's different ways of horse and files you can use Amazon s three, obviously zero as well. That's kind of the school of this course, but in the same will obviously be relevant for that. The image file location that you call within the court, which will go through later, will obviously call these physical files from this or the folder structure that's not publicly accessible to your normal users is an example off a potential security issue. Imagine if you use a tri Taub Lord a PHP file, for example. Well, that page peak file could be malicious. It could, you know, try and delete every file on your file system it could try and send clien taxes. Talking's to, you know, some hacker or something like that, Like a C at what you do is stored outside of the public root. And then, obviously, the user wants If the do applaud something that can't directly access that file, we use a script and we'll go through that later. We use a script, actually, pull that contents and send it back to the user. So you're not actually executing any file or anything like that on the server itself? Privacy Amusing month here. But this CM concept is relevant for all of the Web service such as I s obviously a Patrick , because that's what we using here. But even Engine X, basically a store, any file upload outside of the Web root folder total doing I was actually create this folder. So from your desktop, I'm just gonna go to finder applications and obviously I'm using my amp. Onda. Obviously, this is the contents of the month folder here. So from within here, you can see our agency docks folder and for expand. That should be able to see I would be worn. And obviously I would control the files and things like that. So what we want to do here is create a new fall that called task images. Now you can secure this fall down. It's also the scope of this course, but technically what you would do is you would allow administrators access for administrative purposes of the server. And then, obviously, whatever user Web server is running as they would need, obviously kind of modify access to read and write files to this folder so you can actually secure down to just them to sort of users. But, like I say it out of the school, this course, but I thought I was just pointing in the right direction. If you do implement this, so now that the fall is created were actually get on to change in the database to obviously implement our TBL images table 35. BONUS Section 02 - Task Image Database Table Creation: in this video will create the new database table called TBL images. This will stall the image attributes as well as associating the image against the task is a task. Could could 10 more than one image. So I've already got month. Ruling Andi opened appeared to be my admin, and the first thing we need to do is to create the TBL images. Terrible. So of Klingon task, Stevie, when you could new table called tbl images. And this is gonna have five columns go. So the 1st 1 is going to be the image i d itself. So we'll call that I d following. Obviously what we've done in the previous videos of this course, the ideas will have a big end to allow for name control. Ian, I believe it is on 20 to do we need to make this a primary key. Okay, that on auto increment lend out in a comment, just so you know what it is so image I d number primary key. Next field we're gonna put in is the title. So that's the title of the image. It's gonna be a bar chart. I'm just gonna have 255 characters. Well, put it comment in here. We'll just call it Image title. The next one we're going to do is file Name. This will be a vulture. Andi will be 30 characters. Put in a comment The image file him. Next column is mind type and what this is. This is where you store the type of image that your seven or could be the type of file, for example, so it's things like image slash, g epic or image slash p injury. It basically tells the client what type of file that your return. So we're not using really sort of the file extension Rocky using the actual mind type of the file. So that's actually of our chaw. Put 255 and there we will give it a comment. So image my name type E g image slash P entry. For example, The Net. The last column is Task I. D. So this is how the images actually associated with the task itself. So this will be a foreign key, which links back to a violent task. I d. So this to follow obviously the same rules that we've got to the task I ds This will be a big in a swell Onda. We will. I put a comment in here, so task I d number for Okay. Okay. Everything looks okay on that one. We will put a comment in here. Pope table to store tusk images on the collision. We will select. Um, hello. We're down. Ut f it. General case insensitive. Okay, I believe where done on this? We're not allowing any nose for any columns, Andi, that we're not putting any default in. We've put all the length and values in order. Increment is just on the task ideas. So it should be good to go on that sofa click safe. That's our TBL images. Terrible creators. Thea's a couple of things we need to do to enable the foreign keys, but also a unique key. So what we're going to do here for each task I d. We're only going to allow a unique combination file names because you can't have two files with the same name. So we're actually gonna put that restriction on the dear to be Issa's. Well, in order to do that, what will do will create an index here so we'll create an index on two columns because it's going to be task i d. On file name. So click go and what we'll do. We'll actually call this file near for Tusk i d. It's gonna be unique hand We're going to pick task I d on a final name and then if you go on that, see now that's created unique restriction on an image for a given Tusk i d. So the last thing we need to do is to associate this task I d with the foreign key or the primary key in the TBL tasks table. So we click on Relational View and we'll just give it a name so we'll just call this image task i d f care for foreign key. We want to on delete Restrict. We've covered this obviously, in the previous lessons of this course, basically, this allows you to prevent any delusions of updates. If there's associative images, So what we need to do we need to associate task i d for the tbl images table with the tusks db on the table is tbl tusks. The i d is task i d. So that's just the i d. They so that will actually link the said image to a given task i d. So we'll see if that. And now that's done. That is the database table set up ready for what we need to do in the future lessons. 36. BONUS Section 02 - Implement The Image Model: in this video will be implementing the image model, which represents an image. We did a very similar thing for the task itself. This image model will also be responsible for saving and deleting the physical image file to have already got Adam Organ. The first thing you'll see is our HD Docks folder Going to be one controller and then model will just expand them. So where I'm starting from here is the completed task epi I with authentication. So that's just sort of what were completed in the last part of the course. So the first thing we need to do is create the image model itself. So far, right Click new file and what college image dot PHP and we'll start off the PHP file. So a bit like the task we're going to create on image exception class that will be ableto handle our sort of validation errors for the particular image exactly like doing in the task model class image exception extends exception on it's just gonna be Blanc will then create the class for the image itself to create some space here. So the first thing we need to do now, once we've got the class is to create the instance variables that will hold the details of the image. So these are basically the image attributes remember, in the database table, we've got things like an image i d an image title, an image file, name in mind type, and obviously the associated task i d. So we need to create all of these instance variables. And then they get us and sellers the 1st 1 his i d so private. And then it's gonna be I d private title. Private file name, private mind type, Private Tusk I d. We're actually going to create into the instant valuable toe hold the upload folder location. So, you see, on the left, we created a folder in one of the previous videos called Task Image Is what we're gonna do is actually create an upload folder location. So we can just end of this location in the only sort of have to fill it in once. So you don't have to keep putting the obviously that the file location in there. So we're gonna call his Private Lord folder location. So now that I've got the instance, variables for now need to create the getters and set us for these instance. Variables that centers themselves will perform some validation exactly like it did on the task model s soldiers Run through that. We will be coming back to this image model on adding a few extra help. The methods once we start that sort of developing the control of for this. But we don't want to confuse you at the minute because you won't have any context about why we're creating certain methods and what they do so well, we'll actually revisit this file when you know the time is right. Once with developing the controller for the 1st 1 is to get the image i d. So it's gonna be public function get we'll just call this get I D on which is going to return this. Alrighty, Sam. For title public function, get title on Going to return this title file. Name, public function. Get file name. Return this. Filing him. So the next one we need to do is to create a help of function, to be able to get the file extension so public function gets file extension, and what we're going to do here is to get this string Onda, we use a function called Explored. What this allows you to do is to create an Arria of strings beast on a separator. So I was separated is going to be the dot So for example, image Doc G PG So we'll get in a rear back with worn element populate with image and the second element popular with G epic So from that week and then just access the second element on return the file extension. So we will create a local variable called image Sorry file name Port and will use the explored method we passing in the separator So we want to separate based on the dot and then we pass in what string we want to pass So this will be file name so once have exploded it with them. Want to get the last element of that area which will be the file extension So we'll just save that last every element and that will be count in and file me and parts and then minus one promising the world Why am I doing a minus one? So in a really is zero based to access the different elements. So the start at zero and then one. But obviously, when you count in, we're gonna have to elements in there. So we need a minus one to say, Well, get number one, even though that was two elements because started zero So now that we've got that, we can get the file extension. So file extension equals file, knee imparts and then glassed a re element. So now that I've got that, we could just return file extension. Now that one's done, we can then move on to get mine type So a public function get my name type. I just want to return this my type, some of that down a bit. Here, the next one. So what was the next one? Might types or task I d. So public function? Get task. Heidi, return this The task I d on the other one like a c we're going to storing upload folder location. So we're going to just create together for that. It's a public function. Get lords for a location, return this full that location. So now that's the basic getters created. The next things we need to do is create centers for all of these incidents. Variables. Where will people perform invalidation on it. So the 1st 1 is the image i d for public function set I d and will be passen in an I d. So what we need to do here is to check to make sure relative college, obviously, in the database where store and this is a big inch, which is the maximum number is there was named Quinn. Trillion, I believe awas, but we'll just do the same validation like we did with the task i d. Obviously, you can refer back to that video if you want to know what that means, but we're just going to follow the exact same rules on this, so I'm just going to quickly write them in. So if and then it was I d is not know hopes Andi on the rockets or is numeric And then I day cool. If I t it's less than equal to zero. Oh, I d it's less than sorry. Greater than And then it was the nine Quinn Trillion. I've got this written down here, so just be able this that was named 2 to 337 to 03 685 for 77 58 or seven along number to remember that I think of rotted incorrectly, Andi then or this on the score. I day is not equal to no spelling everything. And then basically, what we're doing here is checking to make sure that it is numeric. It is between one on day nine Quinn trillion, um on and that you're not overwrite in the image I d. That's already populated. We can personal to this. So that's why this validation only occurs if the value is not know. So if it doesn't match any of the invalidation, we will through on image through a new image exception and we'll put in a error message here. So I'm just going to write the generic one image i d. Hera. So now that's it's past validation. In theory, by this point, we need to set it so this I d equals the past in i d. So now that the ideas don't we need to create the next one, which is the title. So the image title so public function sent title passing a title on the validation we do on this. Remember in the database itwas Max characters 255 on it didn't loan ALS, so basically need to check the string length of the past in title. So if S t o Len title, it's less than warn. Cool String. Linds Title is greater than 255. Then we need to throw new image exception. Andi. Just a generic message image title era. If it passes validation, they need to set it. So this title equals the past in Title. Started this up a little bit. I don't care. Hopes you can read this in the white space or we've got a bit more room. The next thing we need to do is the public function set filed him. It will pass in a file name. It was a couple of little different ones here that we need to do. Obviously you remember from the database. It can't be No. So when you obviously need to check the length of the string again, brought to the max characters on this one's 30 characters saw We will check that now. So a string Glenn on file in less than warn or as to your land and then file name hopes three of the Don 30 characters we are gonna put additional bit of validation in here using a regular expression saw the file name should only Conte and violent characters that could be contained in the file name. So there's things like and we're only allowed to include like numbers and letters and underscored the dash, for example. But also we need to have a valid file extension. So the file extensions we're going to use here is J epic Giff and PNG. Obviously, depending on what you're developing, you can obviously put your own file extensions in here. So we're going to use the preg much function, obviously, as previously mentioned, the regular expression that we're going to use his out the score with this course. But it's plenty resources on the Internet to sort of get your by on that. But to be honest, you should be able to just substitute any file extensions that I'm putting in here with the ones for your own on. You should just be able to use it as it is basically, so the next one is preg much on takes two arguments. The 1st 1 is the regular expression itself. The next one is the past in string that it's chicken that would be filed here. It does return in number for how many matches it has found within this fucked like past and filed here. So we're going to be checking to make sure that it is at least worn. So because obviously we're doing reverse here to say, Well, if it does not find warn, then we're going to throw a new image exception era. So we needed to not equal to one create that. So was going to start this off with four slash and then a hot. And then we're going to look for lower kids. It is Ed over. Kiss it, Izzet 0 to 9. Aunt, An underscore under dash. Well, them gonna do is then look for the image extension or the file extension. So I was his g p g or Dodger gift or dot PNG. Well, then end the regular expression with the dollar on a forward slash. So now that we've got this, if it doesn't conform to any of this validation that we're going to throw a new image exception, we're going to put in a message here. Image file, name, era, and most be between mourn on 30 characters on. Only be dot g pg dot PNG for Dr Gift. You can change a sort of error message to whatever you want, but that's that's your message. Happen in there obviously purposes the validation there. We need to set it in the instance in this object. So what's this file name set it to past in file new. The next set we're going to create is the mind type tidy this up. So public function set my type. We're just gonna pass in my type. The validation on this is if remember from the database we said it can't be no on did. It must be no bigger than 255 characters. So we're just going to use the string length again as Teoh Lynn on and my type we're gonna do is less than one go RST. All in my type is greater than 2 55 And if it is, then we're gonna throw a new image exception on We're going to see, um, image my type era. Stephen passes validation. Then we will set the local instance variable. So this my type he calls the past in my name type. That's my type. Dune So the next one need to do is thes the tusk i d So public function set task I d Brazilian a task i d I don't get to see what we're doing. So the validation for this is exactly the same actually, as the image I d. So just to see what's appeared time we are going to copy and pierced what we need to do from the set I d and pieced it here. Just see if this type of you know again. So we're going to substitute what we've got. Obviously I d here with task I d I'm just going to replace thes so I d day looks Task i d. And then we're going through a new image exception. We're going to see image task I t error substitute I d for task i d. And then that is the task I d set up created there. So the last woman need to do is to return like we did with the task. We want to return the image. So I guess all the image attributes as in a resource than we can then pass it into a GIs on in court to get oversee the deals out in a college GS on format. So we'll create this. Help the methods or public function return image as Maria. So we need to create a blank area called Image. And then obviously we need to add to this sword image I d. And then we need to use the getters to get these saw this, get I d and then image title. And we're going to use this get title. The image hopes for the dollar sign image and then the next one wars. The file name? I think so. It's just using the getters, obviously, to return these details or get file Name Mitch buying type. Oops. This get get my type image task I day equals. Then it was this get task i d And there was another one we're going to create. I think I think we'll do this now. To be honest, eso if you remember from the demo that after short your previously in one of the videos when we return an image, we actually returned the link to the image as well. So that's things like, obviously you're full, you are l to allow you to then directly get the image, so you don't have to know. Watch the even if you are really is it is returned as part of the attributes. So I think what we'll do now is actually create that help a method to do that. So just where your getters part, we're going to create one to return the image location based, obviously, on this folder location here. So we're gonna public function on. We're gonna call this get image. You are. L so I guess Just explain a little bit. I was is going to be something like I mean, you should use http s in the real world, but I was is generally going to be something like this local horse did idiots slash b one slash tasks slash task idea of C two and then slash images and then slashed the image IDing soldiers he want for that. So we need to actually return. This is a string. So how you build this? So I'm just gonna leave that there for reference at the minute. So how we build this up is the some functions that we can use to return things like the horse name. Whether using the http or https And then obviously, we just can't cut me that together to return the string. So the first thing we need to do is to check whether we're using http or https sort knows what to put in at the beginning. So the way that would do that is we're just gonna stall this and available called http or https. Andi, we are going to use attorney operator here. So we're going to say, Well, his hopes is set server. And then http s we're going to make sure that exists. That was gonna wrap these in brackets. Then what we need to do is going to be some space here, so make sure it's deep he exists. Otherwise it's gonna be http Andi, the server for Itchy G. P s capitals. Actually, P s is on so obviously the server north, where they using http or Https? So first checking to make sure each DPS exists will then checking to make sure it's actually on. If it is, I hope so. That should be on. If it is, then we are going to put http s otherwise, it's just gonna be http, just give it a lot. So obviously a checks Dimitrij to be exists. Then checks deceive. It's on. If it is it Butch. Http s otherwise it's http. So now we can use that build up off see the beginning of the URL. So now I have done that, but we need to get the horse near next, or Horst, And that is also stored in his super variable on. This is called Http on the school forced. So this will be the local horse on the port. So that's what that content. So now that we've got that, we can now start to build up the u. R L. So the first thing we need to dio is the prefix, our sort of B one slash tusks off. See, this is version one of the FBI. You know, let our endpoint or b one slash tasks, which is in this bid, and then what we'll do Well, then put the task I d. Obviously, we can get that by returning the get task i d. So we can just do that by this and then get tusk I d. And then what we're gonna do is obviously it's then forward slash images and then forward slash and then Obviously, it's the image idea, but we can get that using the get I d for the image. So now it's this get i d. So is he was building up the u R l here. So now we're getting I d. And then we can actually return the whole lots or return http or Https And then we're going to upend the cool on slash slash turret, and then we're going toe upend the Horst. So now it is host, and then we are going to upend the u R L the way returning from this, what should get something. Looks something like that. So I'm just gonna tie to this white space up here, okay? Now that we've built the model so far, like, say, we'll be revisiting this toe, adding some additional help of methods, we should be able to test that now. So just as a temple measure, I'm just going to create a new file and I'm going to call it image test dot PHP start the PHP file off, and what we're going to do is just create an image object just to see if we can return it using porcupine energy. It's on response so actually need to includes the image file itself sore require once. And then it is image dot PHP Because we're in the same folder. Like you say, this is just a temp you measure and then we want to try because, remember, try and catch because we're throwing exceptions. If the validation feels so, I'm just going to set me try and catch block ups or image exception the X and then we want to. If he has an error echo era and then the ex daughter get hopes the X get message. So we want to try and create an image now, so we will image new groups. Image. Actually, we need to create the constructive Who forgot about that. What will do? We've got all the ghettos and centers now, So actually, we can create the constructor. So we'll do that now. Public function. And obviously it's a magic methods. Or put the school in the school construct. We're gonna pass in some attributes. 1st 1 his i d. Title file name, mine type task I d. So just quickly go through and set thes. Obviously these will check the validation because we're gonna go set a method This set I d no posse in the i d This sit title plus in the title poops This sit filed in in the file name this sit My type I see in the mind type this set task I D. Plus in the task i d andi. Obviously, as we refer to we're going to set the folder location here. So I'm just going to add that in the constructor. Just this away was said it is a one off when we don't have to, you know, set it every time. I can reuse. See this folder location So it will set this'll underscore on full the location. It's not a methods variable we're going to set not to. So where we at the minute we are in the model folder, so we need to navigate back up to go to power tasks. Images. So it's up one folder, which takes us to the one open folder again, which takes us to HT docks upon four again to call to the mom folder and that gets a cell, tasked images. So it's hoped three times and then it's tusk images. So you say that is how we're going to use this upload folder location to return it in the image model. So now that we've done that or to say that and then we will go back to our image test on, we will start popular in this. So we've got i d title filed, Liam Mind type of task i d. So I d I'm just going to create born with number one and then it WAAS title. So I'm just gonna say image title here. The next one was the final years. I'm just gonna call this image warned or g a pig. And the next one was the main tapes on this corner. Right image. She a pig in the last one waas the task i d. So I'm just gonna write three on there just for just what's different of the image I d to test for work. Okay, so no need to set the header. You see, this is just more sort of a test for what we're doing. You won't use this file oversee in real life. I just want to prove that I have made any mistakes in the image model just yet. So content, um type and it was application slash gs on and then it was sharp. Set equals utf dash it on. We want to include it. So Jasan in court on this is obviously where we used the return image as a really So it's image and then it is return image as the re function. That's what we should be able to do now is all imports mine up. Try and run at this image test file And what should be able to get something back if we have done everything. Okay, so I'm just gonna impose man, it's a get request. I'm just going to write in http local Horst ported it. It'd come using month V one tasks. Actually, I'm gonna go directly to the model folder, so it's very one slash model and then it was called image test dot PHP. So fighters run. Not We've got an error here, so we'll just work out what that is by going to our mom. Pop log files. Ogata PHP error here. We'll just double check. So I've got a syntax error, So I've made a spelling mistake online. Nearly one, so I'll just double check that now. Just bear with me one second, Blaine 81. So if it'll check that up, I've made a spelling mistake there. So throw new. Hopefully, that's the last ever message would get. So we'll just try it again. So we'll go by the postman or run it again. Get stares of okay, But it doesn't look right, because we're not actually getting anything back out. We've got no till. Just double check this out. Probably made some sort of symbol era. Um, we will go to Atom and then we will double check our image because return and no. So I don't think returning anything yet. Well, forgot to return that. So it will return the image itself. That's a silly mistake. So hopefully this time we'll get there. Eventually. Total open post. Mine will try it again. OK, we're getting somewhere. So now you can see we are getting 200. We're getting the obviously the image object returned. So image idea, one image title here, obviously the file name the main. Take that task I D. However, I've just noticed that I have also missed something else off, which is if a school back upto what? The method that we've just created, which is the get image. You or l toe actually need to return that as well. So after task I d image and then it's image you are l on. We will use this. Get image. You are ill. Okay, So now if we go by the postman and when it again Okay, you can see here Hopes I forgot it slash There This is all part of testing. You see, it's it's good practice. So images slash that we forgot the tasks or forgot to put a forward slash It should be slashed. Tusks slash task I d slash images. Hopefully this type we will get there, right? Local horse, Yet that looks fine. So that would take a dire Obviously what happened demanded this yet, but that would take a direct to the image itself based obviously on the image I d. Now, if we do something silly to to cause an error, we should get something like an error message out. Just proves that our validations working over Go back to Adam. Andi, go back to our image test on if we do something like, um, if we change a file extension, that should work in theory, Sore Doctor your C X, which is a word document. Hopefully, we shouldn't be able to retrieve. You know, it's set that. So now if we go back to postman, you can see they were actually getting an era to see that it must be between 1 30 characters and only BG pay P and G your gift file. So that proves that our validation is working. So for Go back, Teoh Atom. I think that it I think to be honest, I think we have created the image model. Now we obviously will return and legacy will be returning to this toc at some help of functions. But that is the first part off the court created for the image model. 37. BONUS Section 02 - Implement The Image Route Logic: Now that we've got the image model set up in this section, we will implement the routing logic in the new images Control of file. This is what dictates what, http methods and roots are allowed. We're going to write this control in a slightly different way. A few students have asked why all of the court was developed in this course is in one large block rather than separating it out in the different functions and files Well, the answer to that is have tried to focus more on the principles of teaching the subject of rest rather than the principles of object oriented programming in application architecture . If I created model files with lots of different functions than, in my opinion, it would be a lot more difficult for my students to focus specifically on the rest principles. It is up to you as a developer on how you structure your application. I'm specifically teaching the principles of rest and how you can implement them using PHP. So in this control, I'm going to create some additional functions to separate out the logic for each route, just to show you the principles of how you can start a structure your application, but I won't be doing this for all possible parts that could be moved in return functions, as I feel it distracts from the subject of this course. But basically, if you think there's a better way of architect in your application, then feel free to do that. So if that being said, I'll open up Adam and will start creating the images. Control a file to right click new file McAuliffe images dot PHP. So this is the images. Control a file. Create a new PHP file, and we need to include the three files. One for the dear to be is one for the response and one for the image, so I'll do that now require once the 1st 1 is db dot PHP. Because that's how a database connection require once the next one is our response model. So we'll go over folder because I needed never get to the model folder and then is response . Stop PHP! And the next one is finally our image model sore require once model image dot PHP. And like I said at the beginning of this video, we're going to create some help of functions here. So The first function we're going to create that helps us out is a function that builds the response in one line. So previously have had things like create a new response. You set the stage discord. You said the success variable had any messages and things like that. But we're going to shorten that down to create a help function for that. Now, technically, this is the part where you would put this function in a different file and what you would want to do is actually share this file amongst your other controllers. We're not going to do that. They don't want to get into sort of re architect in this application that we've got built. I want to focus specifically on rest. But this function here, you would actually put in a different functions file and then include that functions file within all of the different controllers where it's going to be used. You sort of see what I mean. Once we start developing this, so we're going to create a function and we're going to call it send response on. It is going to take some attributes. So the 1st 1 is the status cord the next one is success. Next one is message. Now, some of these are going to be optional parameters. So I'm just going to default them with No if they're not provided. But the next parameter is to cash that that was false on the next one is Deirdre, and we'll set that to know. So basically, we could send a response with just these three. Sorry, just these two attributes here. Andi, it would default all of the rest if we don't provide any. So the first thing we need to do is set of a new response. Object response. And you response. So this is just like what we're obviously doing in the tasks offer. Just quickly navigate the task he can see here. That here's an example. So we're gonna create helping method. That's what it does this for us. So offer close. Touched down for the time being. New response on. Then the first thing we're gonna do is set status Court Sore response. Set. Http. Status court. I'm just gonna pass in the steer. This court Was he from the past in from literally the next one is response on. Set the success and pass in the success attribute on the next one want to do is if we passing a message. So if message is not no, then we want to at the message to the response on, obviously posse in that set message. Otherwise it won't call that function. We don't want to add a new old message. Basically, obviously, we're gonna hard to cash. So if we're going to catch the response, hopes to cash tell us what expelled on We're just gonna pass in the to cash parameter on the next one is check to dear there. So and if we do an if statement So if data is not no, then want to out the deer there to the response. But it's that data and said the dead here on finally, we need to send on exit. So, as you can see, just going to get rid of these white spaces have created health a function here called send response which will take some arguments on build the response for us. So instead of having all of these lines of cord, even though it's very specific and it's good for sort of being able to see exactly what you're doing, we're going to a sort of branch in tow, worn sort of method, so we'll use that later. So for the time being, we're going to just fall this down talk and see where we are. The next function we're going to create is the check authorization status. This is the simple. It's exactly the same, to be honest, that we've used in our task. So when we added the authorization script, which checks to see if the access talk and violent on all of this, obviously this is going to be used with our images as well, because we want to add authentication to the images. We don't want to be able to, you know, for people to access the images for tasks when they don't have access to them tasks. This is another sort of part of the script that you can actually put into a function. Put that into a separate file and then include that in every control of that requires this function. It just saves taping all the logic out again. I'm not going to restructure this task controller because obviously that sort of door to re architect the application at this point, but that's what you do. What I am going to do, though, is actually just take a copy of that to save us some time. So what of writing it all out? Because that specifically their section is concentrating more on images. I don't really want to go through this again because we've already done that. So I'm just gonna take a copy of that, and then I'm going to create a new function, and I'm gonna call it check orthe status on bond return User I d Iraq. You need a pass in the database connection here. We'll get onto the database. Connection shortly Will do in a second. We just want to create these functions. So we're going to pass in the right Devi want to actually create the connection. But this is just the sort of function body. So I'm gonna do I'm gonna piss that in there and you can see obviously we've got all of our stuff in there. I'm just gonna leave it as it is. The only thing I am going to change is that we're that we send responses back. So just gonna change this slightly because we're going to call this function rather than actually have the response all of separate. It's just a way to show you how dio you know how to use this new function that we've created here. So I'm just going to change this slightly. So first of all, obviously what What messages here? So I'm just going to create a no messages, and then what I'm going to do, I'm just going to run the same checks to see if we need to sort of at the message. So we're just going to run the same check. So if is not set, aunt, it is server http. Authorization. Then we're going to set the message to access. Talking is missing from the header on. The next thing is else because they have made a spoon estate This all this change that so else. If string Lynn and then it's server BS. I'm just re factor in this beauty to fit in with what we've done. You actually pay authorization is less than one. So obviously that's that if it exists, Butch, it hasn't actually got a value. So then we'll not the message, um, access hopes. Talking cannot be blank. Okay, so now we can actually get rid of this because we're going to call this function here. Instead of all of that sore, we will call send response. So we're going to pass in the status cord. Whether it's a success in any message to the Stairs court, which is gonna follow. This is for a one. The success would be false. On the message would be the past in message. And now, because we're doing kind of the senden and exit sort of in the function as you've seen previously, we don't need to call that anymore. So I'm actually just going to get rid of all of that. And I'm just tired of this space up here. So you say instead of building the response sort of line by line, we're actually just created a helping methods to do that. So I'm just going to quickly pass through this down here to see if we need to change these response. I can see that we do here, so I should be able to that before a warn. It's false, and I'm just passing the messaging. So actually, I should just be able to copy that function head of the and replace this whole thing with this So obviously we're person in a specific message. I'm just gonna move that message and put it there. So now I could get rid of all of that. So you see how have gone down from, like, two for 67 lanes down to one lane? I'm just gonna take cover, guys, because we're probably going to replace it further down. Say, here. Here's another response. So for a warn False in which is going to take a copy of this message and paste it in there , they wouldn't get rid of all of that and wouldn't have one lane. Instead, I'm just gonna carry on doing that for what we've got here. In that era. Messages user account is currently locked out. Replace that. Still a fora want success is false. Same with this one to ascend response. Put it there for a one false, and we're gonna copy that tax has talking expired. So now, which is cutting down lots of sort of lines, actually Well, because we just gotta help a function here and told his copy this again because it's their response on this one is a 500 sold change after 500. It's false and I'm just going to copy this message and put it there. We're going to get rid of all the fact to see if that and obviously now you can see that it's dramatically cooked down all of the lines that we've created previously and obviously in the course. So the last thing we need to do to this function is to return the user. I d talk because we're in a function now. We're not actually gonna have access really to these local variables. So I have to pass out the the the user i d. Once we've retrieved from the database is so away we respond to that is just down here. So just after this check here. So if it's passed all of this validation, we can now return the you returned user idea. So return. And then it is the returned user. I d. From up there, that's the one that the way a returner. So now if we have authenticated, then we get the returned user i d, which we can then use to sort of access the tasks and images that belong to this center user. So now that that script doing, I'm just gonna minimize that sort of folded up on fall. The send response function. Oppa's well, it just titles adopting. See where we are now. So we are going to create obviously some extra functions in here to deal with all of the different routes that were going to be using. The roots that we're going to be creating is the one to get the image attributes so that would be slashed. Tasks slash tax Guidi slash images slash image i d slash attributes So that will return the attributes Energy Asan format. The next week we're going to be developing would be the one that returns the image itself, so that would be slashed. Tasks slash task i d slash images slash image i d. So this one will return the image file itself and the next route will be creating is the slash tasks slash tusk i d slash images. So that's the one that will be using to post against. So that's the one that will be using to create images against a set task. So actually have to go through and create these sort of, if else, if statements to recognize which route we're actually going to from that will actually updated to the HD access file as well. So the first thing I need to do is obviously connected the deer dubious. So we'll set that up now. So obviously, as following what we did with the tasks we do, we wrap this in to try and catch till it's try. And then it will be right D B and then it's DP and then connect right db on the re debate. And that will be a DP connect. Read Devi. And then, obviously, if them feel, then we want to catch them. So for to catch and then it will be pidio exception, and then we'll just call it the X on. Well, look this out to the error log. Remember, Obviously, when we created the task controller, any database connection errors or any sort of sequel errors, we will lock them to the internal era log. So we a system at Mons and developers can actually see what's going on. We never want to sure the user the actual dear dubious connection error because it could give up sort of user credentials and things like that. Obviously I have explained that previously, so we use the function called error log Onda. We pass in the message, so I'm just going to write connection, Kara, and then we're going to appendage e every message he saw. The next thing we need to do is obviously send a response. So send response. This is obviously gonna be address on response. So it's 500 error. It's going not going to be successful on. We're going to just pass a generic message called Did Abyss Connection era. Okay, so first we need to do is I'm just gonna put a comment here. This will be image attributes, So that's gonna be a slash tasks slash task i d slash images slash image i d slash attributes. Okay, so we need a pass in. Obviously a task. I d an image i d andi obviously checked to make sure that not know and stuff like that. And obviously we need to check to see if it's got the attributes. So we need use The RIA k exists again. So if we do and if stem it so every que exists on we're checking for tusk I d. Within the get global variable. It's gonna create some space. Yet Andi a really key exists for image I d. Within the global get variable. Andi A Reiki exists for attributes. Oops! In the global groups Get variable, Get out of this white space then we want to. So the first thing we need to do is get obviously, get the task I d get the image. I didn't get the attributes from the query string, so this is no different, really, when we're messed about with them sort of getting getting the task so we'll get the task idea and stuff like that. It's very similar sort Task i D. And they were going to use the get until come in as Tusk i d. The next one is the image I d just do the same. Mitch. I d. On the next one will be attributes to make sure that exists to make sure on the right route attributes. They would just need to perform some simple validation to make sure that you know the are numeric that's been passed into the task. I t in the image I d. So we'll just do that quickly. Now sort image. I d make sure it's not blank or it's not numeric. So is numeric, So image I d or the task i d. Hey is if it is blank. Oh, if it's not you, America hopes so that's task I d. Then if it fails, that validation will send a response is now function on. It's gonna be a 400 cause it's a client era. The sort of client has sort of added some incorrect did when they it's gonna be false on. We're going to see just a generic error message Image I D or Task i d cannot be blank and on most bay numeric. So if that, too, is past validation, then we need the check. Whether the request method is it get are a patch because generally won't allow delete on attributes yearly, they overwrite them or you'll delete the entire image itself. But it's completely up to you. Depends what you trying to do. I'm just gonna create the if statements to check to see if it is get. You could use a switch statement here. My preference is, to be honest, is to use if statements I just fight them a bit clearer, to be honest and that, you know, that's personal preference so save, uh, request method. So if that is equal to get else if server request method is equal to patch ups, courts or, um else and what we're gonna do for the else it's just a four or five for the request methods not found, so we'll send the response back. Four or five chord False for success on the message is request method. Not a lot Well, sort of pre Feliz, surely Just concentrate on getting the body sort of set up at the moment. So now that we've got the image attributes root sort of ready will now implement the get image. So specifically, the image itself route now saw what will do here's else if and then we will check for a reiki exists. What will happen for here is just the task I d on the image i d so freaky exist. Task I d. Andre three k exists for Oops. I forgot to put the get on there toe less on the get variable. Enrique exists for image I D. So this is basically saying if it just contains that's or slash test slash ward slash images slash five, but not the attributes. So this is just specifically for the image itself. So I will just copy appearance that just so we can see where we are here, he's gonna put it, put it there. It's just for our reference. That's really so we know what it's for. So the image I d and then we'll come back to this and put the get in there. Onda, we need to copy these. You can probably right now yourself. I'm just gonna copy paste them because we're still retrieving the same things. Then we will do some validation on that as well. So we'll copy this, too, just to make sure that there exist on bond that they're not blank on that the numeric So now that perform the validation on that, it's now down to check in the if it to get or delete because we want to be able to get the image itself or delete the image itself. So I'm going to do if survive request method. And if that is equal to get on the next one Waas He was still it wasn't it so else if server request upset spelt wrong again, request method equals delete um, an office development match or else if it's if it's not, get or delete, then we will send a response back. Actually, I'm just gonna copy last just to save time. So send response four or five. Request method not allowed. And I guess the last route we need to create is the one that handles creating oven image. So this is where we're just posting too. So I'm just going to put another comment that slash tasks, slash task I d slash images. So this one actually warned, Contain the image i d. So we'll just be checking for the task idea on this one and make sure that the image I d doesn't exist. It'll start that now. So it's it will be else if they're following on from the branch of the If statement was a lot closer. So that's more obvious. So else if every he exists and we're looking for the tusk, i d. Within the get variable aunt, we need to make sure that the image I d doesn't exist. So not every he exists. So office, the way this is false on way living for a majority here within the get variable on will create the body for this. So this is just for posting only. So won't be you can you know, we're not going to set a route up that will delete every image against the task. Although you could. But generally you would get a list of images for a set task, aunt, go through them individually and send a solidly request to that. So for this route, only we are just accepting. Paused. So the first thing we do, I guess, is to perform some validation on that, just like we did with the other one. So I'm just gonna copy these ones piece. Then they get rid of image idea because we're not contending that on then, obviously deleting the validation on the image I d andi, change in that task, I d cannot be blanks. Almost have a task I d passed in that BSE, seeing that make sure image I d doesn't exist in the u. R. L. And it doesn't on this case. It will then check to make sure that the request Method soul server quest method and that is paused patch then was he will carry out lots or else. And we're just going to send a standard ever back here. Four request method not found, not allowed. And we'll see if that so, I guess. Lastly, what we need to do is do a catchall sore else and then send in point not found. So send response. And this is a 40 fire er so if none of these you are Ln points or roots exist, then we're just going to send a four or fall back false on in point, not found, so that if all the other routes don't exist, you know who tried different routes, it doesn't exist. What we need to do now is to alter our HT access, file to office fatigue and recount these new routes that were created. We've left these blanket the minute because we are going to create functions for this. But the 1st 3 what I need to do is actually up there the HT access file. So from here, go in to see the V one fold, and we've got tht access within their. So this is our one that we've already created previously, obviously, in this course. So I need to add a new section two this and, um, which is going to call it the images. And then obviously it's rewrite rule groups of Con Spell and then it's rule. And then what we're going to be doing is looking for the 1st 1 going to look for is obviously slash tasks slash tusk i d. So this will be north to nine with the plus and then end the regular expression, so slash tasks slash task i D. But first we need to put So this was gonna be slash tasks. Last task i d slash images slash and then an image I d obviously also in number between North. Well, I guess not between North and nine, but contained valid numbers. And then he's wanted going to be a slash attributes. So we will right here, control because this is obviously what maps to control us slash images dot PHP task i d equals dollar warned, because that's the warm or encompassing day on the next one is. So it was image I d was not yet image I d equals dollar to because that's what we're capturing there. Andi, we're going to specifically say that the attributes so and attributes equals true on. If it does find us It's the last rule L process, and I will just put a comment on here to see handle image. Um, I d requests for image attributes, Hopes can't spell attributes. So that's the get image attributes. The next one we need the right three right rule. And then it is So will be tusks and then Tusk idea again. So not nine. And then it will be images slash and then an image i d, which is not to nine as well. And this maps to till controller images dot PHP and this will be tusk I d equals the warn onto the image i d equals two. So obviously he put the thing in for the last group on. Just comment. Handle, um, image itself. So that will return the image itself and not the image attributes. And the last one we need to do is thea just slash images toe handle the poor started creation request. So rewrite rule tasks slash. Um sorry. Put in brackets because we need to take this into the URL itself. So north a name for the task. I d slash images and then and the regal expression and this one will be controller slash images dot PHP and this one will be just task i. D. So task ID equals one on a hill on a quick comment, so handle image request for Post. I guess that's fine. So that's our three routes actually created in the itchy access rewrite, So that would be such tasks. Slash task i d slash images slash image I d have missed out a plus on there. Make sure you put a plus there and then slash attributes. So that gets the image attributes that maps to this query string on obviously weight check in within the logic of the if statement where the task i d image I d and attributes exist the same for this one. So this one will handle slash tasks. Last task. I d slash images slash image i d. So this is actually getting the actual image itself. And then obviously the last one is last house Last task. I d slash images and this one will handle the post request or creation of it. So now that created that we can close the HT access file down and takes us back to our image controller so we could actually do now is fire a post mine and just make sure I haven't got any syntax errors at the moment. We're not going to really get anything back because we're not actually on, you know, successful requests for the route. We're not actually going to get anything back, but I just want to prove that we haven't got any syntax. There was just yet. So if I open a postman, it also proved that I reached a access file is working as well. So, http, and then it was local Horst port 80 Idiot slash and the one slash tasks slash tusk I d born and then images. So send that. We've got an internal server error, so we'll just don't check what that error messages. So we're going to find the applications mumps, and then we've got a logs file, and then we could hoping that up on that one there we have an unexpected clearly bracket online 34. So if you just quickly go back to that in atom, So like, 34 school all the way up on hopes I've closed that accidentally. Um, so lying 34. We're missing a seven call on there. Football to them to go by the Post mine on Just send it again. That's fine. Request method Not allowed. So that's sure. Is that our responses? Working Because on the slash task slash task i d such images that should only be opposed. So we just pause that we're getting a 200 legacy. It won't do anything in a minute because we haven't actually implemented the functionality of that, but just proved that I was. Syntax is fine in the file. Now. If we put in slash images slash image idea of one, you can see that we're trying to pose to that. But we can't, which is correct, but we should be able to get that's fine. 200 aunt also or delete. Oops. So that's fine on if we try on and do something like a patch because we don't patch the image where perhaps the image attributes get a full roll five, Which is correct. And then, if we right attributes on the end on, If we just get that for the time being, that's fine, because we can get the attributes we shouldn't be ableto paused. So that's fine. That also working we shouldn't be able to delete that also working but should be able to patch. That's fine. So you can see there that actually our logic on syntax is working correctly. Obviously like to see it doesn't do anything just yet, But in the next set of videos, Well, actually, implementing the court that allows us to up Lord sort of the image files against the task. But in order to do that, we must turn on the check authorization status on return. The user I d purposely left that out at the minute because I just wanted to check to make sure our file that would create it didn't have any errors. It did actually have two areas, as you've just seen. But you should be able to sort of enable that now. So before when this video will just quickly enable that. So what we need to do is just underneath this check or status and return, we just minimize thes on. You will see just before the implementation here for the different routes, we are wanting to perform that validation check for the user. Obviously it does pass back user i d. So we're going to stall out for future So if we call that returned user, I d. I will call this function, so check all status handle, pass in the right, db remember, that's one person in authentication should always be done against the master database. Now, if we try and go back to post my now, in theory, we should get unauthorized ation error because now that we've been able the authorization check So we just got a poor smile on. But if you just try this patch one So you say they're now authorization is being turned on for this route. So obviously, don't be left on now because we'll need it to implement all of the different all the functionality for the different routes. So I guess that's a good time to sort of stop this video here, ready for the next set. 38. BONUS Section 02 - POST - Implement The Upload Image Route: In this video, we will implement the upload, image and image attributes functionally, which uses the pores to http Method Toe will open of Adam. And from here you can see that we're in the images Controller. Now, just a quick tip. What I want to do is actually falled all of these sections up just so we could see exactly where we are Record edit, You got falling and then you can see fooled all. So now you can see that were folded up All of the logic that we've already built in the images control of sorting see exactly where we are What we're gonna do is implement the post method, which is in the slash task slash task. I d slash images. So just expanded that else if and just expand this bit of logic here just so you can see where we are Services previously mentioned. We are going to implement this within a function that we're gonna put at the top of the file. It just makes our logic a bit clearer. So this is where we're going to call the function within the post. So what we're gonna do first is actually create the function, so I'm just gonna put it after send response on the corner, Call it function Cook Lord, the image route. It will actually take in some arguments. So we need to pass in the database connection. The both read and write. We need a passing the task i d. So we know what task to upload it against. We're then gonna obviously adding I were returned. User, I d which is this bit here. Obviously, we're going to call this function down here, so all of these variables will exist by the time we call it. I'm just gonna add these arguments in now, for the 1st 1 is re debate. Next one is the right Devi, then Tusk i d. Then the returned use variety returned. He's a righty. So now that we've got the function body there, we can actually just put it in down here to call that. So we're just gonna call it here. So, Lord damage route, And then we're actually gonna pass in these variables from obviously what we've got further up. You're passing the reedy being the right deep, but you can see that they they So it is going to pass these in now this up. So read DP right db Next one with the task i d. Which way getting from appear Task I d. On the other one was the returned use a variety which we're getting from our authorization check function Here you can see that that stores it in a user i d variable. So now that that's implemented, that's all we need to do in the image logic and all the logic that we caught a bill is going to be in with didn't its function at the top. So I'm just gonna minimize all that down now because we've done that bit. We'll start with the image route. So the first thing we need to do is set up to try and catch. So try and then catch. And obviously, because we're dealing with database connections, we need to catch a PDO exception. So I hope PDO exception The X on the other catch statements were going to be dealing with images. So when you deal with the image, hopes catch image exceptions in which exception and we'll call this e X. So just implement these bits of logic now because all we're doing is basically gonna send in every response back. So PDO exception. Remember, when we deal with the basis, always log it out to the era Log on, will call This go did obvious we re era and then hopes then output the exception. Andi the every response was sending back. So send response memory using the function. It's not It's a 500 it's false on. We're just gonna put a message in every message here, feel to cook Lord the image. Okay, well, we'll come back to this because we need to check if we're in a transaction but will come back to that at the right time. So the next one is the image exception error on DFO. Just send a response back and we'll call. This one is 500 false, and we'll just get the image exception era. So this is a X. Get a message. Okay, so that's the catch disordered. Just gonna create some space so and see where we are. Okay. So, logically thinking about this, we are going to have to perform some validation, First of all on the post request. So we need to check the content type also need to check that the past in task I d exists for our user and that we're not trying to, you know, sign an image to another user's task. And then, obviously we're gonna do some validation on the attributes that were passing in as well as the file I will passed in. We'll start off with the content type, so we'll make sure that it's set. Andi, if you remember, I think I've still got it here. But remember, from the Democratic give off the image of Lords epi, I I think I've still got it. Or been in Postman you can see here we're body attributes. There's obviously there's a field called Attributes which way using to put Jason him, And that's obviously the image after beats themselves. And then there's another parameter call image file, which is the file itself. Now what you'll see in Postman click on Headers and by the way, this this version of Portman slightly different to the one in the early videos of the course. A lot of the headers and now hidden by default. So if you can't see it, if you just click on the name well, I've got name hidden headers, but yours may be different. You'll be able to see that we've got a content type and we've got multi parts like form data and then a boundary, which is calculated when we send the request. Remember, the boundary is just sort of a random character string. So that's what we've gotta check. First of all, in the logic to make sure that we've got a multi party formed. A A content type on the boundary is there. So we'll just go back to Adam and implement that now if the if is set, or if not said, um, server content type. So if it's not set, we're going to create an every response. But also, if it is set, we need to check that it is a valid content type. So we need to do S t e R P us. This is a string position, so we're going to check that the multi part slash form data exists in the content type because obviously the content type contends the boundary as well. So we need to just check that the multi parts life form data exists somewhere in that content type, so we use drink position on that should return false if it doesn't exist. So we're going to check for that. So string pause and then it's server content type and then takes a separate one for the string that we're looking four sorts, multi parts life form Dash theater called Semicolon boundary. And then it's 500 equals. So if that is equal to false, then we're going to throw the never response. So send response on it's gonna be a 400 causes the client issue. It's not gonna be successful. And then the message we're going to write is content type. I had a knot set to multi port slash form data with hopes Minutes for Mr There form theater with a boundary. Get the next validation. We need to do like a C when you check in the database to see if the tusk exists for the task I D on. Obviously, I will use a righty, so we need to run a query against the database. So a query and then hopes. And then we'll use the re database for this because we are just read and agree dp pre here on the sequel Query is select i d from TBL tusks where I d vehicles passed in task i d andi user I d equals the past in user i d hopes trusting user. I d. Okay, we will bind the parameters. So, Queary find Haram on it was the first ones task i d I'm gonna find that too. And it was the task idea that were being passed in. What's not that one? That one there. So we're gonna bind that, too, That we retrieved this from the past in u R l query string for task i d. So that's how we get it. I was called back Opus or task. I d aren't. It is a PDO, and then it's prom into furniture. Queary change, Haram. I hope so, Andi User, I d. And we're gonna passed in with the return user i d. And that is a PDO Haram signature as well. And then we will execute it. Cleary, execute. Right. So now that we've got the query, we should be able to run a count on that to make sure that there is a least one task for that given task. I d under provided user. I d told you. Roll, count your account And then it is Queary. And then it's rule. Come and I will need to see if it is zero. Because if it is zero, then we need to go through a four for not founder. So we'll count people zero. So we'll send response 44 falls on task not found. Okay, However, obviously, if it is found, we now need to perform some additional validation on the attributes that were provided in the response body. The first being attributes. So we need a check to see if it exists. So the first thing is, make sure it's set. He is set parent. It's within a post. So attributes make sure it exists. If not send response on it is 400. There are false. We're going to say attributes missing from body off request. So now the next validation needed. Do we need to make sure that the past in attributes is in a GIs on format, so will try and record it. So what we're trying to do here, So Jason decode on that will return false if it is not. Apologies on, but if it is valid Jeez on We want to stall that in a variable. So the first thing we need to do is put the exclamation mark because that means if it false , and then if it's true, we need to stall this in available call. So we'll call this Jesus on image attributes and will stored in that on the function is Jason record like refuse previously on and it's in the post global variable cold attributes . So if that false, as in it's not valid. Jason, we need to send in a response. Backs or sand response. Andi. It would be a 400 client error. False on. We'll see attributes. Field is not talent Jasan Yes, on hopes. Well, school down a bit. So now that we check that, the next thing we need to do if it is valid Jasan is to check the Js on attributes within that saw, the first ones obviously were given the title. Andi ive file name. So we just need to perform some basic validation on that. So if title and file names not set so we will use the is set. Andi, the GS on should be stored within this genus on image attributes or Jesus on image attributes. It would be called title. Oh, the file near was not set final name or they are blank. So she's gone. Title Gold's blank. Ole, do you sell on average Attributes file name Nichols Blank. Then we'll send it error. So sent response on it will be a 400 false on title Andi file Name fields are mind tree gears allowed to check this either exist both the title on the file name going back to course, Mind you can see that we're person in title and we're passing in file name. So we need to make sure that there exists and that they're not blank. And if the are they will send in every response back, however, of the fine, then we'll move on the next part of the validation, which is making sure that the file name doesn't contain a file extension. Remember where it was passing in file name. We're going to automatically determine the file extension from the file type that we upload . So how you do that is we use string. Pause it again. So we have a look in the string that we're going to check, as in the file name string, to make sure that it doesn't contain a dot So we lose. Str p us on that takes two attributes, which is the first is the string. So that is GS on image attributes on the file name and the second parameter that attics is what you're searching for within that string. So that is a dot So this will return the position. So we need to make sure that it's greater than zero. So if it does contain a dot, then we will send an error response and response on this will be 400 falls. And the message will be, um, file name most not content file extension. A lot of this validation. Obviously it depends on what you're developing. You might not go, you know, into this much detail and obviously depends on what fields that you're actually up Lord and against the image. So obviously this is all relevant to this e p. I like we're development, but obviously you can substitute out these different validation checks based on the the project that you're doing. Okay, now that the title and file name has, you know, have its validation checks when it now need to make sure that the image file is provided. So that's the file itself. So we'll use another if statement. And what will do here is within the post request. If there are any files, they will be in a files global variable. We'll be able to sort of check to see that exists within that. If it if that this file does exist, there is additional meta data that's uploaded with the file. The client base. It does this on your behalf sort things like that name that's being provided, you know, the file name itself. That's before we do any manipulation on the file or or the file name. So that's the firelight you provided that you know the actual name of it. Things like errors soffits feel to a Plourde also things like size of the file and will be doing some checks here based on three things. The 1st 1 is the file size because we're going to limit the file size, we're going to say, Well, the image file itself can be greater than five megabytes. Obviously, that's arbitrary. You can set that tow whatever you want. I'm just going to say five just to show you how it's done, Andi we're going to check to make sure file itself has being applauded that there's not been a problem Applaud in the file on that. We're going to determine the mind. Type off the file itself, so we'll use a function to get this file type. The first thing we're gonna do is to make sure that the file is actually being provided, so we'll use Theis set on it within the files. Global variable on. Obviously, this is the name of the attributes that you'll send him with Your post requests Why was is called image file. So that's the name of the attribute here called Image File. And you can see this is a type of file. So if it's not set, ah, it has not. Bean applauded correctly. So files image file and then we can access and error hopes, not trippy in courts looking access, and every within that on. It should be zero if it has uploaded to the server. Fine. Now, when Europe Lord, using PHP, it stores it in a temporary folder, will get into this a little bit further down here, but just to give you better background, it does upload it to a temporary folder on the server. Andi, if you haven't done anything with that file once a script ends, that file will be deleted automatically so we don't have to deal with the tidy up. So what we have to do is part of obviously the Lord is Then move it to where we want it to go. So after we've done that to them, we can name it whatever we want. So when it uploads, it uploads to attempt to fall on the files. Global variable should contain an era of zero nor errors. But obviously, if it does contain an error, we'll send in every response back. So send response on this is gonna be a 500 error, because this is more than gets a server error. False aunt, where the message wake one right is image file up, Lord on successful. Make sure hopes. Make sure you selected for help. Okay, so that now that we've got the file, in theory, that's passed the validation. Now that we've got the file we can use, we're going to use a function provided by PHP called get image size a little bit misleading if you just do a little bit of a sort of look up on the PHP documents about this. It actually checks the file that you've uploaded to make sure it is an image file. And it does that aunt. It provides a lot of metadata about the image itself. So things like the dimensions of the image, the main types or what type of file it is. Is it a J peg? Is it a gift file? Things like that. So we're actually going to use that to allow us to do some validation on it. So we will check here, call it image file. Details will call it on like a sea of cold catch image size. It takes in the image file location. So, like I say, it does upload to attempt a folder on the server. And you can get this by providing some data from the files array till files. Obviously it's image file. And then, just like our access to our error is another part of information here called TMP name. This is where it stores the file temporarily on the server so we can get some details from that and then obviously performed some validation on that. So we're just gonna look not function and save it in in a variable here. The next thing we're going to do is check file size. It is set. Oh, yeah, if it is set on, it is files image file and then cold size this one. So if it's sit on bond, then we can check the file size itself. Sorts, files again image file and then its size if it's greater than five megabytes. But obviously we this takes a parameter, but I've seen you check against bite. So five megabytes is actually 5 to 4 to 88 0 bytes, So we're making sure that the size exists on. Then we'll check the size so we'll send in every response if it is greater than that. So what hopes that 400 error this time? Because client issue false on the ever message is file most shape on the five megabytes. Okay, now let's make sure the file size is fine. We can then go on to check to make sure that it's valid image file in that it's a Jeep A. It's a gift or a PNG, so I'm just going to store what we are allowing in a nunnery just so we can check against this area. So we're gonna call this allowed image file types. It's an Arria on the mind types for these or image slash g a pig Northey Ian J. Peg. The next one is the average slash gift. Next one is image slash p entry. So these are the three file types that were going to allow, so we need to check against that. So if it's not in this serious off, the main tapes not Ajiep ignited give for a PNG, then we're going to throw in a response. So the well, I would check that is used in every year. Soffit not in the area. Andi. It takes the mind type itself. Sor we're going to use this image file details because that contains the mind type. So image file details on the mind type is just called my And then obviously this in a re a function takes another parameter for the area itself. And it's allowed image file types, so it's not in the area. Then we will send an error response on that is going to be 400 error. False wake. Wanna write file type not supported. Obviously, these are all configurable. Based on what your specifications is for the FBI, you can't allow upload of sort of document files. Although you wouldn't use get image size for documents. Obviously, this is specific to images. So you would have to use a different function to obviously do some checks on to make sure that the valid mind type for a document. There's plenty of resources out there about my types and how to retrieve them from different files and stuff like that. Okay, so the next thing we need to do is most validations don't. Now, we now need to determine the file extension based on this mind type. So we're gonna use obviously the image file details again on the mind, and we're just going to obviously check which one it is, and then apply the relevant file extension against that. Just a demo purposes. You can use an if statement. I'm just gonna use a switch statement here just to show you this intact so that if you don't know what you can just use an if statement if you wish. So we're going to write switch. I was going to get rid of that order complete because I won't actually write it out in Suria. So switch and then we're going to use image file D deals, and then it's against the mime. And then what we need to do is the first thing we're check is a kiss. So if it is image slash gyp egg cups, then we will set the file extension. Actually, what needed to first is create a blank file extension variable file extension, because then we can check it afterwards. So file extension blank and now lives. He will perform the checks or file extension we set out to be Dr P. G. And then we need a break after that because we don't want to fall through onto the next case statement. So kiss what I'm gonna do. I am just going to inset these a little bit sorts more clear. And the next one is image slash gif on. We will set file extension for this. Warned to be dot g i f. And then Rick in the last one is kiss image slash p and G aunt the file extension for this one. He has stopped pay injury Break on that on will set a default. So if if it's non of these, then we're just gonna drop out of it. So go default, then that's just gonna be Brick. Oops, you go break. So if it is one of thes saw him, she picked GIF PNG, then applies the right file type. If it's not, then we're going to drop street out. But the file extension will be blank. So we need to perform some validation on this. So if file extension is blank and send in every response, then this will be 400 false on the message will be nor followed file extension found for my type. So in theory, now that it's past all of that validation, we can try and build a new image of to then save it into the database and then obviously move the file itself. This is where we used the image model. So we'll create a new image based on the image model we'll call this image on. There will be new image. I remember going back to the image model. If we go back to that takes an I d title file near the mind type task I d. So at this point we won't have a image. I d only want to receive it to the database for this first parameter will be no, The next one is the title, so we'll get that from the GS on. So Js on image attributes Title has already performed on the validation on at this point. Next one is filed here. So that comes from the Jason, too, Um, file name and then the mind type member. We've used the mind type appear using the image file details. So we'll just out that in so image file, details line. And the last one was a task i d And obviously we passed that in well, in multiple places, really? But what? We're used the task idea because it passed in to the function itself. So we can just reuse that because we performed validation on that task. I d. Okay, so in theory, that should create the new image based on the image model. If any of them throws an error that would obviously give in here. So throw Imus exception. I will try and catch will catch this just like it does with the task. So we don't need a perform any validation on that because it already do not want to create the model so that now that the model is created, we can then store the title the file name in mind type from the model. The reason I do this is we actually me do some manipulation of the values within the model itself. So are always sort of sets and variables and then get them back out to use in the model itself. I just saw that would know that we're getting valid, you know, college values back sore. I'm gonna call this title on it is image Get title. Next one is I'm gonna call this one the new file name just because we've got an original file name. But the new file name comes from the model itself on will be the actual Finally, um, so in the beginning, Like I say, we've got a temporary file name. So I'm just going to call this a new filing because we are going to move and rename this file toe. Whatever we've provided in the file name. I know it sounds confusing, but you'll understand what we get there. So new file Name? Andi Image get file. name hopes that file extension. That's not what I want. I want file. Name on the last one is the main type sore my type. It calls image, Catch my type. So now that I've got that, we can query the database again at this point because we need to make sure that this file name that we've provided does not already exist for this said task because obviously, on a file system, we can only store a unique file so the file can't. I cannot multiple files that contain the same name. So we need to perform some validation and make sure that final name doesn't already exist. So we'll do another database query now. So Queary on this one is also the reedy Be because we're not writing at this point. Prepare on. It's going to be select. So we're gonna use two tables here. We're going to use the tusk on bond the TBL images table. The reason we're using the tasks table is because we need to make sure that for the given task, I d. We need to make sure that we check in to make sure that it belongs to the user that looked in so select tbl images dot i d from tbl images pond tbl tusks. We're tbl images dot task i d equals TPL tasks dot i d on tbl tusks dot i d equals the set for the past in tusk i d on tbl tasks don't user i d equals the I guess the past in user writing user I d on d tbl images don't file name. So this way, which had finally, um, pulls the past in file name, another times complicated, but basically, we are checking to see for Roy exists for the given task I d. That belongs to the user that were passed in for this file name that was passed in. So now we'll find the parameters. So Queary, find run. Andi, that is the 1st 1 will be tusk I d. That's task I t on. It is a video, Haram and a problem user. I d this one yet? That's right, please or I d and user i d Haram. And the last one is the file name. So we're gonna call this new filing a new file them pidio Haram. And this is a strength the next cue. The query so that I'll check to see if we've already got one that exists or needed to a roar. Count to call, roll count. And then it is Queary rule count. We need to make sure that it's zero. So if it's not there also of raw account is not the year old, then send in response back. So this is a conflict. If it is, remember, conflict is for nine error, so it's gonna be false, and then we're going to write a message. A file with that file name already exists for this task. Try a different file names. Okay, so now that all of our validation is now past, we can now get onto saving the image in the database on obviously moving the image of the uploaded image to the relevant location. So what we need to do here is use a database transaction because we don't want to add a raw into the database table for TBL images. If the file itself feels to upload somehow. So obviously we don't want to say Oh, yeah, this this task has an image. But actually, when you try and retrieve the image file itself, it Dent is actually we can't find this image file. So we need to make sure that the file itself is successfully uploaded and we named before we then add the rule into the TBL images database table. So, like we've done with the test before, we can start transaction. So that's what we'll do now. So we're now right into the database. We will use the right TV connection on we will begin corpse begin Trans section. So now that will start the transaction. Potentially, this could feel at any point. So we need to go back on just our catch demons because we need to end the transaction if it is in a transaction. Remember this PDO exceptional image exception could occur before we started the transaction up here. So we just need to add the check in here to say, Well, if it is in the middle of a transaction, then we need to call back. So we'll do that now. Don't put after the era log, Mr Semicolon. If they have just noticed that, make sure you at that on the air lock there. So we will do if hopes If the right DP is in transaction, then we can rule backs or right dp rule back. I'm just gonna come and pierce that, because that's actually the same here as well. So if it's in transaction currently, then we're going to roll it back. But if it's not, which is gonna ignore that causes nothing to roll back. Okay, Now that that's set up, we can now get on to creating the sequel query to insert into the database table. Queary, we are obviously using the right debate here because we're putting stuff into the deal of this. So using prepare on this will be insert into TBL images. It'll be a title file Name my type Tusk I d. And then the values will be passed in. So title file in groups file Name the mind type on Tusk. I d. Okay, so when you now find these Queary, find Rub. 1st 1 is the title and this is Theo, the title available that was retrieved. Just stop here. He's once here. So title. And this is a video his two yard to strength Cleary find Haram. This woman was file name, file name. This was a PDO for, um, string as well. Actually, that's called new file near. I'll get this. Correct. Make sure. Don't mess that up. It's called new file. Name on the next one is Queary fight for Aunt? It is my type aunt, that is. And what I recall, that thing was called my type yet my my type. And that is also PDO Haram string in the final one. IHS, you re Haram Tusk I d pd or Haram? And this one is an in a job. Okay, so that should do that. So now we need executed. So Queary execute. And then we need to make sure that it waas and actually inserted So we'll run a rock out. Uh, Queary, And then we just need a chick that will count. So I guess if it's equal to zero will throw an error sore and send a response. And this one will be a 500 causes small, the system era Because with pasta politician at this point field to Lord image. Obviously we're in a transaction here, so also need to do a rule back. So if we if right db is in transaction, then we will roll back for right Team B, the book, and then send the ever response. Okay, so now that in Thievy, if that's all past with now insert it or now we should be able to get the last insert i d. So last image I d. Andi, right, baby, And we've used their scent. Obviously, when we uploaded the task, it's cell phones in previous videos lost in cert i D. And then what we should be able to do is then retrieve the image itself to make sure that actually got OBL ordered and that it's the right image to then return because we are actually going to respond with a Jason response of the image actually route. So we'll get the task image out of table again. So another query on spell query equals will use the right DB for this as well, because it's all within one function, even though we retrieving the obviously. If you do use replicated sleeves for my sequel, it can take a bit time to push across because we're all in the CME function here. We are actually going to use the right DB to make sure that we get uploaded Task image back prepare and then we'll new sequel Stephen Tear so select Tvl images dot i d tvl images Dutch title. Tbl images dot file Name TVL Images Not my type tvl images dot task i d from tbl Images on tbl tusks way tvl beverages dot i de Gaulle's passed a new majority on TV l tasks, don't I d. Passed in groups Tusk i d tvl Tusk Dr User i d Sting user I Day on TV l Images Dr Tusk I d equals tvl tasks Dutch I D. Yep. So this sequel query We return in all of the image deals or image attributes for the given Image I D. But obviously is part of getting the image I d would just really in that back to the task, making sure that retrieving the given image for the set task, but also then performance some authentication on the task itself to make sure was still have access. It's always best to do. This reduces any issues to do with security. You make sure that you validate each time on each sequel query, so we'll just buying the variables by the parameters or Queary Haram on the 1st 1 is a majority hopes image I D. That is on the last insert images. Not sort last image idea, because we get that from here. That is a ppd or Haram and Egypt Cleary, find for task. I t Tusk Day from nature. Queary, find Haram coops on this one. Is the use a date? This one is the return. What's not? I want returned on. Use a righty on that is a PDO Haram image as well. It will execute that. So X groups for work execute on. We need to make sure that the raw count is valid when you get the real come first. Sorry. So raw account, Queary. Broad count. And then we need to form that Donald Ross and politician on that. So raw, counterfeit, equal dizzy role. Um, we're in a transaction. Still, soldiers make sure about that. So if write dp Pope's TV in transaction If it is when you will cool buck after roll back, we will send a every response. So that will be the 500 error stops. He's some sort of system issue. Bulls field too. Retrieve image attributes after deplored Try uploading image. I can care. So if it has successfully applauded, we will get this image box will save this in an image area like we did with the tasks, if you remember, and we'll just create a blank area to begin with, and then we'll While this should only be worn in this case but will use the while to keep it consistent while rule equals Queary coronary fetch. And we want an associate of a RIA backs for TD or Fitch Hopes. Spelling's terrible today, which associate of a rear, and we'll see a bitch back as an image using the image model. So a new image and then we will have the 1st 1 will be the I. D. So role. That's the idea. Rule title rule filed him. Roll my table. Think my type. Um, next one hopes Mr Brackett off there on the next one. So my type, the task idea. Sorry. Here. So rule. That's Guidi case. A lot created the image, and then we need to put that image in this imagery. A so image area tops. And then it's just equal to image returned image as a really. So now we've got that we should be able to put this in this every of images, which is good. Andi, right? Sore Now what we need to do is to go back into the image model on to implement a new function which will be responsible for moving the temporary file, the physical file on putting it in the right location. Remember that the location is within tusk images and see on the left hand side here, task images one day, a new folder that is named with the task I D. So it will do that now, and we'll come back to this. So for moving, too. I'm just grateful that down just going normal from model and then image we need to create a new function called Save Image File. So I'm going to do is just cool down. I want to put it just above return images area. So I'm gonna call this public function save image file, and it will actually take a argument which will be the temporary name. So for the school backup, you can see when we uploaded the file, I can find it up here. When we uploaded a file, it took a temporary file name. So we will actually pass this in to the function. So we go back to here, we'll take in it. And the file name. So temp file name. Okay, so a bit of background. When you do here, we need to obviously get the file path itself where we're going to be storing it and give it a name. Were then gone. Teoh, create the task i d folder. If it doesn't already exist within task images, if it does exist, then we'll just use it. Make sure it's there basically, And then we'll use a function called move uploaded file, which then takes two arguments, one being the temple file name and one being the new file name to then move the file. The move uploaded file function does return false. If there's an error in that way, I will. Transaction comes in. So if that function returned false, as in, we haven't been able to correctly move and rename the file. Then we will back out that database transaction. We will not insert it into the database, will roll it back, working, then trial and error to the user. So we need to build the file past that we're gonna blow it. Saw him Corner collis lorded file path. Andi, remember if I school up the model. You can see we get our We've got a function called get uploaded. Full the location, and that is actually set here. So this is where this comes into play now, because we're not having to constantly copy and pierce this into different functions. And then obviously, if you file location changes were doing after, then, you know, go through all the records to then update this new location was set in one place, and then it's the same throughout, so we'll actually use that function. So it will be this on hopes. And then it is get upload for the location, see that to function Well, then going to so fix that at the end with the task I D. So then we will return this. Get Tusk I d. And then at the end of that, when you died in forward slash and then at the end of that, we need to get the file name. So this get file name. Remember this points the file name will have a file extension. So a scho 39. BONUS Section 02 - GET - Implement The Get Image Attributes Route: In this video, we will implement the Get Image Attributes route. This will return a Jason response of the image attributes and not the image itself. We'll do that in one of the next videos. As you've seen, the image attributes includes things like the title on file name as well as the file type such as Image Slash DJIA pic. We implemented the image attributes separately to the get image because it's two different types of content, and you may want to return the image attributes to a client application without having to download the physical image file, which could be making bites and size. So let's get started. We'll open about him, and I folded up all of the current sort of functions in court that was written previously in the course. I'm going to create a new function for this, and I'm just gonna put it after the upload image route. So it is going to create some spears and we'll call it function, get image attributes route on, and the function itself will take in some arguments things like the reedy be because we're not writing anything in this one. Also, the task I D and the returned use a righty, so we'll just add them placeholders now. So read a B tusk i d image i d andi return to use a variety. So now that I've got the function sort of body, they we can actually move down and not this function call within our routing logic. So when you look at our comments here, this is the one that we're after the slash tasks slash task i d slash images slash image I d slash attributes because wax again, the image attributes yet. So I'm just going to expand this so you can see the logic that we're dealing with. We're not going to deal with the patch at the moment because that's when we'll update them in the future video. So within the get we need to call this function. So the function that we just created is called get image attributes Route on will pass in that read Did abyss. So read a B task. I d. Image I d returned. Use a righty. So we're getting these obviously, from this route es or task, I d image I d and attributes. So now that we're calling the function, we can actually close up this logic here and moved back 12 function body and start implementing this. So what we need to do is to create the try and catch blocks. Saw catch on. The 1st 1 that we could catch is obviously an image exception. Quality X. The next one will catches a PDO exception because we're dealing with a database. So catch PDO exception The X on the PDO exception. Want to log to an ever long if there's a sequel era and then it ISS So put a message, did a Theis Cleary Hera and then obviously upend the error message on the end on. Then we need to send in every response off. Send response and of your 500 error. Oops, false. And then one of binary message feels to get image attributes. OK, so we'll move on to image exception on, and it's just in every responsible Send response on it will be a 500 era false, but we want to get the exception message. Okay, so now we've got to try and catch will now work through it. So we need to retrieve the image attributes from the database so we'll start the sequel Query. So Queary calls Read A B because we just read and stuff here or not. We're not passing any right. So read a bay and then want to prepare on. The sequel is so select tbl images dot i dy tvl images dot title tbl images daughter file name TPL images dot mind type t deal in, which is Dr Task i. D. And we want to get them from TBL images on TBL tusks. And then it's way tbl images groups dot i dy equal to the past in image i d. On d tbl tasks dot Heidi is equal to the past In Tusk, it's a task i d on Bennett on tbl tusks dot user i d is equal to the past in use a variety , um tvo images dot task i d equals the TBL tusks. Doctor Ponti. So this sequel selects the image attributes from the TBL images table for the given image idea that was passed in. Obviously, that's image Ideas associate with task ideas will make sure that the logged in user is also the owner off that set task. I d care Now we just need to buying the Providence So Cleary find around in the 1st 1 is the task. I'd and image I d Sorry. So the 1st 1 is image i d. And they call that a majority on two PDO Haram Inderjit Riri buying Haram. And this one is the task. I t the task idea. And obviously, we're getting these ideas past in from the function here. So tusk, i d. On this is the PDO around. And, um, finally Queary buying Farrah. And this one is the user i d. And this is the returned user. I d that PDO Haram. They were executed. Cleary, execute. And we need to make sure that we've got some rules returned for this. Told to roll count Roll County, close Queary roll count. And then we need to make sure that the raw counts if it's equal to zero, then we send a 44 back. Send responds Four or four. False. It's not successful on the message that was sent back. Is image not found? Okay, So if the images found, um, we need to stall that in the theory and then send the area back in a successful response. So will first create that a race or image, really, and it's blank area at the minute and then we need to do a while. So while rule equals, um, Queary fetch and then it's associative arrius or PDO fetch associative memory on Do we need to create a new image office? He, using the image model from the returned values from the database, saw new image. 1st 1 is Roll I D hopes to half court around it. The next one is role file hopes Final name, Sorry Title title and then Rule final name and then roll my type and finally, Rule Task I. D case or created the new image for one. And now put that image into the images of really, even though it's just worn, just makes it easy to Jason in corded back images re he cools image. Then it is Get image. Sorry, Return image has a really Okay, so now that I've got that, we can then send the success response back so we'll send response to 200. We are passing. True is successful. We're not passing any investors. That's all that to know Andi because it's just a get request. We can cash this so we're going to see yes to cash on, then passing the data, which is in the image. Three. Some theory that should work. There should be other fire A postman. First of all, we need to obviously get a new session because they were access talking well of expired by now, we'll copy the access talking, and then we'll create a new get request. On the route is http local Horst Port idiot idiots like video on slash tusks and obviously legacy. We've got two tasks, so it's just task I d one and then it slash images. And I'm just going to get the image with image I d warn, because that's what we've created. So then it slash attributes think spell it correctly because we're just getting the image attribute here within the header will make sure what we put our authorisation access talking in there on will just send that. So I got a 500 error will just quickly check the log to see if we made a spelling mistake probably is have, and the logs on will quickly open it on and line 192 It's got a Barack it and expectant square bracket, so go back to Adam 192 This one here on I can see that they have made a mistake. Sort square bracket. Still check the other ones when I'm in here. Yeah, that's fine. So of course, of course minded. Post that again. Okay, we've got is 200 success. Success is true, nor messengers on then the data. So about the image i d the image title, the file name, the file type, I guess the main type and the associated task i t If we put image I d to send that and say , even though the titles are saying, that's just because we'd ever change that when we uploaded the second image, the file name is obviously image to this one, that DJIA pic, and it's still a short it's still associate with task I d. One. If we put in Ottawa, nor image I d it send, we can see we'll get a four or four image not found so I can say that I will logics now working. So in theory, that's this lesson now completed. You could see how easy that was compared to the previous one. It is just a simple sequel query and then return the response back out in Jason. Former, you will see in the next one 40. BONUS Section 02 - GET - Implement The Getting Of The Actual Image File: in this video will be implemented. The returning of the actual image itself to the client. The FBI will return the binary image file itself. So let's open about him. So you can see we've got our folded up court here in the images controller. We're going to create a new function on which is gonna put it after this one. We're going to call it function, get image route. This will take in a few arguments, the first being the re db the next being the tusk I d. Then followed by the image I d. And then the returned user I d. Now that we've got the body there, we can actually, at this call to the function into the relevant route to them of god slash test slash one slash images and then five, for example, Slatina majority. So this is where we want to call the get image itself. So this is where I put it in the get we're not doing delete dressed yet. So they get we will put in here, get image route and will pass in the read A B and then we'll pass in the task i d. Then the image i d And then the returned use a righty, Sort of turned Use a righty. So that's the call day within the get for the slash test slash one slash images slash five . So this gets the actual image itself. So now that we've implemented that or call, that will actually just minimize that downward folded up so I can see where we are. Well, scroll up and then we'll go back into our images route. So try and catch again because we're dealing with a day to be isn't image objects, so try and then catch in. The 1st 1 is a image exception Image exception the X Hans catch PDO exception. Yes. Yeah. Okay, so I'll do the PDO exception First era log on it is to just an ever message here. So database query hair I and then Ruutel the message itself. Normal Centenary response Send response. So 500 false on. Then it is adjusted. A message Ever getting image. Okay, now the image exception. So we'll just send a response on and that will bay a 500 error false and then he x get message. So that's the trying catches. Sort it out. Malago through the logic for the sequel Query. So Queary equals three days a prepare to create some space. One single doing I want to Get the image itself so it will be the image attributes So tbl I just don't I d Tape you books, TV help images Dutch title TVL images dot filing in tbl Bridges Daughter My type on tbl images dot task i d from TVL Images on tbl tusks We're TPL images Dodge I d equals the past in image i d andi tbl tasks dot i dy equals the past in task i d on then tbl tasks doctor user I d equals the past in user i d on then TPL beverages dot task i d is linked to the tvl I m sorry. Tbl tasks dot Piety yes or this returned all the attributes organ rebuild The image from the image model will end should be able to call a function on the image model which will have to remain in this video to return the actual image itself. So now we'll find parameters or Cleary range Haram in the 1st 1 waas the image i d the majority and that is he PDO Haram In danger. Queary change, Haram. Oops. This one Waas The task i D This is PDO Peron, Indigenous Cleary find around perhaps that Brockett Bank Peron. And this one was the use a righty. Cool on there. This one is the return. Use a variety. This is a PDO Books, Haram in the job. I don't know how we need to execute it. And then we need to check the rule counter. Make sure and image exists. If not, we'll send a response back for four or four. Grow. Couch equals Queary rule. If rule count equal zero send response. Andi, it is a four or four false on the messages average not found and then just moved me from space. But obviously, if the images found we need to get out from the database so we'll just create the image. There's no here for the time being because then what can check if it to know if we try and recreate the image? In theory, if there's a problem, create the image in your mix. Exception should sort of capture that for us. Put Felton Breezes. Um, no. So then we'll run the while while roll equals Queary Finch on its PDO, and it's fetch associate of a really and trying create the image. So image from here, new image and that will pass in rule hi day rule title through clown in and then roll my type control task I d. Okay, that should create the image. So then what need to do is check to see if the image is no, shouldn't be. But if it is, if image because, no Oops, Then we can call the send response on it will be 500 because it's more of a Soviet era false on. Then it would be image file. So image not found? Yep. And then I want to pass it all out father dish when they need to return the image itself. So to do that, we have to go back in the image model and then have to implement a new function. So we'll go back into here and we need to create a new function called Return Image file. So I am just gonna put it underneath the getters. So what just here will do so public function on. We'll call it to image file. So this return the buying refile itself. So we need to get a file path. Soul call this file puss talk file path, and then we'll use this. Get the Lord for the location, and then it will be depend on this. Get Tusk. I d. Because what was he navigated and into the folders here? The task images task idea. And then obviously the images. So then court, forward slash and then depend on the this Get filed in extension file name. So that should be the file path to a file. After returning, we need to make sure it exists because obviously way store in all of these details and the data basis has no actually checking the actual file itself at the moment. So check now that now using the file exists function from PHP. It'll pass in this said file path, you for us. If it doesn't exist, we will throw a new image exception you image exception on. We will put in image file not found. But if it does exist, then what we need to do We need to switch the content type that's being sent in the header back to the client. So currently, all of our responses at the minute have bean Jason responses, even success want, you know, failures and things like that. But because we actually turn an actual binary file here, we need to switch content types now, so we'll use the header function, and the content type will be this Get mind type. So this where the mind type comes into its own here. So obviously we do normally application slash Jason. But obviously the mind type depends on the file itself that you're returning. So if we return it a J pic file were returned an image slash j peg as a mind type as the content type and image slash gif as the obviously the content type if it's a gift file. So we need tell the client what type of file way of returning backs on northward. Handle it. We also need a new header as well for content, disposition, disposition. Yet at fight, so in line basically means that it will returned in line. It will be returned either within the bro's all the climb itself. The is different types of dispositions where it can ask you to download the file instead. So depends what you want to do. I'm just going to return it in lane just so we get to return the image in the browser or, you know, postman in this case. But this probably is the one that you're gonna be user. We can then pass in file name. So if we do want to save the file normally, if we don't pass in this parameter, it will just get around and filing in back. But because where we have the file name stored in the database, we can actually dictate what it's called. So file name equals and then it is finally, um, equals. So it's a double cool for by single court, and then we're a pendant, this get final name. And then at the end of that, we need to upend on single court on then it door court, and then a single court again. So file name is wrapped in court, basically. So that's how we do it in the trivia single court. That's it. So once we still national obviously set the header for the client. Now we need to read the file back to the clients or the especially streams. The buying refile back to the client. If the file doesn't exist off this problem reading it or something, it can return fall. So we will handle Handle that. So if read file is passing the file path file path that returned false. Now this one's a little bit different. So we're going to set just the response. Court reviews this before within our response model. So response respond to court and we're just going to return a 404 You're probably thinking , Well, why aren't were send in response back as in a Jason response. Well, the trouble is that we've already sent the head. Is is a binder file saying, You know, you're going to receive an image, So at this point, it wise just to send four or four back to the client. We can't basically send Jason as an image type, So this is the safest way to do this. So then we need to exit the script. So if I can't find the file, if it has trouble actually reading the physical file, get lonely, returned four or four message back, and once that Stone wants it sent the file. So if the file does exist and it sent it back, the read file will actually send the file back as well. So you're probably thinking, Well, is that not just checking to see if it can read it? No, it's also Cendant or stream in the file back to the client. So once that read, we just want to exit here. Okay, so we'll go back to the images control of file because that's function within. Our model is now being built. Everything looks OK. And we'll go back. The image control of file. And all I need to do now is to call its or image on it waas return image file. Okay, so in theory, that should work. I told her open a postman. Well, just log in again because my session will have expired by now. You might not off but underscore. Log back in quickly, and then we want to get it to you. P local forced idiot idiot slash everyone slash tasks slash task warn flash images slash image one because we've got obviously images one and two currently within the headers, we need to add our access talking authorization and then the access talking. So for San Dutch, you can see that we've got the image file returned. We've got a 200 message and obviously the size and everything like that, so you can see the image itself has been returned successfully for going to the returned headers. He can see the content disposition is actually got finally, a minutes image file one. And if we look at the content type, we can see that it a PNG file. So that's how your client knows what to do with the return buying refile. It's basically telling the client that it's an image file of PNG on, and then it can handle it from there. So when you blow a second image, which was, I think it was something to do with water, and I think that was under image. I d to so change that image I d to now when we return, that will get a 200 message and you can see that we've returned the image itself. So finally use a combination of obviously different sort of headed types there to tell, either it's gonna be a jeison response or whether it's actually going to be the binary file itself. So that's this video now complete, and we'll move on to the next one 41. BONUS Section 02 - PATCH - Implement The Update Image Attributes Route: in this video, we will implement the update image attributes route. He will provide the title on or a file name is a J s on request. This will contain the new values want updated. This will also return a Jason response of the image attributes. This is very similar to the update task, functionally so I won't go into much detail on whilst I'm implementing this. As it would just be repeating theory, we will also need to rename the physical filed or if we provide the file name to be updated . So for over? Nope. Adam, when one I've done is folded up all of the court that was previously written just to make it look Tidier. So we're going to implement the new function called update image attributes route. So lot that in underneath here. So function hooked it. Image attributes route on. That will take in some arguments. We will be doing an update to will pass in the right TB passing the task i d image i d. On the returned user, I d. So now that I've got the function body there, we can actually go down to our logic route logic here. Andi call that function. So what we're doing is updating the attributes Saw it is this route here that we're looking for over expand that one and for expand the get and then the patch Because of already implemented, I would get one. So what we need to do here is implement the function call here. So this one is what did image attributes route on will pass in the variables. So read DB ops. Sorry. Right, baby task I d image I d returned. Use a righty Now don't match. We can close this up because of implemented its that logic Now on, we'll get on implementing the function body. So obviously has probably mentioned we will be sending a GS on body with this Andi receiving and Jason response back. So obviously we're doing the opiate before using patch when we did the task. So it's basically very similar That way we'll check to see watch Field has been passed in in the Js on and will dynamically constructive sequel query to update that the first thing when you do is implement to try and catch and then catch. And the first catch we need to do is Theo the PDO exception E X on the next one is catch image exception. Within the PDO exception, we will write out for a never long as usual looking. The sequel Cleary era on the message will be just a generic message. So database Queary Pera, yea X and then send in the response buck. This will be a 500 false for success. On the message will be Field Teoh Ditch Image that tribute Check your dealer for errors just a generic message. Next one is image exception. So we'll send a response back and this will be a 400 because probably gonna be a climb error. False On the message will be will get the message, actually, from the image sore X Get message k saw within the try and catch The first bit of validation need to do is to check to make sure the content type is application, Jason, like we've done previously. So content type is equal to sorry is not equal to application slash jasan Andi, If it's not, we will send a response back. So this will be a 400 error. False, um, content type better not set to jasan. Okay, so If it is set to Jason, then we'll get the contents of the patch body. So we will see if this in raw punch data and will use the file, get contents like with previously doing on that will be the PHP input. So now we're gonna check to make sure that it is valid. Jason Data. So if it's not, then it's GS on data. So Jason D chord it will be the raw patch dinner. So send response. Pope's not that one send response on it will be a 400. False on the error message will be Request Body is not valid, Jason. It's going to create some species, so going to see a way we are Okay, So it was recorded, Jason in theory. So the next thing we need to do is to set them some variables here. So the title of dead at false, because the only to attribute we can update us a title in the file name, so we'll just keep a check to see what has been updated. So fire near updated equals false will set the false to begin with and will create a new So what a variable Here called query fields to sort of append the sequel depending on what field has been updated. So I just said that the blank to begin with. So now we need to check to see if the title has Bean ended within the Jason Body Saw is set on its juice on Dita on its title. If it has, then we need to set title Dated equals True this time on the query fields we need to depend on to that, um, so append tbl images. Dark title equals and obviously will put the placeholder in for the title, like Syria dynamically building this query like we did with the tasks. One. The next we'll need to do is to check to see if the file name so is set. J. Sohn dear File name Has Bean added to the Jason request. So is part of that. We need to check to see if there's a file extension being provided, because remember, we don't provide the file extension within the file name. It's automatically determined. So if it has been provided, obviously we need to send in a row back, so we need to write If from then str p us to check to see if it's in there. So then dress on. Did a file name? Remember? Take two arguments. 1st 1 is the string itself. And the next thing is that the stream that you're looking for guests and then if that is equal to false, then we can carry on. Sorry, Flat is equal, not false. Then we can send an ever respond back. So send response on that would be a 400 false on the ever message would be filed near cannot contain any dots or file extensions. And then Okay, so if it does pass, then we can set file name updated equals to true. And then we can upend the query fields. So query fields and then it's penned on a TPL images them tibial images dot file name equals and then the placeholder. I just realized I forgot to put the common here then a space. Remember to do that for the title as well. So just here, so common. And then spierce, because with dynamically building these up, if we're at the last one, we can strip this off the end. Lego did with the task. But for the time being, if we just add calmer and then space Until that actually will remove it now because we're finished build because we've only got two fields will finish building the sequel now saw If we do that's or, um, Green Fields and never want to our trim Oops, because we want to take it off the end. Um, oops equals R trim. And then it takes in the query fields, and then we want to take off the last comments and spears of the end give. The next thing we need to do is to make sure either file medium or title has been passed in because obviously the you know what he erupted in if you haven't passed them to it. So we just need to make sure that they set to True. So title updated and false for Sorry, aunt. And then it is File Nam Hope did it equals false. Then we can send the never backs will send response. It's a 400 error false, and the message will be, nor image file and fields provided and wanted. In the validation. We can try on select the image out. So the image and task to make sure it exists to make sure that the valid I d like you passed in exist. So we'll do that now. We will be using a transaction here because we also need to physically rename the file as well. So I guess we'll be doing all of this in a transaction of database transaction. So if physically renaming the file feels on we've provided a new file name, then we mustn't update the database to see while the file name is now this because actually , the file has field to rename, so then would do a rule back. So the first thing we need to do is to begin a transaction sore right db, and then it is begin transaction. And because we've been beginning transaction here, will also need to update our catch statements here to roll back the transaction if it's in the middle of one. So we'll do that now to the 1st 1 after that error. Before we send the response back, we want to do a rule back. So if rights TB in transaction, it's over in a transaction. Then we want to write DB rule back. I will copy that because that is the CME for the image exception. So we'll do that before we send the response back. Case or now we can begin the get task image to make sure that it exists before we're trying up there. So we will do that now. The database query. So, Queary on it is the right db. Oops. Much of equals, right? Db, prepare on the sequel is select tbl images dot i dy tbl images TBL images doc title tbl images dot file name tbl images talk mine type TBL images. Doc Tusk I d from tbl images band tbl tasks where tvl images don't I d equals the past in image i d image i d andi tbl images dot task id equals a past in task i d andi tbl images dot task i d equals tbl tasks dot i d on tbl tusks dot user i d equals passed in use a righty. Okay, so this sequel will return the image attributes for the given past in task I d on image. I d and obviously would do the make sure that at that task on image belongs to our You know why we looked in user here. So now we're buying them parameters. The 1st 1 being Queary buying to Haram. The 1st 1 is the image I d image I d. And obviously like the other functions with doing well, passing the image I d into the function so we can now use this so image I d And that's a PDO, Haram. Next one is bind. Parham, this is the task i d task i d PDO Peron in the chair. Next, Wallace Queary, find Parham on it is the user righty that they returned user I d PDO in a chair and then well executed. Okay. And then what we'll do, We'll get a rule counter, make sure it's being returned successfully. So rule count, because Queary drew account, and then we'll check. Because if that role account zero, then we need to roll back the transaction if it's in one. So if right TB in transaction, we will roll up backs. All right, pull back. Okay. So if in transaction Spellman state there. So in transaction, they were rolling back. And then we will send a response back, which will be a 404 false for success on, and message will be no image found to book did. Obviously, if he is a rule, we will retrieve that sort will use a while on it will be rule equals Queary. And then we'll be Fitch. And then we want to get pidio fetch associative Arria on within that we want to create a new image. Cold image on the 1st 1 is rule I D rule title rule file name and then rule. Um, my type. Sorry. And then finally rule on task i d. So now that we've got the image back, we can now run an update on the sequel. So we will write Queary String because we're gonna build this open sort of upend in our fields that we've got hope here. So we're just going to do that now. So, Queary string equals on the bait update TBL images grouped in the image attributes. And then obviously because we're linking that to a task i d. We also need to join this sequel onto the tasks table. So, in a joint tbl tasks on tbl images dot task I d equals tvl tasks dot i d you never want to set and then we want upend our query fields onto that and then we want to add in the wear clothes away supports Piercy where tvl images dot i dy equals passed in image i d on tbl images equals TPL tasks dot high tea Andi tbl images dot tusk i d equals passed in task i d tbl tasks dot user i d equals the past in user I d Okay, so that looks correct. Or police off the a tibial images in a joint that with tibial tusks Table on images dot task i d two tbl tusks dot i d And then we want to set the list of fields where tbl images don't image i d equals the image i d tvl images equals drops miss something off their tvl images dot tusk i d equals tbl tasks. Doctor, I d Yeah. And then tbl images that task ideas that passed in one So that turtle Lincoln the task of the image on the user together in tbl tasks dot user I d equals the past in use writing. Okay, so now obviously, we need to create that sequel query and buying the parameters. So if we dio Cleary and then it is right db, prepare on. We're just gonna pass in our query string here because that's what we've built up here. The query. So now what we need to do is to find the parameters if they have Bean set. So if title up dear, that equals true, then we need to use image set title. So right there in the image model here that we've got because we'll update that and then we'll return it back out and use that value out of the image model toe up here to the sequel. So it will set the title to the GS on data. And then it was title. And then what will do will return the update. A title toe up title from the image. So now we'll get title just in case we're doing any manipulation in the model itself. War was set and then get back out. And then we can Queary find Peron here because we are dead in it. On it is the title hopes. It is the title here. And then that is gonna be the open data title. So Hope title and that is a PDO perama strength. Okay, so we'll set the title would get the title, but of the image model within binding that new title to the parameter for the sequel. So we'll also do that for the file name here. So if file ni am updated equals true, then we want to write. So this one's a little bit different because ructions still need a normal. The original name of the file was called before were updated. So need a stall out temporarily because we're going to perform a file system operation that will obviously hope Day at the name of the file. But we need to know what the file was called. Is cold at this point to then I did it. So if we just create this ours original filing him and we'll just get that out of the image model currently because that's the lateral filing, because we have no data together. So get filed him hopes file Nam, and then we need to set the file name. So now whatever restored that image set file name and then we need to set that as the GS on theater on the file name, because that's what was passed in. So jsantana file name Butch because we're automatically determined the extension. The file itself is not changing. We just changing the attributes so it can actually pass in already known file extension on the end of this. So we can now append doctor on the end of it, and then image and then get file extension que so we'll get the new filing. And that passed in then would just get him sort of a pendant. The file extension on the end of the new file name want with all natural, and then see if the updated file names or file name Aunt Image, Get file now. So now I've got the updated following on from the model we can now Queary buying this two. The sequel query. So this one is for file name on It is the pope file name. And this is a PDO Haram stream. So now that bind them will need to weaken, then go on to bind the rest of them. So, Queary, find Haram on this will be the image I d. Because this is relevant. No matter what field we are dead in here. So image I d on. That is an image Heidi and PDO Haram Queary find for, um and this one is the task i d tusk I d PDO for our energy. Finally, Queary, find Haram. This is the user. I d saying the returned use a riding in that PDO around in the trap. Now that we've found the parameters, we can execute this or execute So sorry, query and then execute. So Queary execute. Just move that down a bit. So what's he doing on when you do a raw counter? Make sure that the rule waas successfully updated sore Queary roll count. I will check to make sure that is the rule. So if it is zero, then we can rule back any transaction if it is in the transaction. Right, baby in trans section, right, TB, roll back key. Then we can send a response on. This will be a 400 Andi false, false. And then the error will bay image attributes not dated. Um, given Father used me bay this same us, the stored values, for example. Okay, so now that rob dealers would just need to write another sequel Cleary to bring that back out of the database. So, Queary, this will be the right day be, even though we're reading out of it. because we're doing an update. So all of this is happening within, like, a split millisecond, so it might not give the sleeves time to replicate it. So every time we're doing an update will always retrieve that. Upped it from the right db So right, DB prepare books. That's wrong. I always do that. So, Queary and then it is right, baby. Prepare that for now. We're just doing a select sort. Select TVL images don I d tbl images don't title tbl images dot file name tvl images dot my type TPL beverages docked Task I d from TBL in which is tape, you know, tusks way tvl in which is dot i d equals passed in image i d andi for posting a former off on tvl tasks Don't I d calls the past in tasks i d tusk i d on tv Oh, tasks dot id equals tbl images, Doc task I d on tbl tusks daughter user I d equals tbl. That's why we use a variety case. All this is doing is retrieving the new attributes over the deal. Abi's be a stall in the past in image i d on the tusk. I D on D, Obviously the user Rieti So now we're just quickly buying these again. So, Queary Haram Strong is the majority PDO Haram Imogen Queary find program Tusk I d PDO her in jail. Queary Parham User i d when they returned user I d That is a PDO around in the trash will now execute it. We'll do the rule count again. Well, count Queary, we'll come if the role couch zero um, will do if right, db and they want to dio in transaction soft in the middle of the transaction. We can, right, baby roll back, Andi send response. And that response will bay a 404 and false. No image phoned Cam. So now that I've done that, if it does exist office here we need to get this image back, put it back into a model and then return it as a Jason response. So we need to stall this in an image every so we can just on in court it again. And then while roll equals Queary um Fitch PDO Fitch, associate of a really and then image goals. New image. Then it's raw. So we're building the object here, so raw is I d rule title rule file name rule my type then rule Tusk I d que And then we need to put it into the images of re so image every image return image as a really Okay, just orchard This image title finally in mind type task I d Yet that's fine. And then what want to do is we need Teoh run a function now that will rename the physical file. Obviously, we need implement that function, and that function will be in the image model. We'll just create the if statement here. So if the file name because, Well, obviously we're keeping track on what field being updated. So if file name hopes, if I am updated, it equals to true, then obviously we need to run not functioning here to rename the file, So I'm just going to write to do because we're going to do that now. So if you go back over our image model, I've already folded up all of the functions. So we're going see exactly where we are on just underneath save image file. I am going to create a new public function, and I'm going to call it Rename image file. This will taking two parameters the old image name or the current image name. What is what I should see? And then a new image name. So we'll call it old file name, um, on new file name. So it takes in two parameters. Onda, we need to store the old file path, obviously the renamed file path, because we're going to use a file system function that PHP provides called rename, and it takes two parameters. It takes original file name and then new file name. So we're just gonna build these up now? So original file Puff Andi, which is soon going to use the get upload folder location against all this Get up, Lord for the location. And then we're gonna penned that with this dot Get Tusk I d. And then we're going to depend on a forward slash, and then we're going to repent on the old file name, and then we're gonna have a new variable that will stole their renamed file path. And this will be exactly the Siham. So I'm just gonna copy that, paste it here and then instead of all filing here, which is gonna put new file name. So you say that we'll get in the folder location, Remember, Four location is the task images for them in their task. I d which is the task I d here, which is one. And then obviously within that at the minute we've got two files. Image one, an average two. So that's what you put in the end. So we'll see. Renaming this file will see its image one top PNG and we're going to call its image 55 dopey injury so we can pass these two variables to Iranian function. So now that do not weaken now First, check to see if the file exists because, if not, obviously will want to throw an error. So what file exists? And it's the original file path. So if it doesn't exist so it doesn't exist, then we wanted through new image exception and that will be cannot find image file to rename on. Then, if that if the file does exist, we're now going to try and rename it, so we'll use the function called Rename. This will return false if it is field to rename it. That's why we need the transaction. Because if this function feels we need to roll back the deal to be accepted. So if and then rename, you can see here that I've put the exclamation mark because that if it's false over returns false and then it takes to promise I could see which is the original file path, and it takes in the renamed file path. So if that fails, or if it's if it returned false who want to throw a new image exception on will want to return feel two days there. File name. Okay, so that's the rename image file function complete. So if we just minimize that down and then go back to our images controller, we can now call this function. So it's in the image image, and then it is be near file. Sorry. Uranium image file, then. Obviously, we're person in two attributes here. So the 1st 1 is the original file name this time because we're passing that in on it is the updated file name. Remember the updated file name wear sort of creating not just up here. So there have filed their We've updated it here, and then we get the finally back out stored in a terrible so it is passing that into that function. Okay, so at this point, we should have, in theory, successfully named the file. But obviously, if that feels it's draws a Nimet exception that is called here and it rolls back the dead obvious and it sent and every response back case or now that's updated. We can't commit. So right, baby. Commit to make sure that we see if the deal to be his changes. And then we need to send a success response backs for send response and it's going to 200 is going to be true. Andi, the message is going to be image attributes updated. We're not going to cash it on. Then we're gonna pass in the images. They're really because we after, well, did it. As you know, we always passed back the newly or daily object, so we'll pass that back. I mean, a spelling mistake there because that court should be around there instead. So images area Okay, so that should be each. So what we should be able to do now is actually test this So for over a postman, I love to create a new session because mine will have exploited. Just gonna copy this. No, I am. First thing I'm going to do is local forced 40 idiot slash everyone slash tasks. Last task I d one on. We're just going to get the image attributes for the tusk. I d. One in the image i d one member to put your talking in there and then get I hope some you respond to stay there. Trippy images. See, now that we have the image attributes there for image I d wants, What we're gonna do now is try and update it. I'm just gonna go to the applications month fold, and then the task images and then the image idea of warn it. You can see in there we've got image one dot PNG, which then matches our image. One dopey entry. So we're gonna update this. We're going to create a new request. Remember, it's a patch request. So here, http and then we're going to patch the attributes so they want tasks. Tusk I d images image I d. And then attributes. We're going to patch this member to put our access talking in and then in the body. Remember, it's Js on that route. Day and so Gs on that will create the GS on body here. So the first thing going to do is just update the title and we're just going to see a new title here. So for run that and I'll just move this up slightly so you can see you can see that the image attributes have been successfully updated. We've got a new title. So a new title here. We didn't update the file name till that steers the CME. So if I change that to new title here 1 to 1, you can see that that's being updated successfully. New title here, 1 to 1. And if we go back to the get request and we just send that again, you can also see that if we just particularly get that image attributes it returned to the updated title. So now if we update the file name and he kind of did these both together the title and the filing, which would test in second profile name and we just call this new file one member nor file extension and then we see if that's will send that you can see that image attributes did. The title is what was said it in the previous request. But now you see the file name is new file one dot PNG to know for Go back to our tasks I d folder in the images So you can now see we've got that file, which is the same file. But now it's called new file one dot PNG. So if I just quickly change this to or the file and then send that he can now see the finally has being updated. But also, the physical file has also been renamed. So for your dates title at the same time. So we just put in title and then we'll call this well, the title. And then we'll also rename the file to New or the file, you know, selling silly things, really. But I just want to prove that we can update both of title on the file name at the same time . So for sand that you can see the titles be not dare to other title on the final day is being updated to new of the file. Go back tro finder and you can see that left files now being renamed to New all the file That's basically how we opted image attributes. The next video we will be looking at deleting the image on the image file itself against the task. 42. BONUS Section 02 - DELETE - Implement The Image Deletion Route: In this video, we will implement the delete image functionality. This will delete the physical file on the server as well as removed the image roar out of the images date appears so for over no bottom you can see in our images controller. Our functions are now just about complete. We've got one more to implement, and that is for the delete image. So if we create that's now function delete image route, that will take parameters. So it will be the right day be because we're deleting out of it. Task I d Image i D. Andre Returned user i d and what we'll do is we'll just go down Travel logic Andi, call the function down there. So in order to delete your own a delete against the image itself, So to slash tasks slash task i d slash images slash a majority. So for expand that scroll down slightly. You can see we've got the delete that hasn't yet been implemented. So I just run that function, which is delete image roots on were passed in the right db the task i d the image I d hand returned. Use a righty. Okay, so that's the logic fully populated now. So now if we go back up to the function body and start implementing this so it'll be a try and catch against or try hopes and then catch, and they'll be PDO Exception x on also image exception. And, if implemented, the PDO exception first. So era log. And that will be, um, did abyss Queary, Kara and then append on the error on Send a response backs or send response on it will be a 500 error. False for success on bond, an error message field, too. Delete image. And then, if we within the catch for the image exception, just send response 500 false on, then passing the message itself. So get message. Okay, now this will be done in a transaction as well. What we're trying to do now is delete the physical file as well as obviously delete the role that there appears. So if it feels that believe the physical file, then we also don't want to delete the roll out of the database that needs to throw an error . So that's why we use in a transaction on this one. It's overdue, right db and then begin transaction and because of big in the transaction will also need to roll back within the catch blocks as well. So because we started the transaction of the top as well, we don't have to check to see if it's in a transaction. It will be in a transaction as soon as it ends this Try catch block. So for do right DB roll back Andi rights dp Roll back So that's the try and catch is sorted there. So first start here again. First thing we need to do is to make sure that the task on image idea that passed in in the U. R L exists. So we'll do a database query. So Queary and then it is right db repair on it is select tbl images that I. D. Tvl images thought title tbl images dr File name tbl images dot mine type TPL images don't task. I d from tbl images Andi tbl tusks way TPL images dot i d equals image. I d andi tbl tasks dot Heidi equals the past in task i d on tbl tasks dot user i d equals the past in user i d on tbl images Dr Task i d equals tbl tasks dot i d So this will return the image attributes linked to the task policy. We use an authentication again here, so make sure that the user i d that's passed back from the talkin is the owner of the task . So what? We will now find the parameters. It's a query. Find the majority the majority. This is a PDO Peron in nature drops queary brained from And this is a task i d pass gaiety , then PDO Perama in the chair. Queary Baines Haram Hand. It is user I d. On dit is the returned user i d and that's PDO Haram indicator as well. So now we're execute execute. They would check the role count. Well, count equals Queary Roll count on. If rule count is equal to zero, then it a four or four error. So we need to roll back cause we're in the transaction. That's right, B roll back and then send response four or four false on the message is image not? I found camp. So if it is there, we need Teoh. Get the image back on. Store it in a variable so we'll create a variable here because we can check to see if it exists after we've retrieved. It should do because the try catch difference should trigger. If there's a problem creating the image from, you know, the image model from the dead appears so it will do this now. So a while Rule equals Queary, Fitch, PTO, and then it is fetch associative memory, and then its image equals. And then it's new image. And then it is Rule Heidi through title roll. I found him Oops through my type Task I D. So after that, we can do the check to see if the image is still no so image. And if it's no, then we need to roll back hopes, come back and then send a response. And that will be a 500 bulls and it will be an error. Off feels to get image. So if you've got the image we can then try and deleted from the database ists or queary, and it's right db to prepare hopes. Prepare and is delete TBL images from TBL images on bond tbl tasks. So we're seeing delete the rollout of TBL. Images will have to be specific here because otherwise you get put delete from TBL images but we have to be specific. Which table? Wait till even from Because we're gonna link two tables together in the sequel Query So tbl tasks way tbl images don't I d equals passed in image i d And then it is hard tbl tusks dot i dy equals task i d the past in tusk i d on tbl images Dr. Task I is equal to tbl images Sorry tvl tasks dot i d So that links the two on tbl tasks dot user i d equals the past in use variety so they still it's the rule from the tibial images table So where the image is associate with the given task I d on the image ideas associate with the past in image I d on that of the user that was logged in, As you know, is the owner off the task on the image talk and then find some parameters to that. So we'll Queary find Parham on the 1st 1 is image i d the image I Dean PDO Iran into Queary find Haram task I d SkyTeam pidio in queary. Change around this is used variety to a new variety. PDO Parham in the chair and then we'll execute it. Queary, execute. And then we will check to make sure the the number of affected roars is not a zero. But if it is zero and so we need your count, which is Queary Rule count, and then we'll get that. And then we can check that. So rule count equals zero Onda. We will right to be roll back groups and then send response on that will be for four false and I'll be image not found. But if it is found and this is where we will call the function within the image model office, you need to develop that now to delete the image file itself. So, Goro, image model on the function we're going to call it is public function and we'll call it delete image file on create body. This one's a fairly simple once, or the first thing you need to do is get a path to the file will call it file Puff Andi will use the this get applauded, full the location on. Then we will so fix that with this. Get task I t. And then we will suffix that Ford slash on, then so fixed that with this pope's this get file now, So they still return the folder. Sorry, the file path for the file out we're going to delete. So there's get folder location and then so fixed with this get task I d remember it's located in task images down here would never get to that. And then we will check to see if it exists. It's a way file exists on we pass in file path, and if it does exist, we then try and delete it. So we used a function called on link here and that deletes a file on the file system. And I can't return false if it fails to delete. So if on link and it takes the file past variable. So if it fails, then we will, through you image exception on we will see feels Teoh delete image file. So that's that owning function should delete the file itself. So you're probably thinking, Well, what happens if the file doesn't exist? Well, nothing, really, because we're not bothered. The file doesn't exist on the file system, so we can actually just ignore it, so we'll carry on delete the rule over the database because the file doesn't actually exist . Now it could be that a system I've been deleted it or something like that. But obviously we need a handle that eventually that if the file doesn't exist, then we don't want to throw in a row back to the user. So that's that function done would unfold that up and then go back to our images controller on. We should be able to call this function now toe image and never want to delete image file once that successful will then want to right back to the D. V and commit the changes. So commit the delish in of the rule. Obviously, if that feels it will be caught within the image exception and it will roll back once we've committed it, where then want to send his success response back or send response on? We wanted to 200. It's true because it was successful. The messages image deleted. So in theory, that should be it. That is the image delish in route created when I should be able to test this so just quickly I'm gonna go to finder than applications and then bump and then within a task images, you can see that we've got to images. That's image I d to I believe so. The one that we're going to delete his image. I d one just assure you how that file gets removed so evolving a poor man. I'm gonna have to create new session because mine will expired. Copy the access. Talking on to create a new request. I'm just gonna get it first of all, just to sure that it does exist. The want slash tasks slash Tusk warn slash images slash image one in the header Put our access token and send that So you see the image does exist. It's the car. One on if we want to delete it will create a new request. Mitrice like delete you should you pay on its slash 31 slash task slash task i d warn slash images slash image i d. One member to put it in our or authorization accessed organ on what should be a little eat so you can see that it was too wonders. Success message will get a message back image delete Mr de off that. But that's just a message we'll discord and quickly change. That's over. Go back into Atom. And then if we look for that message so image not found image delete natural. Be deleted. So I changed that now. But most importantly, what I wanted to show you Wasif go into finder. You can now see that that image is gone. So image I d warn that physical files now being deleted. So if we go back to this, obviously this is the old response and we send a get request again. We get a four or four image not found because I deleted it. Now forget image to you can see that one was the water and we could go in on Tell it that if we want change that delete too send. That's also being deleted. Success was true. Now they're obviously the messages, right? Image deleted. And if we go in the file system, you can see that in that folder. It's blank now. So if you go into the database into tibial images table, you can see that this is now empty because we've actually deleted the roars within this dear to be a stable now. So that's it cleared the rule is itself has gone on the physical files. The physical image file is now being deleted. So now, independently, this files section is complete. Now, you could have This is a totally independent section, two tasks. But what I'm gonna do now in the next video is to integrate it tusk images with what we've already built with the task side of stuff. So if you remember from the devil, we hard when we return the task, we also in the Jets on response, we returned in a re that contained task images. So that's the bit we're going to do next. So we're going to allow the return off tusk images. And also, when we delete his task itself, he will go through and delete all of the associate ID task images against you know, that task in the database on also the physical file system itself. So totally clear out all the images for the task that were deleted 43. BONUS Section 02 - Integrate Images Into Task API: in this video, we will be amending our current tasks. AP I toe allow for integration of the task Images will be changing a few things here. First we looked at the task model Toehold Honoria of possible images. The ray will be empty if there's no images for the set task, so it's easy for the client to save the images for the task or not will then move on to update the get task roots. So this will include return all tasks return single task we turn complete or incomplete tasks and then obviously returned tasks page by page. These will need to be updated to include obviously, the task images themselves will then move on to update patch route. This will include returning the updated task model with the list of images we also need. Oh, dear. The delete task functionality is now that should first delete all images, including the physical files on the server, and then delete the actual task itself. Open up, Adam. I'm currently in the task controller, but I need to be in the task model. So within here, we need to create a new so for creating private the new instant variable called images. This will store the tusk images is in a really well, it did. The constructor obviously taken into account the getters and centers. So what we'll do now is creative center for the images. So for school down and we're coming to meet, set complete public function, set images and will be passing in the images as an Arria. So first of all, we need to check to make sure it is Honoria. So is Paree. I'll check images, and if it's not in a really need US throw New Tusk exception on on the error message for that will be images is not on Arria hopes, however. Obviously, if it isn't a realize you're passing in, man, we need to sell it. Sort. This images equals in the past in images, so that's the set is created. So now if we go back up to a constructor, we can alter this to know except, um, images, a zone argument. What we'll do is we'll call this images on. It will be a blank area. So if we don't pass in the images so this could be an optional parameter for dawn passing images, it'll actually created as a blank Guerry. So from there we will create It's all set images on passing the images, the one that created were now need to create together. So underneath this or public function get images. I want to return this images. So now that we're doing that, if we scroll down at the bottom where we returned the task we now need to create a new bit of data here called tasks couldn't called images and then we need to use this, What a catch. Images. So we're using the ghettos and centers. So now that doing, we should be able to move on to the task controller just gonna double checks or save in the image in images passen in setting it school down, get images, is returning the images on under the center. So set images person in It's in a really not in a really throw a new task exception. But if it is, then we see of it and then return it under the get images for the task. So that's the task model created. So now we need to do I'm actually in the task controller. So what we're gonna do here, we need to import the image model itself. So we're just like we did with the response of the task so require once and then it's model in an image dot PHP. So that includes the image model on and within the get a lot of the gets on this period. So a lot of the return of the task, we actually want to perform the same function. So instead of copying Pearson in the same sort of sequel querian stuff, we're going to create a function for that. So we're going to call the function, retrieve task images. This will take in three parameters now, obviously dependent on which route that were on depends on which database connection we're using. So we're going to create a generic sort of database connection here that we can pass the set connection into so want to have done that well, passing task I D. And then returned User I d. What this functional do is for the given task. I d. It will go to the dealer being on retreat. All images associate with that task, i d. Obviously, if there's any will store them in an area and then we will return the ary back, you know, from the function to be passed into the task model that was just adjusted before total pussy area in is an image. And then when we returned the task, it will return the images if there's any, if he isn't, then we return a blank ary just to tell the client that he is no images to return. So what we'll do now is create the image Queary hopes Queary on. We will use the DB corn. So whichever did this connection will pass in? Prepare Andi, we're not going to wrap this in a try and catch because this throws an error and we actually calling this function within the try and catchers within our task controller. So just to make this easier to see, I'm just gonna fold all of this up like it did previously. Fooled all. And then if we come down to hear of God's the route logic here, so for going to this given task, So task I d. And then if you go to the get you can see the try and catch is here Now, we're currently catching Tusk Exception and Peter your exception. But we will need either further catch block in here to catch a Nimitz exception. But first of all, what we'll do is we'll implement this functions or image query and then will pass in the sequel Sore Select TVL Images don't I? D tbl images dot title tbl images dot file Name tvl images dot my type tvo images dot task i d from tbl images on tbl tasks where t b l tasks dot i d is equal to a passage in task i d on tbl tasks dot user i d is equal to the past in use a righty on tbl tasks dot i d is equal to tbl images Dr Task I d. So what? This sequel will do return all of the image attributes for all of the images for the same task. So then what we should be able to do is buying the parameters. So image Queary buying Haram 1st 1 waas task I D PDO Parham Image Queary find Haram User I d returned user I d PDO Peron Imager on. Then we want to execute toe image. Queary execute for one set runoff. See, that can return zero. That's fine, but when it runs were need to store the results in an image, race or image area that will be blank Correa at the minute. So even if this return zero, this blank career will be returned back for the set task until we need to do aware and then image roll equals image. Queary, French pidio coach associative a rare So the first it's not aware that should be a while. So the first thing we need to do is to create the image for new image from the model that that's being returned from the dead of yes or image raw Day. Mitch. Parole title. Commit Toral File. Name. Mitch Role. My type image roll ups. And then it was Task I. D. So we have created the image here where they need to at this image into the images area. So image Marie and then it is equals. And then Popes that image return image, us. Correa. Remember this. I would do that. Jason in Cord to obviously be converted into Jason object. So whilst that's donor Chieh creating image, that's the image on bond. Once we've done that, we need to return out of this function. We turn the rich three que so get all of the tusks. So with all of the images for the set task, well, then obviously create a blank imagery for each of the image. Return the image as an Arria added to that imagery and then return it. So that should be that function now doing to know for school down. Andi, if we're going to die, were single, gets single task for the get and if it will not the try catch on, open up the while. So, basically, just before you create the task, we need to call this function. So the function is, and we need a store to see the return to re in on variable so we'll just call this imagery on the function. Waas retrieve task images on what we do here is look to see what database connection has been used. So this one's read DB will pass that in So read DB and then the task I D member will get the task i d. From appear posted in the query string. So tusk I D. And then the retuned user i d, which is part of our authentication sort of this bit here. So once we've done that. Well, now need a pass this imagery into the task constructor, remember, we just a task model to accept this new images variable. So we just need a pass that in the end there. So images, three image really on. Remember, this is important to at on your additional catch book for image exception. So much exceptionally x on for the minute. We're just gonna copy and pierced this same court because it's still relevant. Obviously, in the previous set of videos, we've created a function for this, but it didn't want to go through and sort of adjust our tusk controller to incorporate that this new sort of send response function. So you know, that sort of getting away from the polar one of trying to teach in this video we will just copying pierced the response in this were. So now that the get single tusks set up, what should be able to do now is actually tested. So if we open postman, I'll have to create a new session till creating your session here. Copy the session access talking and the first thing we're gonna do is return. So the one slash task and I've got a task idea of one. So authorisation, access talking in there, you can see that were returned The task in that the images or images and now returned with the task. The images is blank, which is correct because we deleted them in the previous video. So if we quickly create some images against this tasks slash images in our head a authorisation access talking, then in the body remembers form data attributes on image file change the file to file on in the attributes create your GS on body sold fish farms title on. I'm just gonna call this image warn Title. On the next long is file name. I will call this image one. So select the file and I'll just pick the sky for the time being. Toe, propose this. You can see the images being uploaded successfully against task warn. And then if we go back to the get single task school down, you can see that now images has been returned sort of in a re off images. Obviously you've got one day at the minute, so we just quickly go and create a second image against that tusk just through the different one mortar tree and send that you can see that's created two images or go back to get single task. We're now should have two images returned. So the equal Scalia's image wall on and then there's image to. So the get single task has now being updated to take into account images. So I'll just go through and do them for the other get methods. So if you go back to Adam on, what I'm gonna do is just close this get request up here because we also need update the patch requests or updating a single task. Remember when we or did we return the updated task back to the client? So I'm just gonna expand patch expand to try and catch here, and that was scrolled down to where we actually get the task back, which is here within the while loop just before you create the new task, we need to call that function so we'll call this imagery because I need a store the return of the function in an images array. So we'll call this function called Retrieve what motor recall retrieve retrieve tusk images on a database that we're using on this one remember Look, dear Always called from the right db so well, passing the right dp on this one. All right. Debate passing the task i d on the returned user i d. And now off he update our new task constructor, and we'll call this was it images. So I am a jury. So that's been up theaters. And obviously remember to also add the additional catch for the image exception. Be much exception the X on We just got a copy and paste. What in the task exception, Because exactly the same chord. So now that the patch is being sort of adjusted to take into account the task images if we've got a poor smile on creating new request on Patch, this said task So what? We need to go on, copy our access to open and ended in on. And this obviously the patch for the tasks or did task is a J s on body on. We're just going up the title just to make it simple. So new title. I just got my new task one title and then if you send that, we obviously get the update a task back. But you can see that now we're also retrieve in the new sort of idea task, but also a list of the task images associate with that task so the client can obviously use that needs to. So if you go back to Adam, that is the scroll back up that is the patron dated. Just minimize that down will come back to delete because that's a little bit more complicated. I will now do the update off the completed and incomplete, always a get request for open the try statement aren't just where the wild Bears will call this function so And it was image Arria and then we want to retrieve Tusk images, said Tusk. Well, look up. We can see that it uses the read DB so we'll pass that in this time three db and then task I day and then it is returned. Use variety. We'll update the task constructor call here So passive image Correa Onda obviously remember to our own your additional image exception catch statement you just copy with task exception. So now if you go back to postmen on if we go to the get request instead of getting a single task will get complete I think it is. You've got no complete a task or the two tasks I've got. They are actually in complete change to incomplete. And you can see we've got to tax return. But this seems to be a problem because our images areas blank. So we're going check Adam on. We'll just check to see what we're doing here. So this is a complete request is get within a wild function. Um, we d be yet. Task I d yet not wrong because of not passing a task. Ideals you were passing in slash complete or incomplete. The's no task. I d. So what we need to do is use the return to task i d from the database. So for change out to rule and then I d that should know work so you can see their lunch would not, actually, personally a query string with the task I d actually get the task i d from the returned roar from the database. So if you go back to pose months and that you can now see that we're getting in complete tasks or task one, there has some images and then task to has no images, so that's correct. So that working. So now if we go back to Adam Andi, if we minimize the complete incomplete record of pages and do exactly the same in here, So within the get and the try for this one we use in the re D B as well. So for just scroll down to the wild loop here are under for added in here. So we'll call this image every equals retrieve task images. First thing is the database connection, which is the read A Be on this one. Got up there onto the task i d the same as the completed one. We're not actually person in the task idea into the query string were passing in sort of appeared to the pier number. So we need to get the task i d from the devious. So this is raw Heidi and then returned User I d them up. Did I would tusk here to add in our images. I ve there was school down and make sure we're Koch is created. Catch image exception the x Andi copy and pierce the task exception because to see him to know if we go back to post mine Andi ph slash warn. They say that were returned and paid one of tasks. And the task does include the images. So that's all OK, okay, so that's that. Don't saw the next one we need to dio is just scrolling up certain close this down. Next we need to do is get all tasks or when we get all tasks, we will return any images with them said tasks. We won't worry about the post because obviously when we create a task, it won't have any images. So the well, I would build a model. It will always return an empty array anywhere, so we don't need to touch that one. So for no get school down on within the while loop If we just do image every equals retrieve tusk images on bond. The first thing out of passing is database connection, which is the re db. Next is the tusk I d put. We're not passing any query string together, set tasks or return that from the database here. So, um roll idea warn Andi. I returned using right and then obviously I don't here in surgery and then out on our touch block image exception UNIX copy and paste the response of no for Ron postmen and just get all tasks. You can see that we get north tasks on and just the same as the last ones. You can see that we're getting the images as well, or care so that all the get requests set up, we're now need a work on the delete. So if we go back to Atom on and minimize that and for open up our delete function here for given task route So task ideas one in this example on over trying catch here, and then we can see where we are. So we're deleting from tasks. Okay, so what we need to do is just talking through what we're actually going to do. So when you send a delete task, we need to create a sequel query that will get a list of all images against that task that may be known that maybe 20 but we need to get a list of all of them. Then what we need to do is to delete the rule out of the database and then delete the actual image file. So we'll be using a transaction here because if delish in of the actual image files feels then, obviously we want to roll back any changes. Well, then, basically follow the same logic here. So after all the images deleted, we will then delete the tusks or the task from the database itself. And then once the task has been deleted, we can then delete the task folder within the task images folder here. Obviously we get a full that created for each task i D. But obviously, if we're doing the task, we need to do the clean up off the folder itself. So what will do at the top of the try block will create a new query. So we'll call this image. Select Queary groups a query. This will be the Reach Davis or read DB Prepare Onda. We want to do the same sequel. Query here pops naturally in court, so select tbl images don't I didn't tbl images. Dodge title tvl images dot file name tvl images dot my type TV help images Dr. Task I d from TPL images on tbl tasks where tvl tusk I d equals the past in task i d groups tusks I d equals posted Tusk i d on tbl tusks dot user id equals the past in user i d on tbl images Dutch task I d equals tvl tasks dot de So what this will do is return all of the images or image raws for the past in task. So now what we need to do is bind these variables for bind drops image select query bind. Haram, The 1st 1 is Tusk I d You're getting the tusk i d in here. Something just passed away in Seoul Tusk I day. And then, um PDO Karan rich Select query buying to Haram. Oops, user How about a returned years of I did PDO Haram int But then we only personal to Tasca d and user I d yet the only person to so image select query execute. And then obviously once we've got the list off images associate with that task we need So for each one of them toe call this image brought and then it is image Select query and then it is Fetch PDO fetch associative Arria. So now within this for each of them rules that's being returned, we need to deleted saw that delete obviously includes deleting the roar but also deleting physical file itself. So we need a beginner transaction. So I want to do this on the right. Davey Onda. We want to begin the transaction. So begin and because of begin the transaction, the we need to adjust our catch blocks to check to see if it's in a transaction. And then they sort of roll the back if if there's an error. So what we'll do is we'll update the catch blocks and now, so Cata PDO exception. Um, what we need to do here is just before do less or if right, DB and then it's in transact hopes not begin sectarian transaction. Then we need to write dp Cool buck. So that's that a day lets off a school back. Hope on DSO now have begun the transaction. So for the the image that's being returned to save this in favorable image, his new image and then it is image rule I Day Ridge role, the rich rule file name, image roll, my type image rule and then tusk I d. So that creates the image from the model. What would they need to do is to get the i d. From that so image I d i d pops. And then that should be image Get I d. Because we're actually gonna pass that into the delete query here now and I will do into the query equals and this obviously, we're deleting sorts. The right db on it is prepared on the need to write the delete TBL images from TVL images on tbl tasks where tbl images don't I d It's equal to the past in image I d remember we're getting the image i d from here Image idea So I d on image i d will call that Andi tbl, which is dot task idea is equal to the past in task i d on a TPL and tasks dot user I d goes to the past in user i d on tbl images dot task I day is equal to tvl tasks don't I d So this should actually delete the said image rule from the database. So once we do that well to bind. So Queary find Haram on the first wall Waas image I, d Hollande that is called Image Day. Peter York around in the chair Queary buying Peron. And it was task I d so this is Yeah. Task I d not one there yet in this PDO Theron inch Hans. The next one is Cleary. Find Haram. Use that I d. And this is the returned user. I d your Haram int on the need to now execute. So Queary, execute Andi Sof that should delete the row of the table. So if that is successful, then we want to call image. Remember the help of function that were made calls delete image file that should handle dealing the physical file. Obviously it will throw an image exception Andrx remember, we need to add a catch for images because we're dealing with images here. We'll do that now saw catch on. This will be image exception. Andi, we you will need to roll back, so we'll just copy this PS did in there. We need to roll back stairs to be 500 the message will be their message from the exception itself will get message. Okay, so that's the catch done school backup. So if that court that's fine, it will roll back otherwise of successful we need to commit might be commit So that should see if the changes to the abyss. Okay, so now that we've deleted every cause, we're in a while. Loop. So that's now that I've deleted every image against the task we can then go through the logic here, so delete. So this will delete the task itself. School down, Andi, This is where we check to see if the task has been found. And if it has, then we see it Tusk deleted. But what we need to do before return this is actually delete the task i. D. Folder itself, which would be one in this case. So we need to get the location to that so called task image folder Onda. We will put in saw the task. Control is obviously were in control here. So I need to navigate up the structure and navigate to task images or need to navigate hope three times toe one from here today, one from here today and then warned from your state docks to mumps because remember, I would task images is in the month fall that then we need to write to task images and then we need to suffix that with the task i d. So that gets that them all should be able to check to make sure that the folder exists before trying to leave. That So is we use a function called Is Directory doesn't exist. Taschen Image Full death. If it does exist, we use a function called RM D i r. This is removed Directory. So remove folder and you pass in this location from the top year. So our task image Paula. So we're past that in that should handle delete in the folder itself, and then we can send it 200 test deleted back. So we should be able to test this Now, on what I'll do out quickly. Open up. They're folder using task images and we've got Tusk I d. One in there. We will delete this task. Remember, it does contain images, so we'll just test this out now was quickly go into the database, ensure you the images within the TBL images. We've got to all assigned against task one. So if we're going to pour smile, Andi will create a new delete because I wanted to leave the task. Andi wanted elite task warn. Well, we'll have to my sessions. Problems expired now, so I'm just going to get a new session, access talking. Go back to the delete on up authorization and then passing me talking. And I should just be able to leave this now. So send tasks being deleted. Nicholas 200 status back. Okay, we'll check the tables or refresh this. It has deleted the task images, but has it deleted? Yeah, it's deleted the folder as well. So that's actually cleaned up the associated images for that said tasks. Or now the task. It doesn't exist. Going to tasks. You can see what you got. One task, Which is task I d to so quickly Go back to Port Mann. Andi, just get tasks I left. Oh, dear. My authorization talking there. You can see that for us. We just have one task there now, which doesn't have any images. So that shows that we've actually cleaned up all the images, associate with the task and then obviously deleted the task itself. So that's now the end off this section for task images off. See, we've dealt with images here, but a lot of the same principles still apply for all of the other different file types out there. You credible Lord. Word documents. Two your task or whatever. You know, whatever that you've created year P I for. So I hope this has being helpful. And if you've got any questions, feel free to ask.

Bài Viết Liên Quan

Chủ Đề