Hướng dẫn freecodecamp php
freeCodeCamp is a donor-supported tax-exempt 501(c)(3) nonprofit organization (United States Federal Tax Identification Number: 82-0779546) Show
Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons - all freely available to the public. We also have thousands of freeCodeCamp study groups around the world. Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff. You can make a tax-deductible donation here. PHP is an incredibly popular programming language. Statistics say it’s used by 80% of all websites. It’s the language that powers WordPress, the widely used content management system for websites. And it also powers a lot of different frameworks that make Web Development easier, like Laravel. Speaking of Laravel, it may be one of the most compelling reasons to learn PHP these days. PHP is quite a polarizing language. Some people love it, and some people hate it. If we move a step above the emotions and look at the language as a tool, PHP has a lot to offer. Sure it’s not perfect. But let me tell you – no language is. In this handbook, I’m going to help you learn PHP. This book is a perfect introduction if you’re new to the language. It’s also perfect if you’ve done “some PHP” in the past and you want to get back to it. I’ll explain modern PHP, version 8+. PHP has evolved a lot in the last few years. So if the last time you tried it was PHP 5 or even PHP 4, you’ll be surprised at all the good things that PHP now offers. Let’s go! Here's what we'll cover in this handbook:
Note that you can get a PDF, ePub, or Mobi version of this handbook for easier reference, or for reading on your Kindle or tablet. Introduction to PHPPHP is a programming language that many devs use to create Web Applications, among other things. As a language, it had a humble beginning. It was first created in 1994 by Rasmus Lerdorf to build his personal website. He didn’t know at the time it would eventually become one of the most popular programming languages in the world. It became popular later on, in 1997/8, and exploded in the 2000s when PHP 4 landed. You can use PHP to add a little interactivity to an HTML page. Or you can use it as a Web Application engine that creates HTML pages dynamically and sends them to the browser. It can scale to millions of page views. Did you know Facebook is powered by PHP? Ever heard of Wikipedia? Slack? Etsy? What Kind of Language is PHP?Let’s get into some technical jargon. Programming languages are divided into groups depending on their characteristics. For example interpreted/compiled, strongly/loosely typed, dynamically/statically typed. PHP is often called a “scripting language” and it’s an interpreted language. If you’ve used compiled languages like C or Go or Swift, the main difference is that you don’t need to compile a PHP program before you run it. Those languages are compiled and the compiler generates an executable program that you then run. It’s a 2-steps process. The PHP interpreter is responsible for interpreting the instructions written in a PHP program when it’s executed. It’s just one step. You tell the interpreter to run the program. It's a completely different workflow. PHP is a dynamically typed language. The types of variables are checked at runtime, rather than before the code is executed as happens for statically typed languages. (These also happen to be compiled – the two characteristics often go hand in hand.) PHP is also loosely (weakly) typed. Compared to strongly typed languages like Swift, Go, C or Java, you don’t need to declare the types of your variables. Being interpreted and loosely/dynamically typed will make bugs harder to find before they happen at runtime. In compiled languages, you can often catch errors at compile time, something that does not happen in interpreted languages. But on the other hand, an interpreted language has more flexibility. Fun fact: PHP is written internally in C, a compiled and statically typed language. In its nature, PHP is similar to JavaScript, another dynamically typed, loosely typed, and interpreted language. PHP supports object-oriented programming, and also functional programming. You can use it as you prefer. How to Setup PHPThere are many ways to install PHP on your local machine. The most convenient way I’ve found to install PHP locally is to use MAMP. MAMP is a tool that’s freely available for all the Operating Systems – Mac, Windows and Linux. It is a package that gives you all the tools you need to get up and running. PHP is run by a HTTP Server, which is responsible for responding to HTTP requests, the ones made by the browser. So you access a URL with your browser, Chrome or Firefox or Safari, and the HTTP server responds with some HTML content. The server is typically Apache or NGINX. Then to do anything non-trivial you’ll need a database, like MySQL. MAMP is a package that provides all of that, and more, and gives you a nice interface to start/stop everything at once. Of course, you can set up each piece on its own if you like, and many tutorials explain how to do that. But I like simple and practical tools, and MAMP is one of those. You can follow this handbook with any kind of PHP installation method, not just MAMP. That said, if you don’t have PHP installed yet and you want to use MAMP, go to https://www.mamp.info and install it. The process will depend on your operating system, but once you’re done with the installation, you will have a “MAMP” application installed. Start that, and you will see a window similar to this: Make sure the PHP version selected is the latest available. At the time of writing MAMP lets you pick 8.0.8. NOTE: I noticed MAMP has a version that’s a bit behind, not the latest. You can install a more recent version of PHP by enabling the MAMP PRO Demo, then install the latest release from the MAMP PRO settings (in my case it was 8.1.0). Then close it and reopen MAMP (non-pro version). MAMP PRO has more features so you might want to use it, but it’s not necessary to follow this handbook. Press the Start button at the top right. This will start the Apache HTTP server, with PHP enabled, and the MySQL database. Go to the URL http://localhost:8888 and you will see a page similar to this: We’re ready to write some PHP! Open the folder listed as “Document root”. If you're using MAMP on a Mac it’s by default On Windows it’s Yours might be different depending on your configuration. Using MAMP you can find it in the user interface of the application. In there, you will find a file named That is responsible for printing the page shown above. How to Code Your First PHP ProgramWhen learning a new programming language we have this tradition of creating a “Hello, World!” application. Something that prints those strings. Make sure MAMP is running, and open the Open the I recommend using VS Code, as it’s a very simple and powerful code editor. You can check out https://flaviocopes.com/vscode/ for an introduction. This is the code that generates the “Welcome to MAMP” page you saw in the browser. Delete everything and replace it with:
Save, refresh the page on http://localhost:8888, you should see this: Great! That was your first PHP program. Let’s explain what is happening here. We have the Apache HTTP server listening on port When
we access http://localhost:8888 with the browser, we’re making an HTTP request, asking for the content of the route Apache, by default, is configured to serve that route serving the This file exists, and PHP code is executed server-side before Apache sends the page back to the browser. In the PHP file, we have a We have an ending A semicolon is required at the end of every statement. We have this opening/closing structure because we can embed PHP inside HTML. PHP is a scripting language, and its goal is to be able to “decorate” an HTML page with dynamic data. Note that with modern PHP, we generally avoid mixing PHP into the HTML. Instead, we use PHP as a “framework to generate the HTML” – for example using tools like Laravel. But we'll discuss plain PHP in this book, so it makes sense to start from the basics. For example, something like this will give you the same result in the browser:
To the final user, who looks at the browser and has no idea of the code behind the scenes, there’s no difference at all. The page is technically an HTML page, even though it does not contain HTML tags but just a PHP Language BasicsAfter the first “Hello World”, it’s time to dive into the language features with more details. How Variables Work in PHPVariables in PHP start with the dollar sign You can assign a variable any type of value, like strings (defined using single or double quotes):
Or numbers:
or any other type that PHP allows, as we’ll later see. Once a variable is assigned a value, for example a string, we can reassign it a different type of value, like a number:
PHP won’t complain that now the type is different. Variable
names are case-sensitive. It’s not a hard rule, but generally variable names are written in camelCase format, like this: A very important part of any programming language is how you write comments. You write single-line comments in PHP in this way:
Multi-line comments are defined in this way:
What are Types in PHP?I mentioned strings and numbers. PHP has the following types:
and a few other more advanced ones. How to Print the Value of a Variable in PHPWe can use the
The If we used this code:
we’d have
How Operators Work in PHPOnce you have a few variables you can make operations with them:
The We have quite a few operators – so let’s do a quick roundup of the main ones. To start with, here are the arithmetic operators: We have the assignment operator
Next up we have comparison operators, like
What’s the difference? You’ll find it with experience, but for example:
We also have
and
Logical operators work with boolean values:
We also have the not operator:
I used the boolean values
All of the operators listed above are binary, meaning they involve 2 operands. PHP also has 2 unary operators:
How to Work with Strings in PHPI introduced the use of strings before when we talked about variables and we defined a string using this notation:
The big difference between using single and double quotes is that with double quotes we can expand variables in this way:
and with double quotes we can use escape characters (think new lines
PHP offers you a very comprehensive functions in its standard library (the library of functionalities that the language offers by default). First, we can concatenate two strings using the
We can check the length of a string using the
This is the first time we've used a function. A function is composed of an identifier ( The function does something and when it’s done it can return a value. In this case, it returns the number We’ll see how to define our own functions later. We can get a portion of a string using
We can replace a portion of a string using
Of course we can assign the result to a new variable:
There are a lot more built-in functions you can use to work with strings. Here is a brief non-comprehensive list just to show you the possibilities:
You can find a full list here. How to Use Built-in Functions for Numbers in PHPI previously listed the few functions we commonly use for strings. Let’s make a list of the functions we use with numbers:
There are a ton of different functions for all sorts of math operations like sine, cosine, tangents, logarithms, and so on. You can find a full list here. How Arrays Work in PHPArrays are lists of values grouped under a common name. You can define an empty array in two different ways:
An array can be initialized with values:
Arrays can hold values of any type:
Even other arrays:
You can access the element in an array using this notation:
Once an array is created, you can append values to it in this way:
You can use
Count
how many items are in an array using the built-in
Check if an array contains an item using the
If in addition to confirming existence, you need the index, use
Useful Functions for Arrays in PHPAs with strings and numbers, PHP provides lots of very useful functions for arrays. We’ve seen
How to Use Associative Arrays in PHPSo far we’ve used arrays with an incremental, numeric index: 0, 1, 2… You can also use arrays with named indexes (keys), and we call them associative arrays:
We have some functions that are especially useful for associative arrays:
You can see all array-related functions here. How Conditionals Work in PHPI previously introduced comparison operators: Those operators are going to be super useful for one thing: conditionals. Conditionals are the first control structure we see. We can decide to do something, or something else, based on a comparison. For example:
The code inside the parentheses only executes if the condition evaluates to Use
NOTE: I used You can have multiple
In addition to We use this when we have a variable that could have a few different values, and we don’t have to have a long if / elseif block:
I know the example does not have any logic, but I think it can help you understand how The
Instead of just this:
as you’d expect. How Loops Work in PHPLoops are another super useful control structure. We have a few different kinds of loops in PHP: Let’s see them all! How to Use a while loop in PHPA
This would be an infinite loop, which is why we use variables and comparisons:
How to Use a do while loop in PHP
In the In the Do a simple test by setting You'll want to choose one kind of loop, or the other, depending on your use case. How to Use a foreach Loop in PHPYou can use the
You can also get the value of the index (or key in an associative array) in this way:
How to Use a for Loop in PHPThe
You can use the for loop to iterate over an array in this way:
How to Use the break and continue Statements in PHPIn many cases you want the ability to stop a loop on demand. For example you want to stop a
This makes the loop completely stop at that point, and the program execution continues at the next instruction after the loop. If you just want to skip the current loop iteration and keep looking, use
How Functions Work in PHPFunctions are one of the most important concepts in programming. You can use functions to group together multiple instructions or multiple lines of code, and give them a name. For example you can make a function that sends an email. Let’s call it
And you can call it anywhere else by using this syntax:
You can also pass arguments to a function. For example when you send an email, you want to send it to someone – so you add the email as the first argument:
Inside the function definition we get this parameter in this way (we call them parameters inside the function definition, and arguments when we call the function):
You can send multiple arguments by separating them with commas:
And we can get those parameters in the order they were defined:
We can optionally set the type of parameters:
Parameters can have a default value, so if they are omitted we can still have a value for them:
A function can return a value. Only one value
can be returned from a function, not more than one. You do that using the The returned value is super useful as it tells you the result of the work done in the function, and lets you use its result after calling it:
We can optionally set the return type of a function using this syntax:
When you define a variable inside a function, that variable is local to the function, which means it’s not visible from outside. When the function ends, it just stops existing:
Variables defined outside of the function are not accessible inside the function. This enforces a good programming practice as we can be sure the function does not modify external variables and cause “side effects”. Instead you return a value from the function, and the outside code that calls the function will take responsibility for updating the outside variable. Like this:
You can pass the value of a variable by passing it as an argument to the function:
But you can’t modify that value from within the function. It’s passed by value, which means the function receives a copy of it, not the reference to the original variable. That is still possible using this syntax (notice I used
The functions we've defined so far are named functions. They have a name. We also have anonymous functions, which can be useful in a lot of cases. They don’t have a name, per se, but they are assigned to a variable. To call them, you invoke the variable with parentheses at the end:
Note that you need a semicolon after the function definition, but then they work like named functions for return values and parameters. Interestingly, they offer a way to access a variable defined
outside the function through
Another kind of function is an arrow function. An arrow function is an anonymous function that’s just one expression (one line), and implicitly returns the value of that expression. You define it in this way:
Here’s an example:
You can pass parameters to an arrow function:
Note that as the next example shows, arrow functions have automatic access to the variables of the
enclosing scope, without the need of
Arrow functions are super useful when you need to pass a callback function. We’ll see how to use them to perform some array operations later. So we have in total 3 kinds of functions: named functions, anonymous functions, and arrow functions. Each of them has its place, and you’ll learn how to use them properly over time, with practice. How to Loop Through Arrays with map(), filter(), and reduce() in PHPAnother important set of looping structures, often used in functional programming, is the set of Those 3 built-in PHP functions take an array, and a callback function that in each iteration takes each item in the array.
For example we can use it to multiply all items in an array:
Notice the last parameter – it’s the initial value. If you omit that, the default value is Note that in Object Oriented Programming in PHPLet’s now jump head first into a big topic: object-oriented programming with PHP. Object-oriented programming lets you create useful abstractions and make your code simpler to understand and manage. How to Use Classes and Objects in PHPTo start with, you have classes and objects. A class is a blueprint, or type, of object. For example you have the class
Note that the class must be defined in uppercase. Then you can create objects from this class – specific, individual dogs. An object is assigned to a variable, and it’s instantiated using the
You can create multiple objects from the same class, by assigning each object to a different variable:
How to Use Properties in PHPThose objects will all share the same characteristics defined by the class. But once they are instantiated, they will have a life of their own. For example, a Dog has a name, an age, and a fur color. So we can define those as properties in the class:
They work like variables,
but they are attached to the object, once it's instantiated from the class. The You can assign values to those properties in this way:
Notice that the property is defined as That is called an access modifier. You can use two other kinds of access modifiers: We’ll see more about protected when we’ll talk about inheritance. How to Use Methods in PHPDid I say method? What is a method? A method is a function defined inside the class, and it’s defined in this way:
Methods are very useful to attach a behavior to an object. In this case we can make a dog bark. Notice that I use the You invoke a method on the object instance like this:
A method, just like a function, can define parameters and a return value, too. Inside a method we can access the object’s properties using the special built-in
Notice I used How to Use the Constructor Method in PHPA special kind of method named
You use this method to initialize the properties of an object when you create it, as it’s automatically invoked when calling
This is such a common thing that PHP (starting in PHP 8) includes something called constructor promotion where it automatically does this thing:
By using the access modifier, the assignment from the parameter of the constructor to the local variable happens automatically:
Properties can be typed. You can require the name to be a string using
Now all works fine in this example, but try changing that to PHP will raise an error if you initialize
Interesting, right? We can enforce properties to have a specific type between What is Inheritance in PHP?The fun in object oriented programming starts when we allow classes to inherit properties and methods from other classes. Suppose you have an
Every animal has an age, and every animal can eat. So we add an
A dog is an animal and has an age and can eat too, so the
We can now instantiate a new object of class
In this case we call Dog the child class and Animal the parent class. Inside the child class we can use It’s worth noting that while we can access the parent’s properties and methods from the child, we can’t do the reverse. The parent class knows nothing about the child class. protected Properties and Methods in PHPNow that we've introduced inheritance, we can discuss
How to Override Methods in PHPWhat happens
if we have an
Now any instance of Static Properties and Methods in PHPWe’ve seen how to define properties and methods that belong to the instance of a class, an object. Sometimes it’s useful to assign those to the class itself. When this happens we call them static, and to reference or call them we don’t need to create an object from the class. Let’s start with static properties. We define them with the
We reference them from inside the class using the keyword
and from outside the class using:
This is what happens for static methods:
From the outside of the class we can call them in this way:
From inside the class, we can reference them using the
How to Compare Objects in PHPWhen we talked about operators I mentioned we have the Mainly the difference is that When we use those operators to compare objects,
For example:
How to Iterate over Object Properties in PHPYou can loop over all the public properties in an object using a
How to Clone Objects in PHPWhen you have an object, you can clone it using the
This performs a shallow clone, which means that references to other variables will be copied as references – there will not a “recursive cloning” of them. To do a deep clone you will need to do some more work. What are Magic Methods in PHP?Magic methods are special methods that we define in classes to perform some behavior when something special happens. For example when a property is set, or accessed, or when the object is cloned. We’ve seen That’s a magic method. There are others. For example we can set a “cloned” boolean property to true when the object is cloned:
Other magic methods include You can see the full list here How to Include Other PHP FilesWe’re now done talking about the object oriented features of PHP. Let’s now explore some other interesting topics! Inside a PHP file you can include other PHP files. We have the following methods, all used for this use case, but they're all slightly different:
You can decide to use one or the other depending on your use case. If you want your program to exit if it can’t import the file, use
This is useful if, for example, you have multiple files loading some other file, and you typically want to avoid loading that more than once. My rule of thumb is to never use Use Here’s an example:
The above syntax includes the You can use relative paths:
to include a file in the parent folder or to go in a subfolder:
You can use absolute paths:
In modern PHP codebases that use a framework, files are generally loaded automatically so you’ll have less need to use the above functions. Useful Constants, Functions and Variables for Filesystem in PHPSpeaking of paths, PHP offers you several utilities to help you work with paths. You can get the full path of the current file using:
You can get the full path of the folder where the current file is using:
How to Handle Errors in PHPEvery programmer makes errors. We’re humans, after all. We might forget a semicolon. Or use the wrong variable name. Or pass the wrong argument to a function. In PHP we have:
The first two are minor errors, and they do not stop the program execution. PHP will print a message, and that’s it. Errors terminate the execution of the program, and will print a message telling you why. There are many different kinds of errors, like parse errors, runtime fatal errors, startup fatal errors, and more. They’re all errors. I said “PHP will print a message”, but.. where? This depends on your configuration. In development mode it’s common to log PHP errors directly into the Web page, but also in an error log. You want to see those errors as early as possible, so you can fix them. In production, on the other hand, you don’t want to show them in the Web page, but you still want to know about them. So what do you do? You log them to the error log. This is all decided in the PHP configuration. We haven’t talked about this yet, but there’s a file in your server configuration that decides a lot of things about how PHP runs. It’s called The exact location of this file depends on your setup. To find out where is yours, the easiest way is to add this to a PHP file and run it in your browser:
You will then see the location under “Loaded Configuration File”: In my case it’s Note that the information generated by Using MAMP you can open the MAMP application folder and open Open that file in an editor. It contains a really long list of settings, with a great inline documentation for each one. We’re particularly interested in In production you want its value to be The errors will not show up anymore in the website, but you will see them in the This file will be in a different folder depending on your setup. You set this location in your The error log will contain all the error messages your application generates: You can add information to the error log by using the
It’s common to use a logger service for errors, like Monolog. How to Handle Exceptions in PHPSometimes errors are unavoidable. Like if something completely unpredictable happens. But many times, we can think ahead, and write code that can intercept an error, and do something sensible when this happens. Like showing a useful error message to the user, or trying a workaround. We do so using exceptions. Exceptions are used to make us, developers, aware of a problem. We wrap some code that can potentially raise an exception into a
Notice that we have an
Let’s look at an example. Let's say that by mistake I divide a number by zero:
This will trigger a fatal error and the program is halted on that line: Wrapping the operation in a try block and printing the error message in the catch block, the program ends successfully, telling me the problem:
Of course this is a simple example but you can see the benefit: I can intercept the issue. Each exception has a different class. For example we can catch this as I can have a catch-all for any throwable error at the end, like this:
And I can also append a
You can use the built-in exceptions provided by PHP but you can also create your own exceptions. How to Work with Dates in PHPWorking with dates and times is very common in programming. Let’s see what PHP provides. We can get the current timestamp (number of seconds since Jan 1 1970 00:00:00 GMT) using
When you have a timestamp you can format that as a date using
See the full list of characters you can use to format the date here. We can convert any date into a timestamp using
...it’s pretty flexible. For dates, it’s common to use libraries that offer a lot more functionality than what the language can. A good option is Carbon. How to Use Constants and Enums in PHPWe can define constants in PHP using the
And then we can use
We use uppercase identifiers as a convention for constants. Interestingly, inside classes we can define constant properties using the
By default they are
Enums allow you to group constants under a common “root”. For example you want to have a So you have:
Now we can reference those constants in this way:
Enums are objects, they can have methods and lots more features than we can get into here in this short introduction. How to Use PHP as a Web App Development PlatformPHP is a server-side language and it is typically used in two ways. One is within an HTML page, so PHP is used to “add” stuff to the HTML which is manually defined in the Another way considers PHP more like the engine that is responsible for generating an “application”. You don't write the HTML in a This is what happens when you use a modern framework like Laravel. I would consider the first way a bit “out of fashion” these days, and if you’re just starting out you should know about those two different styles of using PHP. But also consider using a framework like “easy mode” because frameworks give you tools to handle routing, tools to access data from a database, and they make it easier to build a more secure application. And they make it all faster to develop. That said, we’re not going to talk about using frameworks in this handbook. But I will talk about the basic, fundamental building blocks of PHP. They are essentials that any PHP developer must know. Just know that “in the real world” you might use your favorite framework’s way of doing things rather than the lower level features offered by PHP. This does not apply just to PHP of course – it’s an “issue” that happens with any programming language. How to Handle HTTP Requests in PHPLet’s start with handling HTTP requests. PHP offers file-based routing by default. You create an
We saw that when we made the Hello World example in the beginning. Similarly, you can create a How to Use $_GET, $_POST and $_REQUEST in PHPFiles respond to all HTTP requests, including GET, POST and other verbs. For any request you can access all the query string
data using the This is of course most useful in GET requests, but also other requests can send data as a query string. For POST, PUT and DELETE requests you’re more likely to need the data posted as URL-encoded data or using the FormData object, which PHP makes available to you using There is also How to Use the $_SERVER Object in PHPWe also have the superglobal variable You saw how to use In your
Then generate the page at localhost:8888 and search Important ones you might use are:
How to Use Forms in PHPForms are the way the Web platform allows users to interact with a page and send data to the server. Here is a simple form in HTML:
You can put this in your A PHP file assumes you write HTML in it with some “PHP sprinkles” using So
we have this Pressing the Submit button will make a GET request to the same URL sending the data via query string. Notice that the URL changed to localhost:8888/?name=test. We can add some code to check if that parameter is set using the
See? We can get the information from the
GET request query string through What you usually do with forms, though is you perform a POST request:
See, now we got the same information but the URL didn’t change. The form information was not appended to the URL. This is because we’re using a POST request, which sends the data to the server in a different way, through URL-encoded data. As mentioned above, PHP will still serve the We’re mixing a bunch of code and we could separate the form request handler from the code that generates the form. So we can have this in
and we can create a new
PHP will display this content now after we submit the form, because we set the This example is very simple, but the PHP lets us set the HTTP headers of a response through the HTTP Headers are a way to send information back to the browser. We can say the page generates a 500 Internal Server Error:
Now you should see the status if you access the page with the Browser Developer Tools open: We can set the
We can force a 301 redirect:
We can use headers to say to the browser “cache this page”, “don’t cache this page”, and a lot more. How to Use Cookies in PHPCookies are a browser feature. When we send a response to the browser, we can set a cookie which will be stored by the browser, client-side. Then, every request the browser makes will include the cookie back to us. We can do many things with cookies. They are mostly used to create a personalized experience without you having to login to a service. It’s important to note that cookies are domain-specific, so we can only read cookies we set on the current domain of our application, not other application’s cookies. But JavaScript can read cookies (unless they are HttpOnly cookies but we’re starting to go into a rabbit hole) so cookies should not store any sensitive information. We can use PHP to read the value of a cookie referencing the
The
We can add a third parameter to say when the cookie will expire. If omitted, the cookie expires at the end of the session/when the browser is closed. Use this code to make the cookie expire in 7 days:
We can only store a limited amount of data in a cookie, and users can clear the cookies client-side when they clear the browser data. Also, they are specific to the browser / device, so we can set a cookie in the user’s browser, but if they change browser or device, the cookie will not be available. Let’s do a simple example with the form we used before. We’re going to store the name entered as a cookie:
I added some conditionals to handle the case where the cookie was already set, and to display the name right after the form is submitted, when the cookie is not set yet (it will only be set for the next HTTP request). If you open the Browser Developer Tools you should see the cookie in the Storage tab. From there you can inspect its value, and delete it if you want. How to Use Cookie-based Sessions in PHPOne very interesting use case for cookies is cookie-based sessions. PHP offers us a very easy way to create a cookie-based session using Try adding this:
in a PHP file, and load it in the browser. You will see a new cookie named by default That’s the session ID. This will be sent for every new request and PHP will use that to identify the session. Similarly to how we used cookies, we can now use Only the session ID is. The data is stored server-side by PHP.
This works for simple use cases, but of course for intensive data you will need a database. To clear the session data you can call To clear the session cookie use:
How to Work with Files and Folders in PHPPHP is a server-side language, and one of the handy things it provides is access to the filesystem. You can check if a file exists using
Get the size of a file using
You can open a file using
We can terminate the file access by calling Read the content of a file into a variable like this:
You can also read a file line by line using
To write to a file you must first open it in write mode, then use
We can delete a file using
Those are the basics, but of course there are more functions to work with files. PHP and DatabasesPHP offers various built-in libraries to work with databases, for example:
I won't cover this in the handbook because I think this is a big topic and one that would also require you to learn SQL. I am also tempted to say that if you need a database you should use a framework or ORM that would save you security issues with SQL injection. Laravel’s Eloquent is a great example. How to Work with JSON in PHPJSON is a portable data format we use to represent data and send data from client to server. Here’s an example of a JSON representation of an object that contains a string and a number:
PHP offers us two utility functions to work with JSON:
Example:
How to Send Emails with PHPOne of the things that I like about PHP is the conveniences, like sending an email. Send an email using
To send emails at scale we can’t rely on this solution, as these emails tend to reach the spam folder more often than not. But for quick testing this is just helpful. Libraries like https://github.com/PHPMailer/PHPMailer will be super helpful for more solid needs, using an SMTP server. How to Use Composer and PackagistComposer is the package manager of PHP. It allows you to easily install packages into your projects. Install it on your machine (Linux/Mac or
Windows) and once you’re done you should have a Now inside your project you can run
It will do some work: Once it’s done, you will find
some new things in the folder
Now in the
and then we can use the library!
See? We didn’t have to manually download a package from the internet and install it somewhere...it was all fast, quick, and well organized. The How to Deploy a PHP ApplicationWhen you’ve got an application ready, it’s time to deploy it and make it accessible from anyone on the Web. PHP is the programming language with the best deployment story across the Web. Trust me, every single other programming language and ecosystem wishes they were as easy as PHP. The great thing about PHP, the thing it got right and allowed it to have the incredible success it has had, is the instant deploy. You put a PHP file on a folder served by a Web server, and voilà – it just works. No need to restart the server, run an executable, nothing. This is still something that a lot of people do. You get a shared hosting for $3/month, upload your files via FTP, and you're done. These days, though, I think Git deploy is something that should be baked into every project, and shared hosting should be a thing of the past. One solution is always having your own private VPS (Virtual Private Server), which you can get from services like DigitalOcean or Linode. But managing your own VPS is no joke. It requires serious knowledge and time investment, and constant maintenance. You can also use the so-called PaaS (Platform as a Service), which are platforms that focus on taking care of all the boring stuff (managing servers) and you just upload your app and it runs. Solutions like DigitalOcean App Platform (which is different from a DigitalOcean VPS), Heroku, and many others are great for your first tests. These services allow you to connect your GitHub account and deploy any time you push a new change to your Git repository. You can learn how to setup Git and GitHub from zero here. This is a much better workflow compared to FTP uploads. Let’s do a bare bones example. I created a simple PHP application with just an
I add the parent folder to my GitHub Desktop app, I initialize a Git repo, and I push it to GitHub: Now go on digitalocean.com. If you don’t have an account yet, use my referral code to sign up get $100 free credits over the next 60 days and you can work on your PHP app for free. I connect to my DigitalOcean account and I go to Apps → Create App. I connect my GitHub Account and select the repo of my app. Make sure “Autodeploy” is checked, so the app will automatically redeploy on changes: Click “Next” then Edit Plan: By default the Pro plan is selected. Use Basic and pick the $5/month plan. Note that you pay $5 per month, but billing is per hour – so you can stop the app any time you want. Then go back and press “Next” until the “Create Resources” button appears to create the app. You don’t need any database, otherwise that would be another $7/month on top. Now wait until the deployment is ready: The app is now up and running! ConclusionYou’ve reached the end of the PHP Handbook! Thank you for reading through this introduction to the wonderful world of PHP development. I hope it will help you get your web development job, become better at your craft, and empower you to work on your next big idea. Note: you can get a PDF, ePub, or Mobi version of this handbook for easier reference, or for reading on your Kindle or tablet. Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started |