Intro to PHP Part 2, First PHP Script

Now that you've finished installing PHP and Apache, it's time to start writing PHP! Start by opening your favorite text editor and making a new file called program1.php saved in the same server root folder as last time (in my case, it's C:\wamp64\www since I'm running windows) This page will have one regular HTML paragraph tag, and another paragraph tag that is generated by php! This can be accomplished by using php's echo'...' statement to print out a paragraph tag.

1
2
3
4
5
6
7
8
9
10
11
12
13
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf8">
    <title>PHP Program 1</title>
  </head>
  <body>
    <p>This line is regular old HTML...</p>
    <?php
      echo'<p>But this line was generated by PHP!</p>';
    ?>
  </body>
</html>

PHP is able to dynamically generate HTML code from the echo statement. As you can see from the picture below, the result looks just like normal HTML. If you view the source code below, it looks as if there was never any php there at all!

program1

One thing to note s that since the PHP code is being parsed by your apache server, you can only access the page through a URL like this:
http://localhost/program1.php (Windows)
or
http://127.0.0.1/program1.php (Linux)
or
http://localhost/~<user>/program.php(Mac)
if you try to access this page through your file directory like any normal HTML file on your hard drive like this file:///C:/wamp64/www/program1.php then the PHP code will not work. It MUST be accessed through a URL.

Like JavaScript, every line of code in PHP must be ended with a semicolon.

Escape characters

So, Imagine you're trying to use PHP to output the following:

1
2
echo"He told me, "I know PHP!"";
echo'I've learned PHP!';

Both of these lines will result in a syntax error. There are two ways to get around this. First, you could just use double quotes when printing a single quote, and use single quotes when printing a double quote...

1
2
echo'He told me, "I know PHP!"';
echo"I've learned PHP!";

And that works just fine for this example, but another method is to escape the quotes using a backslash, like this.

1
2
echo"He told me, \"I know PHP!\"";
echo'I\'ve learned PHP!';

This is especially useful if you need to print both single and double quote, like this:

1
echo"here's something that would be problematic without the \"escape\" backslashes! There's single and double quotes here."

Now that we've learned about PHP's echo statement, the next post will be about using variables in PHP.


Special thanks to Larry Ullman, whose textbooks helped me learn PHP programming (no affiliation)

Follow me!