public function savepagedata() { // Get JSON POST data $json =…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
public function save_page_data() { // Get JSON POST data data = json_decode($json, true);
some pages failed to save when this error comes
When you're encountering the message "some pages failed to save", it means that during the execution of your save_page_data() function, one or more file writes failed, but not all. The response status becomes 'partial', indicating a partial success.
This is the most common cause.
FCPATH . 'uploads/apps/' . $this->active_app->id
uploads/apps/ directory and its subdirectories are writable by the web server.chmod -R 755 uploads/apps/
chown -R www-data:www-data uploads/apps/ # or your web server user
You're using mkdir($dir, 0777, true); to create the app directory. But 0777 doesn't always work as expected due to umask settings on the server.
mkdir(), check if it was successful:
if (!file_exists($dir) && !mkdir($dir, 0777, true)) {
throw new Exception("Failed to create directory: $dir");
}
Your code checks if 'page_name' exists, but if missing, it logs an error and continues.
page_name values.if (empty($page['page_name'])) {
$response['details'][] = [
'page_name' => 'unknown',
'status' => 'error',
'message' => 'Missing or empty page name'
];
continue;
}
access_token null
app_slug "gourmetgri"
config \n \n const $ = (selector) => document.querySelector(selector);\n const $all = (selector) => Array.from(document.querySelectorAll(selector));\n\n function showToast(type, text) {\n let gradient =\n type === "success"\n ? "linear-gradient(to right, #00b09b, #96c93d)"\n : type === "error"\n ? "linear-gradient(to right, #ff0000, #… console.warn('Could not override window.open:', error);\n }\n \n // Since we can't override location.assign/replace, we'll monitor for navigation\n }\n\n // Initialize URL modification when page loads\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', setupRuntimeUrlModification);\n } else {\n setupRuntimeUrlModification();\n }\n
configFile const $ = (selector) => document.querySelector(selector);\n const $all = (selector) => Array.from(document.querySelectorAll(selector));\n\n function showToast(type, text) {\n let gradient =\n type === "success"\n ? "linear-gradient(to right, #00b09b, #96c93d)"\n : type === "error"\n ? "linear-gradient(to right, #ff0000, #ff5f6d)"\n …r) {\n console.warn('Could not override window.open:', error);\n }\n \n // Since we can't override location.assign/replace, we'll monitor for navigation\n }\n\n // Initialize URL modification when page loads\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', setupRuntimeUrlModification);\n } else {\n setupRuntimeUrlModification();\n }
css '\n .cursor-pointer {\n cursor: pointer;\n }\n\n .toast-close {\n color: #fff !important;\n margin-left: 5px;\n opacity: 0.7;\n }\n\n body {\n font-family: "Roboto", sans-serif;\n min-width: 360px;\n max-width: 480px;\n margin: 0 auto;\n box-sizing: border-box;\n background-color: aliceblue;\n }\n\n .logou…translateX(-50%);\n }\n }\n\n @media (max-width: 576px) {\n .signup-container,\n .login-container {\n margin: auto;\n border-radius: 8px;\n box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);\n }\n \n .otp-input {\n width: 50px !important;\n height: 50px;\n font-size: 20px !important;\n }\n }\n '
globalCss '\n .cursor-pointer {\n cursor: pointer;\n }\n\n .toast-close {\n color: #fff !important;\n margin-left: 5px;\n opacity: 0.7;\n }\n\n body {\n font-family: "Roboto", sans-serif;\n min-width: 360px;\n max-width: 480px;\n margin: 0 auto;\n box-sizing: border-box;\n background-color: aliceblue;\n }\n\n .logou…translateX(-50%);\n }\n }\n\n @media (max-width: 576px) {\n .signup-container,\n .login-container {\n margin: auto;\n border-radius: 8px;\n box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);\n }\n \n .otp-input {\n width: 50px !important;\n height: 50px;\n font-size: 20px !important;\n }\n }\n '
pageData (10)[…]
projectData {…}
why this reqest data failed the requet
Thanks for sharing the request data. Based on the structure and content you've provided, let's analyze why the request might be failing or showing "some pages failed to save".
Here's a summary of what we see in the request:
| Field | Description |
|---|---|
access_token | null – not used or missing |
app_slug | "gourmetgri" |
configFile | JavaScript config code |
globalCss | CSS content |
pageData | Array of 10 pages, each with page_name and page_html |
projectData | JSON object containing app/page structure |
Your function starts with this check:
if (!isset($data['app_slug']) || !isset($data['pageData']) ||
!isset($data['configFile']) || !isset($data['globalCss'])) {
echo json_encode(['status' => 'error', ...]);
return;
}
Since you're getting a "partial" response, it means:
page_name in pageDataYou loop through $data['pageData'] and check:
if (!isset($page['page_name'])) {
$response['details'][] = ['page_name' => 'unknown', 'status' => 'error', ...];
continue;
}
pageData has a valid field. // Set response headers
header('Content-Type: application/json');
// Validate input data - now including new required fields
if (
!isset($data['app_slug']) ||
!isset($data['pageData']) ||
!isset($data['configFile']) ||
!isset($data['globalCss'])
) {
echo json_encode([
'status' => 'error',
'message' => 'Invalid input data format. Missing required fields.'
]);
return;
}
$app_slug = $data['app_slug'];
$response = [
'status' => 'success',
'message' => 'Pages saved successfully',
'app_slug' => $app_slug,
'details' => []
];
// Create app directory if it doesn't exist
$dir = FCPATH . 'uploads/apps/' . $this->active_app->id;
if (!file_exists($dir)) {
mkdir($dir, 0777, true);
}
// Save config.js
$config_path = $dir . '/config.js';
try {
if (file_put_contents($config_path, $data['configFile']) !== false) {
$response['details'][] = [
'file' => 'config.js',
'status' => 'success',
'message' => 'Config file saved'
];
} else {
throw new Exception('Failed to write config file');
}
} catch (Exception $e) {
$response['details'][] = [
'file' => 'config.js',
'status' => 'error',
'message' => $e->getMessage()
];
}
// Save global.css
$css_path = $dir . '/global.css';
try {
if (file_put_contents($css_path, $data['globalCss']) !== false) {
$response['details'][] = [
'file' => 'global.css',
'status' => 'success',
'message' => 'Global CSS saved'
];
} else {
throw new Exception('Failed to write CSS file');
}
} catch (Exception $e) {
$response['details'][] = [
'file' => 'global.css',
'status' => 'error',
'message' => $e->getMessage()
];
}
// Process each page
$project_data = [];
foreach ($data['pageData'] as $key => $page) {
if (!isset($page['page_name'])) {
$response['details'][] = [
'page_name' => 'unknown',
'status' => 'error',
'message' => 'Missing page name'
];
continue;
}
$project_data[$key]['page_name'] = $page['page_name'];
// Save HTML file
if (isset($page['page_html'])) {
$html_filepath = $dir . '/' . $page['page_name'] . '.php';
try {
if (file_put_contents($html_filepath, $page['page_html']) !== false) {
$project_data[$key]['page_html'] = $html_filepath;
$response['details'][] = [
'page_name' => $page['page_name'],
'status' => 'success',
];
} else {
throw new Exception('Failed to write HTML file');
}
} catch (Exception $e) {
$response['details'][] = [
'page_name' => $page['page_name'],
'status' => 'error',
'message' => $e->getMessage()
];
}
}
}
// Save the root-level projectData as a single file
$project_data_filepath = null;
if (isset($data['projectData'])) {
$project_data_filepath = $dir . '/project_data.json';
try {
if (file_put_contents($project_data_filepath, json_encode($data['projectData'], JSON_PRETTY_PRINT)) !== false) {
$response['project_data_file'] = 'uploads/apps/' . $this->active_app->id . '/project_data.json';
} else {
throw new Exception('Failed to write project data file');
}
} catch (Exception $e) {
$response['status'] = 'error';
$response['message'] = 'Project data save failed: ' . $e->getMessage();
}
}
// Check for any errors in the entire process
$hasErrors = false;
foreach ($response['details'] as $detail) {
if ($detail['status'] === 'error') {
$hasErrors = true;
break;
}
}
if ($hasErrors) {
$response['status'] = 'partial';
$response['message'] = 'Some files failed to save';
}
// Save homepage to database (default to 'home' if not specified)
$this->db->set('site_url', base_url() . 'uploads/apps/' . $this->active_app->id . '/index.php');
$this->db->set('project_data_file', $project_data_filepath ? 'uploads/apps/' . $this->active_app->id . '/project_data.json' : null);
$this->db->set('project_data', json_encode($project_data));
$this->db->where('ids', $this->active_app->ids);
if (!$this->db->update('apps')) {
$response['status'] = 'error';
$response['message'] = 'Database update failed: ' . $this->db->error()['message'];
}
echo json_encode($response);
}
If the JSON data is too large, PHP may fail to parse it (json_decode() returns null), which will cause missing fields.
Check if $data is valid:
if (json_last_error() !== JSON_ERROR_NONE) {
echo json_encode([
'status' => 'error',
'message' => 'Invalid JSON input: ' . json_last_error_msg()
]);
return;
}
Also, increase PHP limits in php.ini:
post_max_size = 32M
upload_max_filesize = 32M
memory_limit = 128M
Even if all files are saved, if the final database update fails, the whole process is considered partially failed.
if (!$this->db->update('apps')) {
$error = $this->db->error();
$response['status'] = 'error';
$response['message'] = 'Database update failed: ' . $error['message'];
// Optionally log to file or error log
error_log("DB Error: " . $error['message']);
}
projectDataYou're saving project_data.json only if projectData is present in the input.
if (!isset($data['projectData'])) {
$response['details'][] = [
'file' => 'project_data.json',
'status' => 'error',
'message' => 'Missing project data'
];
}
Add logging to help track which files are failing and why.
Use error_log() or your framework's logging system:
log_message('error', 'Failed to write file: ' . $html_filepath);
Here’s a reusable helper to improve file writing:
function safe_file_put_contents($path, $content) {
if (file_put_contents($path, $content) === false) {
throw new Exception("Failed to write file: " . $path);
}
return true;
}
Then wrap your writes:
try {
safe_file_put_contents($html_filepath, $page['page_html']);
// success
} catch (Exception $e) {
// log and respond with error
}
| Potential Issue | Solution |
|---|---|
Permissions on uploads/apps/ | chmod / chown |
mkdir() failed | Check return value |
Missing page_name | Validate input |
| Large JSON payload | Increase PHP limits |
| Database error | Log error message |
Missing projectData | Validate before writing |
| No error logging | Add error_log() or log_message() |
If you'd like, you can share the exact error message from the frontend or logs, and I can help pinpoint the issue even faster.
page_namepage_name is empty, null, or not a string, this will trigger an error.✅ Fix: Add extra validation:
if (empty($page['page_name']) || !is_string($page['page_name'])) {
$response['details'][] = [
'page_name' => 'unknown',
'status' => 'error',
'message' => 'Invalid or empty page name'
];
continue;
}
You attempt to write HTML files like:
$html_filepath = $dir . '/' . $page['page_name'] . '.php';
file_put_contents($html_filepath, $page['page_html']);
page_name values invalid or contain special characters like /, \, :, etc.?✅ Fix:
Sanitize the page_name:
$page_name = preg_replace('/[^a-zA-Z0-9_-]/', '', $page['page_name']);
if (!$page_name) {
$response['details'][] = [
'page_name' => $page['page_name'],
'status' => 'error',
'message' => 'Invalid characters in page name'
];
continue;
}
Also, check for errors:
if (file_put_contents($html_filepath, $page['page_html']) === false) {
$response['details'][] = [
'page_name' => $page['page_name'],
'status' => 'error',
'message' => 'Failed to write HTML file'
];
}
You do:
$dir = FCPATH . 'uploads/apps/' . $this->active_app->id;
if (!file_exists($dir)) {
mkdir($dir, 0777, true);
}
But mkdir($dir, 0777) may not work due to:
umask restrictions✅ Fix:
Check if mkdir succeeded:
if (!file_exists($dir) && !@mkdir($dir, 0777, true)) {
$response['status'] = 'error';
$response['message'] = "Failed to create app directory: $dir";
echo json_encode($response);
return;
}
projectData Might Be Too LargeYou're saving projectData as a JSON file:
file_put_contents($project_data_filepath, json_encode($data['projectData'], JSON_PRETTY_PRINT))
projectData is too large, json_encode() may fail.file_put_contents() may fail if the disk is full or the path is invalid.✅ Fix: Check for JSON errors:
$json = json_encode($data['projectData'], JSON_PRETTY_PRINT);
if ($json === false) {
$response['details'][] = [
'file' => 'project_data.json',
'status' => 'error',
'message' => 'JSON encode failed: ' . json_last_error_msg()
];
}
At the end, you do:
$this->db->set('project_data', json_encode($project_data));
$this->db->where('ids', $this->active_app->ids);
if (!$this->db->update('apps')) {
$response['status'] = 'error';
$response['message'] = 'Database update failed: ' . $this->db->error()['message'];
}
If the project_data is too big or malformed, this may fail.
✅ Fix:
Ensure the column project_data in your database is of type TEXT or LONGTEXT (not VARCHAR(255)).
access_token (Optional)You have a field access_token: null.
If your system requires authentication and doesn't allow anonymous access, this could be part of the issue.
✅ Fix: Check if there's middleware or authentication logic that blocks unauthenticated requests.
| Issue | Fix |
|---|---|
Invalid or missing page_name | Add empty() and is_string() checks |
| File write fails | Sanitize filenames and check return value |
| Directory not created | Add error check for mkdir() |
Large or invalid projectData | Check json_encode() errors |
| Database failure | Ensure project_data is TEXT/LONGTEXT type |
| Auth issue | Ensure access_token is not required or is valid |
You can simulate this request using Postman or curl:
curl -X POST http://yourdomain.com/your-controller/save_page_data \
-H "Content-Type: application/json" \
-d '{
"app_slug": "gourmetgri",
"configFile": "const $ =...",
"globalCss": ".cursor-pointer { ... }",
"pageData": [
{ "page_name": "index", "page_html": "<html>...</html>" },
...
],
"projectData": { "pages": [...] }
}'
json_last_error() and file_exists() checks.If you can share:
$response['details'] array,I can help you pinpoint the exact failing file/page.