PHP File Comparison Tool: Effortlessly Identify Code Differences with This Python Script
php file comparison tool by PrometheanLink
php file comparison tool by PrometheanLink

 

PHP File Comparator Tool

Placeholder ImageWelcome Coders to the PrometheanLink Blog. This page introduces a tool I’ve built to help you compare two PHP files easily. Follow the instructions below to use it, and you’ll find the full Python script available for copying at the end of the page.

Instructions

  1. Ensure you have Python installed on your computer along with the tkinter module.
  2. Copy the script provided below into a Python file (e.g., php_file_comparator.py).
  3. Run the script using your preferred Python IDE or the command line (python php_file_comparator.py).
  4. Use the “Browse” buttons to select the two PHP files you want to compare.
  5. Click the “Compare” button to display the differences between the files.
  6. Use the “Save Results” button to save the comparison output as a text file, if needed.
  7. Click “Clear” to reset the result area.

Python Script

Below is the full Python script for the PHP File Comparator Tool. Copy and paste this into your Python environment to start using the tool:

import tkinter as tk
from tkinter import filedialog, messagebox, scrolledtext
import difflib
def select_file1():
    file_path = filedialog.askopenfilename(title="Select the first PHP file", filetypes=[("PHP Files", "*.php"), ("All Files", "*.*")])
    if file_path:
        file1_entry.delete(0, tk.END)
        file1_entry.insert(0, file_path)
def select_file2():
    file_path = filedialog.askopenfilename(title="Select the second PHP file", filetypes=[("PHP Files", "*.php"), ("All Files", "*.*")])
    if file_path:
        file2_entry.delete(0, tk.END)
        file2_entry.insert(0, file_path)
def compare_files():
    file1_path = file1_entry.get()
    file2_path = file2_entry.get()
    if not file1_path or not file2_path:
        messagebox.showerror("Error", "Please select both files before comparing.")
        return
    try:
        with open(file1_path, 'r') as file1, open(file2_path, 'r') as file2:
            file1_lines = file1.readlines()
            file2_lines = file2.readlines()
        differ = difflib.unified_diff(
            file1_lines,
            file2_lines,
            fromfile="File 1",
            tofile="File 2",
            lineterm=''
        )
        
        result_text.delete(1.0, tk.END)
        result_text.insert(tk.END, "Differences Found:\n\n")
        for diff in differ:
            if diff.startswith("@@"):
                # Line number information
                result_text.insert(tk.END, f"Line info: {diff}\n", "highlight")
            elif diff.startswith("-"):
                # Lines removed from file 1
                result_text.insert(tk.END, f"Removed: {diff}\n", "removed")
            elif diff.startswith("+"):
                # Lines added to file 2
                result_text.insert(tk.END, f"Added: {diff}\n", "added")
            else:
                result_text.insert(tk.END, f"{diff}\n")
    except Exception as e:
        messagebox.showerror("Error", f"An error occurred while comparing files:\n{e}")
def clear_results():
    result_text.delete(1.0, tk.END)
def save_results():
    result_content = result_text.get(1.0, tk.END).strip()
    if not result_content:
        messagebox.showwarning("Warning", "No results to save!")
        return
    
    file_path = filedialog.asksaveasfilename(
        defaultextension=".txt",
        filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")],
        title="Save Comparison Results"
    )
    if file_path:
        with open(file_path, 'w') as file:
            file.write(result_content)
        messagebox.showinfo("Success", "Results saved successfully!")
# GUI setup
root = tk.Tk()
root.title("PHP File Comparator")
frame = tk.Frame(root)
frame.pack(padx=10, pady=10)
# File selection fields
file1_label = tk.Label(frame, text="File 1:")
file1_label.grid(row=0, column=0, padx=5, pady=5, sticky="e")
file1_entry = tk.Entry(frame, width=50)
file1_entry.grid(row=0, column=1, padx=5, pady=5)
file1_button = tk.Button(frame, text="Browse", command=select_file1)
file1_button.grid(row=0, column=2, padx=5, pady=5)
file2_label = tk.Label(frame, text="File 2:")
file2_label.grid(row=1, column=0, padx=5, pady=5, sticky="e")
file2_entry = tk.Entry(frame, width=50)
file2_entry.grid(row=1, column=1, padx=5, pady=5)
file2_button = tk.Button(frame, text="Browse", command=select_file2)
file2_button.grid(row=1, column=2, padx=5, pady=5)
# Buttons
compare_button = tk.Button(frame, text="Compare", command=compare_files, bg="lightgreen")
compare_button.grid(row=2, column=1, pady=10)
clear_button = tk.Button(frame, text="Clear", command=clear_results)
clear_button.grid(row=2, column=0, pady=10)
save_button = tk.Button(frame, text="Save Results", command=save_results)
save_button.grid(row=2, column=2, pady=10)
# Results area
result_text = scrolledtext.ScrolledText(root, wrap=tk.WORD, width=80, height=20)
result_text.pack(padx=10, pady=10)
# Text styling
result_text.tag_config("highlight", foreground="blue")
result_text.tag_config("removed", foreground="red")
result_text.tag_config("added", foreground="green")
# Run the application
root.mainloop()