Files
overcode/commands/cmd_new.py

1069 lines
28 KiB
Python
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
New File Creation Command with Epic Templates
"""
import os
from colorama import Fore, Style, init
init(autoreset=True)
class NewCommand:
"""Create new files with templates"""
def __init__(self, cwd, filename):
self.cwd = cwd
self.filename = filename.strip()
self.templates = {
'hello': self._hello_world_template,
'demo': self._demo_template,
'games': self._games_template,
'web': self._web_template,
'ai': self._ai_template,
'crypto': self._crypto_template
}
def run(self):
"""Execute the new file command"""
if not self.filename:
self._show_templates()
return
# Check if template is specified
parts = self.filename.split(':')
if len(parts) == 2:
template_name = parts[1].lower()
filename = parts[0]
if template_name in self.templates:
content = self.templates[template_name]()
self._create_file(filename, content)
else:
print(Fore.RED + f"Template '{template_name}' not found!")
self._show_templates()
else:
# Create basic file
self._create_file(self.filename, self._basic_template())
def _show_templates(self):
"""Show available templates"""
print(Fore.CYAN + "📄 OverCode File Templates")
print(Fore.YELLOW + "" * 30)
print()
templates = {
'hello': '👋 Hello World in multiple languages',
'demo': '🚀 Full feature demonstration',
'games': '🎮 Interactive games showcase',
'web': '🌐 Web development polyglot',
'ai': '🤖 AI and machine learning',
'crypto': '🔒 Cryptography and security'
}
for template, desc in templates.items():
print(f"{Fore.GREEN}{template:<12} {Fore.WHITE}{desc}")
print()
print(Fore.MAGENTA + "Usage:")
print(f"{Fore.WHITE} new filename.ovc:template")
print(f"{Fore.LIGHTBLACK_EX} Example: new demo.ovc:hello")
def _create_file(self, filename, content):
"""Create the file with content"""
# Ensure .ovc extension
if not filename.endswith('.ovc'):
filename += '.ovc'
filepath = os.path.join(self.cwd, filename)
try:
with open(filepath, 'w', encoding='utf-8') as f:
f.write(content)
print(Fore.GREEN + f"✓ Created: {filename}")
print(Fore.CYAN + f"📍 Location: {filepath}")
print(Fore.YELLOW + f"💡 Run with: run {filename}")
except Exception as e:
print(Fore.RED + f"Error creating file: {e}")
def _basic_template(self):
"""Basic empty template"""
return '''<?py
# OverCode - Enhanced Polyglot Programming
print("Hello from OverCode!")
?>
<?js
// JavaScript section
console.log("JavaScript is running!");
?>
<?php
// PHP section
echo "PHP is working!\\n";
?>
<!-- Add more language blocks as needed -->
'''
def _hello_world_template(self):
"""Hello World in multiple languages"""
return '''<?py
# Python Hello World
print("🐍 Hello from Python!")
print("Welcome to OverCode!")
?>
<?js
// JavaScript Hello World
console.log("🟨 Hello from JavaScript!");
console.log("Node.js is awesome!");
?>
<?php
// PHP Hello World
echo "🐘 Hello from PHP!\\n";
echo "Server-side magic!\\n";
?>
<?go
// Go Hello World
fmt.Println("🐹 Hello from Go!")
fmt.Println("Fast and efficient!")
?>
<?rs
// Rust Hello World
println!("🦀 Hello from Rust!");
println!("Memory safe and fast!");
?>
<?java
// Java Hello World
System.out.println("☕ Hello from Java!");
System.out.println("Write once, run anywhere!");
?>
<?cpp
// C++ Hello World
cout << "⚡ Hello from C++!" << endl;
cout << "The power language!" << endl;
?>
<?rb
# Ruby Hello World
puts "💎 Hello from Ruby!"
puts "Programmer happiness!"
?>'''
def _demo_template(self):
"""Full feature demonstration"""
return '''<?py
# OverCode Feature Demo
import random
import time
print("🚀 OverCode Feature Demonstration")
print("=" * 40)
# Variables and data structures
languages = ["Python", "JavaScript", "PHP", "Go", "Rust"]
print(f"Supported languages: {', '.join(languages)}")
# Random selection
chosen = random.choice(languages)
print(f"Random choice: {chosen}")
# Simple algorithm
def fibonacci(n):
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
print(f"Fibonacci(8) = {fibonacci(8)}")
?>
<?js
// JavaScript Advanced Features
const features = {
async: "Asynchronous programming",
modules: "ES6 modules",
classes: "Object-oriented programming",
functions: "First-class functions"
};
console.log("🟨 JavaScript Features:");
for (const [key, value] of Object.entries(features)) {
console.log(` ${key}: ${value}`);
}
// Arrow functions and promises
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
(async () => {
console.log("Async operation starting...");
// await delay(100);
console.log("Async operation completed!");
})();
?>
<?php
// PHP Web Features
class OverCodeDemo {
private $version = "2.0.0-ULTRA";
public function showFeatures() {
echo "🐘 PHP Features in OverCode:\\n";
echo "- Object-oriented programming\\n";
echo "- Web development capabilities\\n";
echo "- Database connectivity\\n";
echo "- Server-side logic\\n";
}
public function getVersion() {
return $this->version;
}
}
$demo = new OverCodeDemo();
$demo->showFeatures();
echo "Version: " . $demo->getVersion() . "\\n";
?>
<?go
// Go Concurrency Demo
package main
import (
"fmt"
"sync"
"time"
)
func worker(id int, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Printf("Worker %d starting\\n", id)
time.Sleep(time.Millisecond * 100)
fmt.Printf("Worker %d done\\n", id)
}
var wg sync.WaitGroup
fmt.Println("🐹 Go Concurrency Demo:")
for i := 1; i <= 3; i++ {
wg.Add(1)
go worker(i, &wg)
}
// wg.Wait()
fmt.Println("All workers completed!")
?>'''
def _games_template(self):
"""Interactive games template"""
return '''<?py
# OverCode Games Collection
import random
print("🎮 OverCode Games Showcase")
print("=" * 30)
# Number Guessing Game
def guess_game():
number = random.randint(1, 10)
print("\\n🎯 Number Guessing Game")
print("I'm thinking of a number between 1 and 10")
# Simulate a guess
guess = random.randint(1, 10)
print(f"Computer guesses: {guess}")
if guess == number:
print("🎉 Correct! You won!")
else:
print(f"❌ Wrong! The number was {number}")
guess_game()
# Rock Paper Scissors
def rps_game():
print("\\n✂ Rock Paper Scissors")
choices = ["rock", "paper", "scissors"]
player = random.choice(choices)
computer = random.choice(choices)
print(f"Player: {player}")
print(f"Computer: {computer}")
if player == computer:
print("🤝 It's a tie!")
elif (player == "rock" and computer == "scissors") or \\
(player == "paper" and computer == "rock") or \\
(player == "scissors" and computer == "paper"):
print("🏆 Player wins!")
else:
print("🤖 Computer wins!")
rps_game()
?>
<?js
// JavaScript Game Logic
console.log("\\n🕹 JavaScript Mini Games");
// Dice Rolling Simulator
function rollDice(sides = 6) {
return Math.floor(Math.random() * sides) + 1;
}
console.log("\\n🎲 Dice Rolling:");
for (let i = 0; i < 5; i++) {
console.log(`Roll ${i + 1}: ${rollDice()}`);
}
// Simple Quiz Game
const quiz = [
{ q: "What does HTML stand for?", a: "HyperText Markup Language" },
{ q: "Which company created JavaScript?", a: "Netscape" },
{ q: "What year was JavaScript created?", a: "1995" }
];
console.log("\\n🤔 Programming Quiz:");
const randomQ = quiz[Math.floor(Math.random() * quiz.length)];
console.log(`Question: ${randomQ.q}`);
console.log(`Answer: ${randomQ.a}`);
?>
<?php
// PHP Game Server Logic
echo "\\n🎰 PHP Casino Games\\n";
// Slot Machine
function spinSlots() {
$symbols = ["🍒", "🍋", "🔔", "", "💎"];
$reel1 = $symbols[array_rand($symbols)];
$reel2 = $symbols[array_rand($symbols)];
$reel3 = $symbols[array_rand($symbols)];
echo "Spinning... $reel1 $reel2 $reel3\\n";
if ($reel1 == $reel2 && $reel2 == $reel3) {
echo "🎉 JACKPOT! Three of a kind!\\n";
} elseif ($reel1 == $reel2 || $reel2 == $reel3 || $reel1 == $reel3) {
echo "🎊 Nice! Two matching symbols!\\n";
} else {
echo "😐 Try again!\\n";
}
}
spinSlots();
// Simple Blackjack
echo "\\n🃏 Blackjack Hand:\\n";
$cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
$hand = array_rand(array_flip($cards), 2);
$total = array_sum($hand);
echo "Cards: " . implode(", ", $hand) . "\\n";
echo "Total: $total\\n";
if ($total == 21) {
echo "🎉 Blackjack!\\n";
} elseif ($total > 21) {
echo "💥 Bust!\\n";
} else {
echo "🎯 Good hand!\\n";
}
?>'''
def _web_template(self):
"""Web development template"""
return '''<?py
# Python Web Backend
from datetime import datetime
import json
print("🌐 OverCode Web Development Stack")
print("=" * 40)
# API Response Simulation
def create_api_response(data):
return {
"status": "success",
"timestamp": datetime.now().isoformat(),
"data": data,
"version": "2.0.0-ULTRA"
}
# Sample user data
users = [
{"id": 1, "name": "Alice", "role": "developer"},
{"id": 2, "name": "Bob", "role": "designer"},
{"id": 3, "name": "Charlie", "role": "manager"}
]
response = create_api_response(users)
print("API Response:")
print(json.dumps(response, indent=2))
?>
<?js
// JavaScript Frontend Logic
console.log("\\n🎨 Frontend JavaScript");
// DOM Manipulation Simulation
class ComponentManager {
constructor() {
this.components = new Map();
}
register(name, component) {
this.components.set(name, component);
console.log(`✓ Component '${name}' registered`);
}
render(name) {
const component = this.components.get(name);
if (component) {
console.log(`🖼️ Rendering ${name}:`, component.template);
}
}
}
const manager = new ComponentManager();
// Register components
manager.register('header', {
template: '<header><h1>OverCode App</h1></header>',
styles: { background: '#2d3748', color: 'white' }
});
manager.register('userCard', {
template: '<div class="card"><h3>{{name}}</h3><p>{{role}}</p></div>',
props: ['name', 'role']
});
manager.render('header');
manager.render('userCard');
// Event handling simulation
const events = ['click', 'scroll', 'resize'];
events.forEach(event => {
console.log(`📡 Event listener for '${event}' attached`);
});
?>
<?php
// PHP Server-Side Logic
echo "\\n🐘 PHP Backend Services\\n";
// Database simulation
class UserService {
private $users = [];
public function __construct() {
$this->users = [
["id" => 1, "email" => "alice@overcode.dev", "active" => true],
["id" => 2, "email" => "bob@overcode.dev", "active" => true],
["id" => 3, "email" => "charlie@overcode.dev", "active" => false]
];
}
public function getActiveUsers() {
return array_filter($this->users, function($user) {
return $user['active'];
});
}
public function getUserById($id) {
foreach ($this->users as $user) {
if ($user['id'] == $id) {
return $user;
}
}
return null;
}
}
$userService = new UserService();
$activeUsers = $userService->getActiveUsers();
echo "Active Users:\\n";
foreach ($activeUsers as $user) {
echo "- {$user['email']}\\n";
}
// Session simulation
session_start();
echo "\\n🔐 Session Management:\\n";
echo "Session ID: " . session_id() . "\\n";
echo "Session started: " . date('Y-m-d H:i:s') . "\\n";
?>
<?css
/* CSS Styling */
body {
font-family: 'SF Pro Display', -apple-system, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
margin: 0;
padding: 20px;
color: #333;
}
.container {
max-width: 1200px;
margin: 0 auto;
background: rgba(255, 255, 255, 0.95);
border-radius: 12px;
padding: 30px;
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
}
.card {
background: white;
border-radius: 8px;
padding: 20px;
margin: 10px;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
transition: transform 0.2s ease;
}
.card:hover {
transform: translateY(-2px);
}
.header {
background: linear-gradient(45deg, #2d3748, #4a5568);
color: white;
padding: 20px;
border-radius: 8px 8px 0 0;
}
?>'''
def _ai_template(self):
"""AI and machine learning template"""
return '''<?py
# AI and Machine Learning with OverCode
import random
import math
print("🤖 OverCode AI Playground")
print("=" * 30)
# Simple Neural Network Simulation
class SimpleNeuron:
def __init__(self):
self.weight = random.uniform(-1, 1)
self.bias = random.uniform(-1, 1)
def activate(self, input_value):
# Sigmoid activation function
z = self.weight * input_value + self.bias
return 1 / (1 + math.exp(-z))
def train(self, inputs, targets, learning_rate=0.1):
for input_val, target in zip(inputs, targets):
output = self.activate(input_val)
error = target - output
# Update weights and bias
self.weight += learning_rate * error * input_val
self.bias += learning_rate * error
return self.weight, self.bias
# Create and train a simple neuron
neuron = SimpleNeuron()
print(f"Initial weight: {neuron.weight:.3f}, bias: {neuron.bias:.3f}")
# Training data (simple linear relationship)
training_inputs = [1, 2, 3, 4, 5]
training_targets = [0.2, 0.4, 0.6, 0.8, 1.0]
final_weight, final_bias = neuron.train(training_inputs, training_targets)
print(f"Final weight: {final_weight:.3f}, bias: {final_bias:.3f}")
# Test the trained neuron
test_input = 3.5
prediction = neuron.activate(test_input)
print(f"Prediction for {test_input}: {prediction:.3f}")
# Genetic Algorithm Example
def genetic_algorithm_demo():
print("\\n🧬 Genetic Algorithm Demo")
# Simple fitness function (maximize sum)
def fitness(individual):
return sum(individual)
# Create initial population
population_size = 6
chromosome_length = 5
population = []
for _ in range(population_size):
chromosome = [random.randint(0, 1) for _ in range(chromosome_length)]
population.append(chromosome)
print("Initial population:")
for i, individual in enumerate(population):
print(f" Individual {i}: {individual} (fitness: {fitness(individual)})")
# Selection (top 50%)
population.sort(key=fitness, reverse=True)
survivors = population[:population_size//2]
print("\\nSurvivors:")
for i, individual in enumerate(survivors):
print(f" Survivor {i}: {individual} (fitness: {fitness(individual)})")
genetic_algorithm_demo()
?>
<?js
// JavaScript AI Utilities
console.log("\\n🧠 JavaScript AI Tools");
// K-Means Clustering Simulation
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
distanceTo(other) {
return Math.sqrt(Math.pow(this.x - other.x, 2) + Math.pow(this.y - other.y, 2));
}
}
// Generate sample data points
const points = [
new Point(2, 3), new Point(3, 4), new Point(2, 4), // Cluster 1
new Point(8, 7), new Point(9, 8), new Point(8, 8), // Cluster 2
new Point(1, 1), new Point(2, 1), new Point(1, 2) // Cluster 3
];
console.log("Data Points:");
points.forEach((point, i) => {
console.log(` Point ${i}: (${point.x}, ${point.y})`);
});
// Simple centroid calculation
function calculateCentroid(pointGroup) {
const n = pointGroup.length;
const sumX = pointGroup.reduce((sum, p) => sum + p.x, 0);
const sumY = pointGroup.reduce((sum, p) => sum + p.y, 0);
return new Point(sumX / n, sumY / n);
}
const centroid = calculateCentroid(points.slice(0, 3));
console.log(`\\nCentroid of first 3 points: (${centroid.x.toFixed(2)}, ${centroid.y.toFixed(2)})`);
// Decision Tree Node
class DecisionNode {
constructor(feature, threshold, left = null, right = null) {
this.feature = feature;
this.threshold = threshold;
this.left = left;
this.right = right;
}
classify(sample) {
if (sample[this.feature] <= this.threshold) {
return this.left instanceof DecisionNode ? this.left.classify(sample) : this.left;
} else {
return this.right instanceof DecisionNode ? this.right.classify(sample) : this.right;
}
}
}
// Simple decision tree
const tree = new DecisionNode(0, 5, "Class A", "Class B");
console.log("\\n🌳 Decision Tree Classification:");
console.log(`Sample [3]: ${tree.classify([3])}`);
console.log(`Sample [7]: ${tree.classify([7])}`);
?>
<?php
// PHP ML Data Processing
echo "\\n📊 PHP Data Processing\\n";
// Data preprocessing utilities
class DataProcessor {
public static function normalize($data) {
$min = min($data);
$max = max($data);
$range = $max - $min;
return array_map(function($value) use ($min, $range) {
return $range > 0 ? ($value - $min) / $range : 0;
}, $data);
}
public static function standardize($data) {
$mean = array_sum($data) / count($data);
$variance = array_sum(array_map(function($x) use ($mean) {
return pow($x - $mean, 2);
}, $data)) / count($data);
$stddev = sqrt($variance);
return array_map(function($value) use ($mean, $stddev) {
return $stddev > 0 ? ($value - $mean) / $stddev : 0;
}, $data);
}
}
// Sample dataset
$rawData = [10, 20, 15, 35, 25, 40, 30];
echo "Original data: " . implode(", ", $rawData) . "\\n";
$normalizedData = DataProcessor::normalize($rawData);
echo "Normalized: " . implode(", ", array_map(function($x) {
return number_format($x, 3);
}, $normalizedData)) . "\\n";
$standardizedData = DataProcessor::standardize($rawData);
echo "Standardized: " . implode(", ", array_map(function($x) {
return number_format($x, 3);
}, $standardizedData)) . "\\n";
// Simple recommendation system
class RecommendationEngine {
private $userPreferences = [];
public function addUser($userId, $preferences) {
$this->userPreferences[$userId] = $preferences;
}
public function cosineSimilarity($user1, $user2) {
$prefs1 = $this->userPreferences[$user1];
$prefs2 = $this->userPreferences[$user2];
$dotProduct = 0;
$norm1 = 0;
$norm2 = 0;
foreach ($prefs1 as $item => $rating1) {
if (isset($prefs2[$item])) {
$rating2 = $prefs2[$item];
$dotProduct += $rating1 * $rating2;
$norm1 += $rating1 * $rating1;
$norm2 += $rating2 * $rating2;
}
}
return ($norm1 * $norm2) > 0 ? $dotProduct / (sqrt($norm1) * sqrt($norm2)) : 0;
}
}
$engine = new RecommendationEngine();
$engine->addUser('user1', ['python' => 5, 'javascript' => 4, 'php' => 3]);
$engine->addUser('user2', ['python' => 4, 'javascript' => 5, 'ruby' => 4]);
$similarity = $engine->cosineSimilarity('user1', 'user2');
echo "\\nUser similarity: " . number_format($similarity, 3) . "\\n";
?>'''
def _crypto_template(self):
"""Cryptography and security template"""
return '''<?py
# Cryptography and Security with OverCode
import hashlib
import random
import string
print("🔒 OverCode Security & Cryptography")
print("=" * 40)
# Hash Functions
def demonstrate_hashing():
message = "OverCode is awesome!"
# Different hash algorithms
algorithms = ['md5', 'sha1', 'sha256', 'sha512']
print("Hash Function Demonstration:")
print(f"Original message: '{message}'\\n")
for algo in algorithms:
hasher = hashlib.new(algo)
hasher.update(message.encode('utf-8'))
hash_value = hasher.hexdigest()
print(f"{algo.upper():<6}: {hash_value}")
demonstrate_hashing()
# Simple Caesar Cipher
def caesar_cipher(text, shift):
result = ""
for char in text:
if char.isalpha():
ascii_offset = 65 if char.isupper() else 97
shifted = (ord(char) - ascii_offset + shift) % 26
result += chr(shifted + ascii_offset)
else:
result += char
return result
print("\\n🔐 Caesar Cipher Demo:")
original = "HELLO OVERCODE"
encrypted = caesar_cipher(original, 13) # ROT13
decrypted = caesar_cipher(encrypted, -13)
print(f"Original: {original}")
print(f"Encrypted: {encrypted}")
print(f"Decrypted: {decrypted}")
# Password Generator
def generate_password(length=12):
chars = string.ascii_letters + string.digits + "!@#$%^&*"
return ''.join(random.choice(chars) for _ in range(length))
print("\\n🔑 Secure Password Generation:")
for i in range(3):
password = generate_password(16)
print(f"Password {i+1}: {password}")
# Simple XOR Cipher
def xor_cipher(data, key):
return bytes([data[i] ^ key[i % len(key)] for i in range(len(data))])
print("\\n⚡ XOR Cipher Demo:")
message = b"Secret Message"
key = b"KEY123"
encrypted = xor_cipher(message, key)
decrypted = xor_cipher(encrypted, key)
print(f"Original: {message.decode()}")
print(f"Key: {key.decode()}")
print(f"Encrypted: {encrypted.hex()}")
print(f"Decrypted: {decrypted.decode()}")
?>
<?js
// JavaScript Cryptographic Functions
console.log("\\n🛡 JavaScript Security Tools");
// Base64 Encoding/Decoding
function base64Demo() {
const message = "OverCode Security Demo";
// Simulate base64 encoding (simplified)
const encoded = btoa ? btoa(message) : "Encoded: " + message;
console.log("\\n📝 Base64 Encoding:");
console.log(`Original: ${message}`);
console.log(`Encoded: ${encoded}`);
}
base64Demo();
// JWT Token Structure Simulation
class SimpleJWT {
static create(payload, secret) {
const header = { alg: "HS256", typ: "JWT" };
const headerB64 = btoa(JSON.stringify(header));
const payloadB64 = btoa(JSON.stringify(payload));
// Simplified signature (not cryptographically secure)
const signature = btoa(headerB64 + payloadB64 + secret).slice(0, 16);
return `${headerB64}.${payloadB64}.${signature}`;
}
static decode(token) {
const [header, payload, signature] = token.split('.');
return {
header: JSON.parse(atob(header)),
payload: JSON.parse(atob(payload)),
signature: signature
};
}
}
console.log("\\n🎫 JWT Token Demo:");
const payload = { userId: 123, username: "developer", exp: Date.now() + 3600000 };
const token = SimpleJWT.create(payload, "secret123");
console.log("Generated Token:", token);
const decoded = SimpleJWT.decode(token);
console.log("Decoded Payload:", decoded.payload);
// Random Number Generation
console.log("\\n🎲 Secure Random Numbers:");
for (let i = 0; i < 5; i++) {
// Use crypto.getRandomValues if available, fallback to Math.random
const randomNum = typeof crypto !== 'undefined' && crypto.getRandomValues
? crypto.getRandomValues(new Uint32Array(1))[0]
: Math.floor(Math.random() * 1000000);
console.log(`Random ${i + 1}: ${randomNum}`);
}
// Hash Table for Password Storage Simulation
class PasswordManager {
constructor() {
this.users = new Map();
}
// Simulate password hashing (not cryptographically secure)
hash(password) {
let hash = 0;
for (let i = 0; i < password.length; i++) {
const char = password.charCodeAt(i);
hash = ((hash << 5) - hash) + char;
hash = hash & hash; // Convert to 32-bit integer
}
return hash.toString(16);
}
register(username, password) {
const hashedPassword = this.hash(password);
this.users.set(username, hashedPassword);
console.log(`✓ User '${username}' registered`);
}
verify(username, password) {
const storedHash = this.users.get(username);
const inputHash = this.hash(password);
return storedHash === inputHash;
}
}
const pm = new PasswordManager();
pm.register("alice", "securepass123");
pm.register("bob", "mypassword456");
console.log("\\n🔍 Password Verification:");
console.log("Alice correct password:", pm.verify("alice", "securepass123"));
console.log("Alice wrong password:", pm.verify("alice", "wrongpass"));
?>
<?php
// PHP Security Implementation
echo "\\n🔐 PHP Security Features\\n";
// Secure Session Management
class SecureSession {
public static function start() {
// Security settings for sessions
ini_set('session.cookie_httponly', 1);
ini_set('session.cookie_secure', 1);
ini_set('session.use_strict_mode', 1);
session_start();
// Regenerate session ID periodically
if (!isset($_SESSION['created'])) {
$_SESSION['created'] = time();
} else if (time() - $_SESSION['created'] > 1800) {
session_regenerate_id(true);
$_SESSION['created'] = time();
}
}
public static function setSecureData($key, $value) {
$_SESSION[$key] = $value;
}
public static function getSecureData($key) {
return isset($_SESSION[$key]) ? $_SESSION[$key] : null;
}
}
// CSRF Token Generation
class CSRFProtection {
public static function generateToken() {
return bin2hex(random_bytes(32));
}
public static function validateToken($token) {
return isset($_SESSION['csrf_token']) && hash_equals($_SESSION['csrf_token'], $token);
}
}
echo "CSRF Token: " . CSRFProtection::generateToken() . "\\n";
// SQL Injection Prevention (Prepared Statements Simulation)
class SafeDatabase {
public static function prepare($query, $params = []) {
// Simulate prepared statement
echo "Prepared Query: $query\\n";
echo "Parameters: " . json_encode($params) . "\\n";
// In real implementation, this would use PDO prepared statements
foreach ($params as $key => $value) {
$escaped = addslashes($value);
echo "Parameter $key: '$escaped' (escaped)\\n";
}
}
}
echo "\\n🛡 SQL Injection Prevention:\\n";
SafeDatabase::prepare(
"SELECT * FROM users WHERE username = ? AND email = ?",
["alice", "alice@example.com"]
);
// Input Sanitization
class InputSanitizer {
public static function sanitizeString($input) {
return htmlspecialchars(strip_tags(trim($input)), ENT_QUOTES, 'UTF-8');
}
public static function sanitizeEmail($email) {
return filter_var($email, FILTER_SANITIZE_EMAIL);
}
public static function validateEmail($email) {
return filter_var($email, FILTER_VALIDATE_EMAIL);
}
}
echo "\\n🧹 Input Sanitization:\\n";
$dangerousInput = "<script>alert('XSS')</script>Hello World";
$sanitized = InputSanitizer::sanitizeString($dangerousInput);
echo "Dangerous input: $dangerousInput\\n";
echo "Sanitized: $sanitized\\n";
$email = "user@example.com";
echo "Email validation: " . ($InputSanitizer::validateEmail($email) ? "Valid" : "Invalid") . "\\n";
// File Upload Security
class SecureFileUpload {
private static $allowedTypes = ['image/jpeg', 'image/png', 'image/gif'];
private static $maxSize = 5 * 1024 * 1024; // 5MB
public static function validateFile($file) {
$errors = [];
// Check file size
if ($file['size'] > self::$maxSize) {
$errors[] = "File too large";
}
// Check file type
if (!in_array($file['type'], self::$allowedTypes)) {
$errors[] = "Invalid file type";
}
// Check for upload errors
if ($file['error'] !== UPLOAD_ERR_OK) {
$errors[] = "Upload error occurred";
}
return $errors;
}
}
echo "\\n📁 File Upload Security Demo\\n";
$mockFile = [
'name' => 'image.jpg',
'type' => 'image/jpeg',
'size' => 1024 * 1024, // 1MB
'error' => 0
];
$errors = SecureFileUpload::validateFile($mockFile);
echo "File validation: " . (empty($errors) ? "Passed" : implode(", ", $errors)) . "\\n";
?>'''