ファイルをチェックするとき、パスの関係でヘッダーやフッダー、画像など、うまく開けなかったりすることってありますよね。
そんなとき、ローカルサーバがあるとすごく便利です。URLでアクセスできるようになるので、
Excelマクロと組み合わせれば、複数ページのスクリーンショットをまとめて撮ることもできます。
ローカルサーバを立ち上げて、HTMLやPHPの動作を確認できるようにしておくと、
Webディレクターにとってはかなりメリットがあります。
自分で動きを確認できるので、デザインや仕様のズレにすぐ気づけるし、開発メンバーへの指示も的確に出せるようになります。
クライアントへの事前説明やデモも、ローカルで動かして見せられるので話が早く、公開前にしっかり確認できます。
ネットがない場所でも作業できるし、外部に公開しないからセキュリティ的にも安心。
スケジュール管理や品質チェックにも役立ちます。
XAMPPみたいなツールを使ってもOKですが、
Pythonが入っていれば、コマンド一発でサーバを立ち上げられるので、
わざわざ環境を整えなくてもすぐ確認できます
また複数のフォルダーから起動できるのでアプリと違って、どのフォルダーからでも立ち上げられるのでバージョン違いや必要なフォルダーを指定できるのがが嬉しいポイントです。
run_server.py
という名前で保存して実行
このPythonスクリプトは、index.php
または index.html
をローカルで簡単に確認できる ローカルサーバ起動ツール です。PHPが使える場合はPHPサーバを、使えない場合はPythonの簡易HTTPサーバを自動で選んで起動してくれます。
import subprocess
import webbrowser
import time
import shutil
import sys
import os
import socket
# 必要な外部モジュールの確認と自動インストール
required_modules = {
"bs4": "beautifulsoup4",
"lxml": "lxml"
}
for module_name, package_name in required_modules.items():
try:
__import__(module_name)
except ImportError:
print(f"{package_name} が見つかりません。インストールを試みます...")
try:
subprocess.check_call([sys.executable, "-m", "pip", "install", package_name])
except subprocess.CalledProcessError:
print(f"{package_name} のインストールに失敗しました。手動でインストールしてください。")
sys.exit(1)
# モジュールのインポート
from http.server import SimpleHTTPRequestHandler
from socketserver import TCPServer
import threading
from bs4 import BeautifulSoup
# 実行ファイルの位置を取得
base_path = os.path.dirname(os.path.abspath(__file__))
# 利用可能なポートを探す(8000〜8008まで)
def find_available_port(start_port=8000, max_tries=9):
for port in range(start_port, start_port + max_tries):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
try:
s.bind(("localhost", port))
return port
except OSError:
continue
return None
class CustomHTTPRequestHandler(SimpleHTTPRequestHandler):
def do_GET(self):
if self.path.endswith(".html"):
file_path = os.path.join(base_path, self.path[1:])
if os.path.exists(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
content = self.process_includes(content)
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(content.encode('utf-8'))
else:
self.send_error(404, "File not found")
else:
super().do_GET()
def process_includes(self, content):
soup = BeautifulSoup(content, "lxml")
comments = soup.find_all(string=lambda text: isinstance(text, str) and "#include" in text)
for comment in comments:
if '<!--#include' in comment:
try:
file_path = comment.split('file="')[1].split('"')[0]
include_file_path = os.path.join(base_path, file_path)
if os.path.exists(include_file_path):
with open(include_file_path, 'r', encoding='utf-8') as include_file:
include_content = include_file.read()
include_soup = BeautifulSoup(include_content, "lxml")
comment.replace_with(include_soup)
else:
comment.replace_with(f"<!-- File {file_path} not found -->")
except Exception as e:
comment.replace_with(f"<!-- Error processing include: {e} -->")
return str(soup)
def start_python_server(port):
handler = CustomHTTPRequestHandler
os.chdir(base_path)
try:
httpd = TCPServer(("", port), handler)
except OSError:
print(f"ポート {port} は使用中です。別のポートを探します...")
port = find_available_port(start_port=port + 1)
if port is None:
return None, None
httpd = TCPServer(("", port), handler)
print(f"✅ Python HTTPサーバを起動中: http://localhost:{port}")
thread = threading.Thread(target=httpd.serve_forever)
thread.daemon = True
thread.start()
return httpd, port
def start_php_server(port):
os.chdir(base_path)
try:
proc = subprocess.Popen(["php", "-S", f"localhost:{port}"])
except OSError:
print(f"ポート {port} は使用中です。別のポートを探します...")
port = find_available_port(start_port=port + 1)
if port is None:
return None, None
proc = subprocess.Popen(["php", "-S", f"localhost:{port}"])
print(f"✅ PHPローカルサーバを起動中: http://localhost:{port}")
return proc, port
# サーバ起動条件の確認
has_index_php = os.path.exists(os.path.join(base_path, "index.php"))
php_available = shutil.which("php") is not None
initial_port = 8000
# サーバ起動処理
if php_available and has_index_php:
server_process, PORT = start_php_server(initial_port)
if server_process is None:
print("❌ 8000〜8008 のポートがすべて使用中です。サーバを起動できません。")
input("何かキーを押すと終了します。")
sys.exit(1)
use_subprocess = True
else:
if not php_available:
print("ℹ PHP が見つかりません。")
if not has_index_php:
print("ℹ index.php が見つかりません。")
print("Python HTTPサーバを使用します。")
httpd, PORT = start_python_server(initial_port)
if httpd is None:
print("❌ 8000〜8008 のポートがすべて使用中です。サーバを起動できません。")
input("何かキーを押すと終了します。")
sys.exit(1)
use_subprocess = False
# ブラウザを開く
URL = f"http://localhost:{PORT}"
time.sleep(1)
webbrowser.open(URL)
# 終了待機ループ
try:
while True:
key = input("終了するには「q」を押してください: ")
if key.strip().upper() == 'q':
print("🛑 サーバを停止中...")
if use_subprocess:
server_process.terminate()
else:
httpd.shutdown()
break
except KeyboardInterrupt:
print("\n🛑 キーボード割り込みを受け取りました。")
if use_subprocess:
server_process.terminate()
else:
httpd.shutdown()
使い方
このスクリプトの使い方
このスクリプトを使えば、ローカル環境でHTMLやPHPファイルを簡単に表示・確認できます。Webディレクターやデザイナーでも扱いやすく、面倒な設定は不要です。
事前準備
- 表示させたい
index.html
またはindex.php
などのファイルを、スクリプト(例:run_server.py
)と同じフォルダに置きます。 - PHPファイルを動かしたい場合は、PCにPHPをインストールしておきましょう(HTMLだけなら不要です)。
起動方法
- スクリプトファイル(例:
run_server.py
)を ダブルクリック するか、ターミナル(コマンドプロンプト)から以下を実行します:
python run_server.py
- 実行すると、フォルダ内の
index.php
が存在し、PHPが使える場合は PHPのローカルサーバ が起動します。 - もしPHPが使えない場合や
index.php
がない場合は、Pythonの簡易HTTPサーバ が自動で使われます。
自動でブラウザが開く!
1秒ほど待つと、ブラウザが自動で開いて http://localhost:8000
を表示します。 これで、対象のHTMLやPHPページをローカルで確認できます。
⏹ サーバの停止方法
- サーバを終了したいときは、Pythonのコンソール画面で 「q」 を入力してください。
- もしくは、
Ctrl + C
を押して強制終了も可能です。
PHPも使いたいときは?
PHPを使いたい場合は、あらかじめPCにPHPをインストールしておけばOK!
このスクリプトは自動でPHPサーバを起動してくれるので、特別な設定は不要です。
HTMLだけならそのままでも使えるので、まずは気軽に試してみてください。
PHPのインストール方法(Windows向け)
✅ 1. PHP をダウンロードする
- 公式サイト(https://www.php.net/downloads)にアクセス
- 「Windows downloads」をクリック
- 「ZIP版(Non Thread Safe / x64 など)」(Zip [xx.xxMB]を選んでダウンロード
- ダウンロードしたZIPファイルを解凍し、
例:C:\data\php
フォルダに置いておく
✅ 2. 環境変数に PHP のパスを追加する
PHPをコマンドで使えるようにするための設定です。
- スタートメニューを開いて
「環境変数」や「システムの環境変数を編集」と入力して、出てきた項目をクリック- 「システムのプロパティ」というウィンドウが開きます
→ 右下の「環境変数(N)…」をクリック- 「環境変数」という画面が開きます
→ 下の「システム環境変数」または上の「ユーザー環境変数」の中から
「Path」 を探して選び、「編集(E)…」をクリック- 「Pathの編集」画面で
→ 「新規(N)」をクリックして、PHPを置いたフォルダのパスを入力
例:C:\data\php
- OK を押して、すべてのウィンドウを閉じる
✅ 3. コマンドプロンプトで動作確認
次のコマンドを入力して Enter:
スタートメニューから「cmd」または「コマンドプロンプト」を起動php -v
ちょっとした画面チェックや、クライアントに見せる簡易デモにもぴったり!
ネットがない環境でも使えるから、外出先や制限のある社内ネットでも安心です。
HTMLだけでも、PHPがあればさらに柔軟に対応できるので、ディレクター業務の強い味方になりますよ。
サンプルコードは、下記から取れます