Basic PHP syntax:
1 |
<?php //Code ?> |
The default extension for file is .php
Example;
1 2 3 4 5 6 7 8 9 |
<!DOCTYPE html> <html> <body> <h1>My First PHP Web Script</h1> <?php echo "Hello World!"; ?> </body> </html> |
Use .php extension for all php files even if it contains HTML code.
PHP Tags
1 2 |
Opening Tags: <?php Closing Tag: ?> : It is essential if your code is followed by HTML but it is optional if no other code follows. |
Using PHP
For your PHP script to run you need to store your files inside server root folder in many cases it is htdocs or www or public_html
Viewing PHP files locally
Make sure local web server is running and then run the file using the URL like http://localhost/config.php
Check PHP configuration
Before starting you must check your PHP server is up and running and check how PHP is configured.
Create a blank file config.php
1 |
<?php phpinfo();?> |
Load the file in the browser
If you have saved the file in www directory you can load the file with localhost/config.php
Before going further make sure you have your PHP file running to make sure everything is working correctly. Please make a note of main configuration file that is php.ini you may need to edit this file.
Comments and Whitespace
Comments in PHP are the lines of that are not read/executed. Comments make the code easier to read. Another reason to use comments is to disable part of code temporarily.
1 2 3 4 5 6 7 8 9 |
<?php // This is single line comment #This is also single line comment /* This is a multi-line comment You can go in next line If a comment is long */ ?> |
Difference Between single and double Quotes
1 2 |
$title = 'The Nomimi\’s guide to escape'; echo $title; |
In PHP we use single or double quotes for a string. You can use any of these, but there is an important difference in how they work.
Example:
1 |
$title = 'The Kritika’s guide to learn'; |
If you run these code you will get an error. The problem here is that quotes must be in matching pairs.
How we can remove the error?
- Inserting a black slash in front of the apostrophe.
1 2 |
$title = 'The Kritika\’s guide to learn'; echo $title; |
The syntax error has been corrected. This is known as an escape sequence.
Problem: The main problem with escape string is that it looks ugly when there are lots of single codes inside a string.
2) Using double quotes:
Example 1:
1 2 |
$title = "The Kritika's guide to learn"; echo $title; |
Another difference between single and double quotes:
Example 1: When using single quotes to echo something
1 2 |
$title = "The Kritika's guide to learn"; echo 'this is $title'; |
An output of this: This is
1 |
this is $title |
Example 1: When using double quotes to echo something
1 2 |
$title = "The Kritika's guide to learn"; echo "this is $title"; |
An output of this:
1 |
This is The Kritika's guide to learn |