BASH

Start Local Web Server & Open Browser

Launch a basic HTTP server using Python's `http.server` or PHP's built-in server on a specified port, then automatically open the default web browser to that address.

#!/bin/bash

PORT=${1:-8000}

echo "Attempting to start local web server on port $PORT..."

# Check for python3
if command -v python3 &> /dev/null; then
    echo "Using Python 3's http.server..."
    python3 -m http.server "$PORT" &
    SERVER_PID=$!
# Check for php
elif command -v php &> /dev/null; then
    echo "Using PHP's built-in web server..."
    php -S 0.0.0.0:"$PORT" &
    SERVER_PID=$!
else
    echo "Error: Neither python3 nor php found. Cannot start a local web server."
    exit 1
fi

echo "Server started with PID: $SERVER_PID. Opening in browser..."
sleep 2 # Give server a moment to start

# Open in default browser
if command -v xdg-open &> /dev/null; then # Linux
    xdg-open "http://localhost:$PORT"
elif command -v open &> /dev/null; then # macOS
    open "http://localhost:$PORT"
elif command -v start &> /dev/null; then # Windows (via Git Bash/WSL)
    start "http://localhost:$PORT"
else
    echo "Could not open browser automatically. Please navigate to http://localhost:$PORT manually."
fi

echo "Press Ctrl+C to stop the server."
wait "$SERVER_PID" # Wait for the server process to be killed
How it works: This script starts a simple HTTP server in the current directory. It prioritizes Python 3's `http.server`, falling back to PHP's built-in server if Python isn't available. After launching the server on the specified (or default 8000) port, it attempts to automatically open the server's URL in the default web browser, making local testing quick and easy.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs