/home/u764571690/domains/savitrfoundation.com/public_html
Edit: /home/u764571690/domains/savitrfoundation.com/public_html/scholarshipapply.php (219769B)
$maxDimension || $height > $maxDimension) {
if ($width > $height) {
$newWidth = $maxDimension;
$newHeight = intval(($height / $width) * $maxDimension);
} else {
$newHeight = $maxDimension;
$newWidth = intval(($width / $height) * $maxDimension);
}
} else {
$newWidth = $width;
$newHeight = $height;
}
$quality = 70;
$attempts = 0;
$maxAttempts = 15;
do {
// Create new image with current dimensions
$newImage = imagecreatetruecolor($newWidth, $newHeight);
// Preserve transparency for PNG and GIF
if ($mime == 'image/png' || $mime == 'image/gif') {
imagealphablending($newImage, false);
imagesavealpha($newImage, true);
$transparent = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
imagefilledrectangle($newImage, 0, 0, $newWidth, $newHeight, $transparent);
}
// Resize image
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
// Save to temporary file
$tempFile = $destination . '.tmp';
switch ($mime) {
case 'image/jpeg':
case 'image/jpg':
imagejpeg($newImage, $tempFile, $quality);
break;
case 'image/png':
$pngQuality = intval((100 - $quality) / 11.11);
imagepng($newImage, $tempFile, $pngQuality);
break;
case 'image/gif':
imagegif($newImage, $tempFile);
break;
}
imagedestroy($newImage);
// Check file size
$currentSize = filesize($tempFile);
if ($currentSize <= $targetSize) {
// Success!
rename($tempFile, $destination);
imagedestroy($image);
return true;
}
// File still too large
if ($quality > 35) {
$quality -= 5;
} else {
$newWidth = intval($newWidth * 0.85);
$newHeight = intval($newHeight * 0.85);
$quality = 60;
}
if (file_exists($tempFile)) {
unlink($tempFile);
}
$attempts++;
} while ($attempts < $maxAttempts && $newWidth > 200 && $newHeight > 200);
// Final attempt with very aggressive settings
$newWidth = intval($newWidth * 0.7);
$newHeight = intval($newHeight * 0.7);
$newImage = imagecreatetruecolor($newWidth, $newHeight);
if ($mime == 'image/png' || $mime == 'image/gif') {
imagealphablending($newImage, false);
imagesavealpha($newImage, true);
$transparent = imagecolorallocatealpha($newImage, 255, 255, 255, 127);
imagefilledrectangle($newImage, 0, 0, $newWidth, $newHeight, $transparent);
}
imagecopyresampled($newImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
switch ($mime) {
case 'image/jpeg':
case 'image/jpg':
imagejpeg($newImage, $destination, 30);
break;
case 'image/png':
imagepng($newImage, $destination, 8);
break;
case 'image/gif':
imagegif($newImage, $destination);
break;
}
imagedestroy($image);
imagedestroy($newImage);
return true;
}
// Referral: capture referrer user id from query to include in hidden field
$referrerUserId = isset($_GET['ref']) ? trim($_GET['ref']) : '';
// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['form_submitted'])) {
// Process form data and save to database
$success = processApplication($_POST);
if ($success) {
$_SESSION['success'] = "Application submitted successfully!";
header('Location: scholarshipapply?success=1');
exit();
}
}
function processApplication($data) {
global $pdo;
// Normalize aadhar number (remove spaces)
$normalizedAadhar = isset($data['aadhar_number']) ? preg_replace('/\s+/', '', trim($data['aadhar_number'])) : '';
$data['aadhar_number'] = $normalizedAadhar;
// Debug: Log the received data
error_log('Received application data: ' . print_r($data, true));
try {
$pdo->beginTransaction();
// Check for duplicate applications
$duplicateCheck = $pdo->prepare("
SELECT applicant_id FROM applicants
WHERE email = ? OR phone = ? OR aadhar_number = ?
");
$duplicateCheck->execute([
$data['email'],
$data['phone'],
$data['aadhar_number']
]);
if ($duplicateCheck->rowCount() > 0) {
$pdo->rollBack();
$_SESSION['error'] = "Application already exists. Please contact technical officer to renew or for other queries at 7772056856 (WhatsApp and call) !";
return false;
}
$normalizedAccountNumber = isset($data['account_number']) ? preg_replace('/\s+/', '', $data['account_number']) : '';
$normalizedIfscCode = isset($data['ifsc_code']) ? strtoupper(trim($data['ifsc_code'])) : '';
if (empty($normalizedAccountNumber)) {
$pdo->rollBack();
$_SESSION['error'] = 'Bank account number is required.';
return false;
}
$accountCheck = $pdo->prepare("SELECT applicant_id, application_id FROM applicants WHERE account_number = ?");
$accountCheck->execute([$normalizedAccountNumber]);
if ($accountCheck->rowCount() > 0) {
$existingAccount = $accountCheck->fetch(PDO::FETCH_ASSOC);
$existingApplicationId = $existingAccount['application_id'] ?? null;
$pdo->rollBack();
$_SESSION['error'] = $existingApplicationId
? "This bank account is already linked with application ID {$existingApplicationId}. Please use a different bank account or contact support."
: "This bank account has already been used in another application. Please use a different bank account or contact support.";
return false;
}
// Create documents_upload directory if it doesn't exist
$uploadDir = 'documents_upload/';
if (!file_exists($uploadDir)) {
if (!mkdir($uploadDir, 0777, true)) {
throw new Exception('Failed to create documents upload directory');
}
}
// Normalize empty strings to NULL for optional numeric fields
$normalizeEmptyToNull = function($value) {
return ($value === '' || $value === null) ? null : $value;
};
// Normalize numeric fields - convert empty strings to NULL
$annualSchoolFees = isset($data['annual_school_fees']) && $data['annual_school_fees'] !== ''
? (is_numeric($data['annual_school_fees']) ? $data['annual_school_fees'] : null)
: null;
$annualCollegeFees = isset($data['annual_college_fees']) && $data['annual_college_fees'] !== ''
? (is_numeric($data['annual_college_fees']) ? $data['annual_college_fees'] : null)
: null;
// Insert applicant data with improved error handling
$stmt = $pdo->prepare("
INSERT INTO applicants (name, phone, whatsapp, email, dob, age, gender, education_level, category, marital_status, scheme_name, father_name, mother_name, aadhar_number, nationality, family_income, address, pincode, state, district, city, institution_type, institution_name, class, course, year, annual_school_fees, annual_college_fees, last_exam_percentage, existing_scholarship, bank_name, account_holder_name, account_number, ifsc_code, branch_name, referred_by_user_id)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");
$result = $stmt->execute([
$data['name'],
$data['phone'],
$data['whatsapp'],
$data['email'],
$data['dob'],
$data['age'],
$data['gender'],
$data['education_level'],
$data['category'],
$data['marital_status'],
$data['scheme_name'],
$data['father_name'],
$data['mother_name'],
$data['aadhar_number'],
$data['nationality'],
$data['family_income'],
$data['address'],
$data['pincode'],
$data['state'],
$data['district'],
$data['city'],
$data['institution_type'],
$data['institution_name'],
$normalizeEmptyToNull($data['class'] ?? null),
$normalizeEmptyToNull($data['course'] ?? null),
$data['year'],
$annualSchoolFees,
$annualCollegeFees,
$data['last_exam_percentage'],
$data['existing_scholarship'],
$data['bank_name'],
$data['account_holder_name'],
$normalizedAccountNumber,
$normalizedIfscCode,
$data['branch_name'],
$normalizeEmptyToNull($data['referred_by_user_id'] ?? null)
]); if (!$result) {
throw new Exception('Failed to insert applicant data');
}
// Debug: Log the data being inserted
error_log('Inserting applicant data: institution_type=' . ($data['institution_type'] ?? 'NULL') .
', institution_name=' . ($data['institution_name'] ?? 'NULL') .
', year=' . ($data['year'] ?? 'NULL') .
', class=' . ($data['class'] ?? 'NULL') .
', course=' . ($data['course'] ?? 'NULL'));
$applicantId = $pdo->lastInsertId();
if (!$applicantId) {
throw new Exception('Failed to get applicant ID');
}
// Generate APP2025 format application ID
$appId = 'APP2025' . str_pad($applicantId, 6, '0', STR_PAD_LEFT);
// Save application_id to database
$updateStmt = $pdo->prepare("UPDATE applicants SET application_id = ? WHERE applicant_id = ?");
$updateResult = $updateStmt->execute([$appId, $applicantId]);
if (!$updateResult) {
throw new Exception('Failed to update application ID');
}
// Store application ID in session for popup
$_SESSION['new_application_id'] = $appId;
// Create applicant-specific folder using APP2025 ID
$applicantFolder = $uploadDir . $appId . '/';
if (!file_exists($applicantFolder)) {
if (!mkdir($applicantFolder, 0777, true)) {
throw new Exception('Failed to create applicant folder');
}
}
// Handle document uploads - SESSION-BASED APPROACH (files already uploaded via AJAX)
$uploadErrors = [];
if (isset($_SESSION['uploaded_documents']) && !empty($_SESSION['uploaded_documents'])) {
foreach ($_SESSION['uploaded_documents'] as $field => $fileInfo) {
$tempPath = $fileInfo['temp_path'];
if (file_exists($tempPath)) {
// Generate final filename
$fileName = basename($tempPath);
$finalPath = $applicantFolder . $fileName;
// Move file from temp to final location
if (rename($tempPath, $finalPath)) {
// Insert document record
$docStmt = $pdo->prepare("
INSERT INTO documents (applicant_id, document_type, document_name, document_path)
VALUES (?, ?, ?, ?)
");
$docResult = $docStmt->execute([
$applicantId,
$field,
$fileInfo['original_name'],
$finalPath
]);
if (!$docResult) {
error_log("❌ Failed to insert document record for {$field}");
} else {
error_log("✅ Moved {$field}: " . round($fileInfo['webp_size']/1024, 2) . "KB");
}
} else {
error_log("❌ Failed to move file for {$field}: {$tempPath} to {$finalPath}");
}
} else {
error_log("❌ Temp file not found for {$field}: {$tempPath}");
}
}
// Clean up temp folder
if (isset($_SESSION['upload_session_id'])) {
$userTempDir = 'documents_upload/temp_uploads/' . $_SESSION['upload_session_id'] . '/';
if (is_dir($userTempDir)) {
// Remove temp directory
$files = glob($userTempDir . '*');
if ($files) {
foreach ($files as $file) {
if (is_file($file)) {
unlink($file);
}
}
}
rmdir($userTempDir);
}
}
// Clear session data
unset($_SESSION['uploaded_documents']);
unset($_SESSION['upload_session_id']);
}
// If there were upload errors, rollback and show errors
if (!empty($uploadErrors)) {
$pdo->rollBack();
$_SESSION['error'] = implode("
", $uploadErrors);
return false;
}
$pdo->commit();
return true;
} catch(Exception $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
error_log("Application submission failed: " . $e->getMessage());
// Convert technical errors to user-friendly messages
$errorMessage = $e->getMessage();
$userFriendlyMessage = convertToUserFriendlyError($errorMessage);
$_SESSION['error'] = $userFriendlyMessage;
return false;
} catch(PDOException $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
error_log("Application submission failed: " . $e->getMessage());
// Convert database errors to user-friendly messages
$errorMessage = $e->getMessage();
$userFriendlyMessage = convertToUserFriendlyError($errorMessage);
$_SESSION['error'] = $userFriendlyMessage;
return false;
}
}
/**
* Convert technical database errors to user-friendly messages
*/
function convertToUserFriendlyError($errorMessage) {
// Common error patterns and their user-friendly messages
$errorPatterns = [
// Empty field errors
'/column `[^`]+`\.`([^`]+)` at row \d+/i' => 'कृपया सभी आवश्यक फ़ील्ड भरें।',
'/Incorrect decimal value: \'\' for column `[^`]+`\.`([^`]+)`/i' => function($matches) {
$fieldName = $matches[1] ?? 'field';
$fieldMap = [
'annual_school_fees' => 'वार्षिक स्कूल शुल्क',
'annual_college_fees' => 'वार्षिक कॉलेज शुल्क'
];
$hindiName = $fieldMap[$fieldName] ?? $fieldName;
return "कृपया {$hindiName} फ़ील्ड को सही तरीके से भरें। यह फ़ील्ड खाली नहीं हो सकती।";
},
// Duplicate entry errors
'/Duplicate entry/i' => 'यह जानकारी पहले से मौजूद है। कृपया अलग जानकारी दर्ज करें।',
// Foreign key errors
'/Cannot add or update a child row/i' => 'कृपया सभी जानकारी सही तरीके से भरें।',
// General SQL errors
'/SQLSTATE\[.*\]/i' => 'कृपया सभी आवश्यक फ़ील्ड सही तरीके से भरें।',
];
// Try to match patterns
foreach ($errorPatterns as $pattern => $replacement) {
if (preg_match($pattern, $errorMessage, $matches)) {
if (is_callable($replacement)) {
return $replacement($matches);
}
return $replacement;
}
}
// Default user-friendly message
return "आवेदन जमा करने में समस्या आई। कृपया सभी फ़ील्ड सही तरीके से भरें और पुनः प्रयास करें। यदि समस्या बनी रहे, तो कृपया तकनीकी अधिकारी से संपर्क करें: 7772056856";
}
?>
Apply for Scholarship - Savitr Foundation Scholarship | Savitra Foundation Application
If you face any difficulty or problem while submitting the application form, you can contact our technical officer for free. For any kind of suggestion or information, call or WhatsApp on 7772056856 and share your query
Application submitted successfully! Please check the receipt popup for your Application ID.
Personal Details
Address Details
Institute Details
Document Verification
Bank Verification
Previous
Next
Submit Application