( ′∀`)σ≡σ☆))Д′)レ(゚∀゚;)ヘ=З=З=Зε≡(ノ´_ゝ`)ノ
<?php
// 1. Configuration (Replace 'YOUR_API_KEY' with your actual key)
$apiKey = "AIzaSyDzjpTQSqHho2hDFno2wH2ACh_mXzoERik";
$apiUrl = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image-preview:generateContent?key=" . $apiKey;
$model = "gemini-2.5-flash-image-preview";
// 2. Set headers for JSON response
header('Content-Type: application/json');
// 3. Get the user prompt from the POST request (sent by AJAX)
$input_data = file_get_contents('php://input');
$data = json_decode($input_data, true);
$prompt = $data['prompt'] ?? null;
// Simple validation
if (empty($prompt)) {
echo json_encode(['error' => 'Prompt is required.']);
exit;
}
// 4. Construct the API Payload
$payload = [
'contents' => [
['parts' => [['text' => $prompt]]]
],
'generationConfig' => [
'responseModalities' => ['TEXT', 'IMAGE']
]
];
// 5. Initialize cURL for the API Request
$ch = curl_init($apiUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
]);
// 6. Execute and close cURL
$api_response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// 7. Process the API Response
$result = json_decode($api_response, true);
// Check for API errors
if ($http_code !== 200) {
echo json_encode([
'error' => 'API Call Failed',
'details' => $api_response
]);
exit;
}
// Extract the base64 image data
$base64Data = $result['candidates'][0]['content']['parts'][0]['inlineData']['data'] ?? null;
// Check if data was found
if (empty($base64Data)) {
echo json_encode(['error' => 'Could not find image data in response.']);
exit;
}
// 8. Send the base64 data back to the client
echo json_encode([
'success' => true,
'base64Image' => $base64Data
]);
?>