Mini Shell

Direktori : /home/mhcadmin/public_html/Portal/
Upload File :
Current File : /home/mhcadmin/public_html/Portal/sendmailPassword.php

<?php
// Start session at the VERY beginning
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$rootPath = realpath(dirname(__FILE__) . '/..');
require_once $rootPath . '/Portal/config/config.php'; // Use clean config file

// Load PHPMailer
require 'PHPMailer/src/PHPMailer.php';
require 'PHPMailer/src/SMTP.php';
require 'PHPMailer/src/Exception.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// ============= CONFIGURATION =============
$site_name = "mhc.mw";              // Your website name
$redirect_url = "login.php";           // Form page

// SMTP Settings
$smtp_host = "localhost";       // InMotion uses localhost for SMTP
$smtp_port = 25;               // Port 25, 465, or 587 (25 is default)
$smtp_username = "";           // Leave empty for localhost (no auth needed)
$smtp_password = "";           // Leave empty for localhost
$smtp_secure = "";             // Empty, "ssl", or "tls"
// =========================================

// Check if form was submitted
if ($_SERVER["REQUEST_METHOD"] !== "POST") {
    header("Location: $redirect_url");
    exit;
}

// Anti-spam honeypot check
if (!empty($_POST['website'])) {
    header("Location: $redirect_url?success=true");
    exit;
}

// Validate and sanitize inputs
function clean_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
    return $data;
}

function generate_secure_string($length = 8) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $characters_length = strlen($characters);
    $random_string = '';
    for ($i = 0; $i < $length; $i++) {
        // Use random_int() for cryptographically secure pseudo-random integers
        $random_index = random_int(0, $characters_length - 1);
        $random_string .= $characters[$random_index];
    }
    return $random_string;
}

// Main processing logic
$email = clean_input($_POST['email'] ?? '');
$FullName = clean_input($_POST['FullName'] ?? '');

// Validate email
if (empty($email)) {
    header("Location: $redirect_url?error=Email is required");
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
	
	
    $error_message = urlencode("Invalid email format");
    header("Location: $redirect_url?error=true&message=$error_message");
	exit;
}
 
try {
    // Get DB instance and check if email exists
    $db = getDbInstance();
	$db->where("email", $email);
	$db->where("Full_Name", "%$FullName%", "LIKE");
	$row = $db->getOne('admin_accounts');
    
    // Check if email was found in database
    if ($db->count < 1) {
		
        $error_message = urlencode("Email or Name not found in our system");
        header("Location: $redirect_url?error=true&message=$error_message");
        exit;
    }
    
    // Email found - proceed with password reset
    $name = $row['user_name'];
    
    // Generate new random password
    $randomPassword = generate_secure_string(8);
    
    // You should hash the password before storing it
    $passwd = md5($randomPassword);
    
    // If you want to update the password in database immediately:
    $db->where('email', $email);
    $db->where("Full_Name", "%$FullName%", "LIKE");
    $db->update('admin_accounts', ['passwd' => $passwd]);
    
    // Create PHPMailer instance
    $mail = new PHPMailer(true);
    
    // Server settings
    $mail->isSMTP();                                      // Use SMTP
    $mail->Host       = $smtp_host;                      // SMTP server
    $mail->Port       = $smtp_port;                      // SMTP port
    $mail->SMTPAuth   = !empty($smtp_username);          // Enable SMTP authentication if username provided
    $mail->SMTPSecure = $smtp_secure;                    // Enable TLS/SSL encryption
    
    if (!empty($smtp_username)) {
        $mail->Username = $smtp_username;                // SMTP username
        $mail->Password = $smtp_password;                // SMTP password
    }
    
    // Timeout settings
    $mail->Timeout = 30;                                 // 30 second timeout
    $mail->SMTPDebug = 0;                                // Debug mode: 0 = off
    
    // Recipients
    $mail->setFrom('noreply@' . $_SERVER['HTTP_HOST'], $site_name);
    $mail->addAddress($email);                           // Add recipient
    
    // Content
    $mail->isHTML(true);                                 // Set email format to HTML
    $mail->Subject = "PASSWORD RESET - $site_name";
    
    // Email body with styling - Changed blue (#4a6fa5) to green (#28a745)
    $mail->Body = "
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset='UTF-8'>
        <style>
            body { font-family: Arial, sans-serif; line-height: 1.6; color: #333; }
            .container { max-width: 600px; margin: 0 auto; }
            .header { background: #28a745; color: white; padding: 20px; border-radius: 5px 5px 0 0; }
            .content { padding: 20px; background: #f9f9f9; }
            .field { background: white; padding: 15px; margin-bottom: 10px; border-left: 4px solid #28a745; }
            .label { font-weight: bold; color: #555; display: block; margin-bottom: 5px; }
            .password { font-size: 18px; color: #d9534f; font-weight: bold; padding: 10px; background: #f2dede; border-radius: 4px; }
            .footer { padding: 15px; text-align: center; color: #666; font-size: 12px; background: #eee; border-radius: 0 0 5px 5px; }
        </style>
    </head>
    <body>
        <div class='container'>
            <div class='header'>
                <h2>PASSWORD RESET REQUEST</h2>
            </div>
            
            <div class='content'>
                <p>Hello " . htmlspecialchars($name) . ",</p>
                <p>We received a request to reset your password for your MHC IMS account</p>
                
                <div class='field'>
                    <span class='label'>Your temporary password:</span>
                    <div class='password'>" . htmlspecialchars($randomPassword) . "</div>
                </div>
                
                <div class='field'>
                    <span class='label'>Instructions:</span>
                    <ol>
                        <li>Log in with this temporary password</li>
                        <li>Go to <strong>My Profile</strong></li>
                        <li>Change your password immediately</li>
                    </ol>
                </div>
                
                <div class='field'>
                    <span class='label'>Request Details:</span>
                    <ul>
                        <li><strong>Date & Time:</strong> " . date('F j, Y, g:i a') . "</li>
                        <li><strong>IP Address:</strong> " . $_SERVER['REMOTE_ADDR'] . "</li>
                    </ul>
                </div>
                
                <p><strong>If you didn't request this password reset, please contact ICT Team immediately.</strong></p>
            </div>
            
            <div class='footer'>
                This email was sent automatically from MHC IMS. Please do not reply to this email.
            </div>
        </div>
    </body>
    </html>";
    
    // Alternative plain text version for email clients that don't support HTML
    $mail->AltBody = "PASSWORD RESET\n\nHello $name,\n\nYou requested a password reset for your account on MHC IMS.\n\nYour temporary password: $randomPassword\n\nInstructions:\n1. Log in with this temporary password\n2. Go to your account settings\n3. Change your password immediately\n\nRequest Details:\n- Date & Time: " . date('F j, Y, g:i a') . "\n- IP Address: " . $_SERVER['REMOTE_ADDR'] . "\n\nIf you didn't request this password reset, please contact ICT Team immediately.\n\nThis email was sent automatically from MHC IMS.";
    
    // Send email
    $mail->send();
    
    // Store the temporary password in session for verification if needed
    $_SESSION['temp_password'] = $randomPassword;
    $_SESSION['reset_email'] = $email;
    
    // You might want to store the reset token in database with expiration
    // $reset_token = bin2hex(random_bytes(32));
    // $expires_at = date('Y-m-d H:i:s', strtotime('+1 hour'));
    // $db->insert('password_resets', [
    //     'email' => $email,
    //     'token' => $reset_token,
    //     'expires_at' => $expires_at
    // ]);
    
    // Redirect to success page
    $error_message = urlencode("Password reset email sent, Please check your eamil");
        header("Location: $redirect_url?success=true&message=$error_message");
	
    exit;
    
} catch (Exception $e) {
    // Log the error
    error_log("Password reset failed for $email: " . $e->getMessage());
    
    // Redirect with error message
    $error_message = urlencode("Failed to send password reset email. Please try again later.");
    header("Location: $redirect_url?error=true&message=$error_message");
    exit;
}
?>