Before we start writing a lot of PHP code, let's get a server set up with a simple PHP 'Hello World'. First we need a project folder. Let's create a folder called 'HelloWorld' on our desktop. Inside it let's add a basic HTML file called
helloworld.html. Type this code into it:
<!DOCTYPE html> <html> <head> <title>helloworld</title> </head> <body> <h1>Hello World!</h1> </body> </html>
Just like in intro we can open this directly in our browser and it will display "Hello World!".
Now, let's convert this file to PHP by renaming the file to
helloworld.php. And let's tell the HTML what to say using some PHP scripts. Replace your previous code with the following:
<?php $message = "Hello World!"; ?> <!DOCTYPE html> <html> <head> <title>helloworld</title> </head> <body> <h1><?php echo $message; ?></h1> </body> </html>
Now if you try to load the page the browser isn't acting right. We see every line of code we wrote. The browser isn't parsing the HTML.
Remember PHP is a server-side scripting language. This means instead of Chrome reading our code, we need a server to read the PHP and produce the appropriate HTML for us. The development environment we'll use is called localhost. By accessing our project in this way we can make requests of our program from the browser and use the PHP software on our local machine to handle the requests from the browser and reciprocate with the desired response.
We'll start our server from the terminal by navigating to our project folder. Then we use this php command:
php -S localhost:8000
You should see something like this as output:
PHP 5.6.3 Development Server started at Wed Nov 19 10:31:09 2014 Listening on http://localhost:8000 Document root is /Users/epicodus/Desktop Press Ctrl-C to quit.
(Note: Pressing ctrl-c stops the server. You can only see your files in the browser while the server is running.)
Now let's browse to http://localhost:8000/helloworld.php. We should now see the same website as when we were working with exclusively HTML.
Remember a server is a computer program or device that uses HTTP to distribute information to a client. A client is a program or device requesting resources from a server. In our case we're creating a local development environment where the client and host (server) are on the same machine.
That said, the way they interact is exactly the same as if the two were thousands of miles apart. For example, when we use Chrome to view our Facebook page, we're making requests from Chrome to a Facebook server. Different locations... same request/response cycle.