What is PHP?
PHP (Hypertext Preprocessor) is a server-side scripting language that is widely used for web development. It is especially suited for creating dynamic web pages and interacting with databases.
Setting Up PHP:
Install PHP: You can download PHP from the official PHP website (https://www.php.net/downloads.php) or use a package manager like XAMPP or WAMP, which includes PHP, Apache, and MySQL.
Configure Web Server: Make sure your web server (like Apache or Nginx) is configured to process PHP files. Usually, this involves adding PHP handler directives to your server configuration.
Your First PHP Script:
Create a new file with a .php
extension, for example, hello.php
, and add the following code:
php<?php
echo "Hello, World!";
?>
Running PHP Code:
- Save the
hello.php
file in your web server's document root directory. - Open a web browser and navigate to
http://localhost/hello.php
(replacelocalhost
with your server's hostname if necessary). - You should see the output "Hello, World!" displayed in your browser.
Basic Syntax:
- PHP code is enclosed within
<?php
and?>
tags. - Statements end with a semicolon (
;
). - Comments can be added using
//
for single-line comments or/* */
for multi-line comments.
Variables:
Variables in PHP start with a dollar sign ($
) followed by the variable name. PHP is loosely typed, meaning you don't need to declare variable types.
php<?php
$name = "John";
$age = 30;
echo "My name is $name and I am $age years old.";
?>
Control Structures:
PHP supports various control structures like if-else, loops, and switch-case statements.
php<?php
$num = 10;
if ($num > 0) {
echo "$num is positive.";
} elseif ($num < 0) {
echo "$num is negative.";
} else {
echo "$num is zero.";
}
?>
Functions:
You can define and call functions in PHP.
php<?php
function greet($name) {
echo "Hello, $name!";
}
greet("Alice");
?>
Working with Forms:
PHP is commonly used to process form data submitted by users.
html<!-- form.html -->
<form action="process.php" method="post">
Name: <input type="text" name="name"><br>
Email: <input type="email" name="email"><br>
<input type="submit" value="Submit">
</form>
php<!-- process.php -->
<?php
$name = $_POST['name'];
$email = $_POST['email'];
echo "Hello, $name! Your email is: $email";
?>
This is just a basic introduction to PHP. There's a lot more to learn, including working with databases, sessions, cookies, and more. But this should give you a good starting point. Let me know if you have any questions!
Commentaires
Enregistrer un commentaire