Fun Programming

Running Your First PHP Script

So, you’ve set up your local environment (XAMPP, MAMP, or LAMP) and you’re ready to dive into PHP. But wait—how do you actually run a PHP script? No worries, I got you! In this guide, we’ll walk through creating and running your first PHP script like a pro. Spoiler alert: It’s easier than you think!

Step 1: Create a PHP File

First, you need to create a file with a .php extension. Here’s how:

  1. Open your favorite code editor (VS Code, Sublime Text, Notepad++, or even Notepad if you’re feeling adventurous).
  2. Create a new file and save it as index.php inside your local server's web directory:
    • XAMPP: C:\xampp\htdocs\myproject\
    • MAMP: /Applications/MAMP/htdocs/myproject/
    • LAMP: /var/www/html/myproject/

Step 2: Write Your First PHP Code

Now, let’s write a simple PHP script that prints "Hello, World!" to the browser.

<?php
  echo "Hello, World!";
?>

Explanation:

  • <?php – Tells the server that PHP code is starting.
  • echo – Outputs text to the browser.
  • "Hello, World!"; – The text to display.
  • ?> – Ends the PHP code (optional in some cases).

Step 3: Run Your PHP Script

Now, let’s see the magic happen!

  1. Start your local server (XAMPP, MAMP, or LAMP).
  2. Open your web browser and go to:
    http://localhost/myproject/index.php
    
  3. If everything is set up correctly, you should see:
    Hello, World!
    

Congratulations! You just ran your first PHP script!

Common Issues & Fixes

1. PHP Code Not Running, Just Showing as Text

Fix: Make sure your file is saved as .php, not .html. Also, check that your server is running!

2. 404 Error – File Not Found

Fix: Ensure your file is inside the correct directory (e.g., htdocs for XAMPP).

3. Blank Page

Fix: Enable error reporting in PHP by adding this at the top of your script:

<?php
  error_reporting(E_ALL);
  ini_set('display_errors', 1);
?>

You did it! Running your first PHP script is a major milestone in your PHP journey. Now that you know how to execute PHP files, the real fun begins—dynamic pages, forms, databases, and beyond!

Next up: Let’s explore variables and data types in PHP. Until then, keep coding and don’t forget to have fun! 

No comments:

Post a Comment