ohno Posted March 30, 2023 Share Posted March 30, 2023 I have this code : - <?php $site_root = 'https://'.$_SERVER['SERVER_NAME']; // check maximum upload size $max_upload = (int)(ini_get('upload_max_filesize')); $max_post = (int)(ini_get('post_max_size')); $max_size = min($max_upload, $max_post); $max_size_bytes = $max_size * 1024 * 1024; // server size in bytes // display maximum upload size echo "<center><b>Maximum Upload File Size: $max_size MB</b></center>"; echo "<center><b>Maximum Post Size: $max_post MB</b></center>"; echo "<center><b>Maximum Size Bytes: $max_size_bytes</b></center>"; $style = '<style> .button { background-color: #00A5FF; border-radius: 4px; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; } </style> <title>ERROR DETECTED!</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> '; // error checking if (isset($_FILES["file"])) { $fileName = $_FILES["file"]["tmp_name"]; $fileType = $_FILES["file"]["type"]; $allowedTypes = array('text/csv', 'application/vnd.ms-excel'); if ($_FILES["file"]["error"] !== UPLOAD_ERR_OK) { echo "<center><img src='".$site_root."/images/cartwarningred.png' alt='Error!' /> <b>File upload failed with error: "; echo $style; switch ($_FILES["file"]["error"]) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: echo "The uploaded file exceeds the maximum file size. Maximum file size allowed is $max_size MB"; echo "<a href='javascript:window.history.back();'><button class='button'>BACK!</button></a>"; echo $style; break; case UPLOAD_ERR_PARTIAL: echo "The uploaded file was only partially uploaded."; echo "<a href='javascript:window.history.back();'><button class='button'>BACK!</button></a>"; echo $style; break; case UPLOAD_ERR_NO_FILE: echo "No file selected, no file was uploaded."; echo "<center><a href='javascript:window.history.back();'><button class='button'>BACK!</button></a></center>"; echo $style; break; case UPLOAD_ERR_NO_TMP_DIR: echo "Missing a temporary folder."; echo "<center><a href='javascript:window.history.back();'><button class='button'>BACK!</button></a></center>"; echo $style; break; case UPLOAD_ERR_CANT_WRITE: echo "Failed to write file to disk."; echo "<center><a href='javascript:window.history.back();'><button class='button'>BACK!</button></a></center>"; echo $style; break; case UPLOAD_ERR_EXTENSION: echo "File upload stopped by extension."; echo "<center><a href='javascript:window.history.back();'><button class='button'>BACK!</button></a></center>"; echo $style; break; default: echo "Unknown upload error."; echo "<center><a href='javascript:window.history.back();'><button class='button'>BACK!</button></a></center>"; echo $style; break; } echo "</b></center>"; exit; } else if (!in_array($fileType, $allowedTypes)) { echo "<center><img src='".$site_root."/images/cartwarningred.png' alt='Error!' /> <b>File upload failed with error: Only CSV files are allowed</b></center>"; echo "<center><a href='javascript:window.history.back();'><button class='button'>BACK!</button></a></center>"; echo $style; exit; } else { $file = fopen($fileName, "r"); } } class ImportController { // getting connection in constructor function __construct($conn) { $this->conn = $conn; } // function for reading csv file public function index() { $fileName = ""; // if there is any file if(isset($_FILES['file'])) { // reading tmp_file name $fileName = $_FILES["file"]["tmp_name"]; } $counter = 0; // if file size is not empty if (isset($_FILES["file"]) && $_FILES["file"]["size"] > 0) { $file = fopen($fileName, "r"); // eliminating the first row of CSV file fgetcsv($file); ?> <table class="table"> <thead> <th> IP From </th> <th> IP To </th> <th> Country Code </th> <th> Country Name </th> <th> Response </th> </thead> <?php // prepare the statement $stmt = $this->conn->prepare("REPLACE INTO ip2location (ip_from, ip_to, country_code, country_name) VALUES (?, ?, ?, ?)"); while (($column = fgetcsv($file, 10000, ",")) !== FALSE) { $counter++; // assigning csv column to a variable $ip_from = $column[0]; $ip_to = $column[1]; $country_code = $column[2]; $country_name = $column[3]; // bind the values to the statement parameters and execute $stmt->bind_param("ssss", $ip_from, $ip_to, $country_code, $country_name); $result = $stmt->execute(); if($result == 1): ?> <tr> <td> <?php echo $ip_from; ?> </td> <td> <?php echo $ip_to; ?> </td> <td> <?php echo $country_code; ?> </td> <td> <?php echo $country_name; ?> </td> <td> <?php echo "<label class='text-success'>Success </label> " .date('d-m-Y H:i:s');?> </td> </tr> <?php endif; } $stmt->close(); // close the statement ?> </table> <?php } } } ?> During testing if post_max_size is too small but upload_max_filesize is not it tries to upload but fails, I get no error. If post_max_size is OK but upload_max_filesize is not it tries to upload & correctly displays the error "The uploaded file exceeds the maximum file size." How can I get it to display an error if the post_max_size setting on the server is too small? Quote Link to comment https://forums.phpfreaks.com/topic/316067-post_max_size-error-checking/ Share on other sites More sharing options...
requinix Posted March 30, 2023 Share Posted March 30, 2023 post_max_size is not part of the file upload system, so if the request is too large then $_FILES will not tell you - because the upload wasn't tried. You should be able to detect if the request was too large by looking at the Content-Length request header. If there is one, since it's possible the request won't use that. Without, you may be able to filesize the request body, which is accessible at php://input. Maybe. Otherwise the solution is simple: make sure post_max_size is always greater than upload_max_filesize. That way you'll always get an error if it's too large. Quote Link to comment https://forums.phpfreaks.com/topic/316067-post_max_size-error-checking/#findComment-1606956 Share on other sites More sharing options...
mac_gyver Posted March 30, 2023 Share Posted March 30, 2023 assuming that uploads are enabled on the server (which you can test using code) and you have a valid post method form, with at least one type='file' field, if the $_SERVER['REQUEST_METHOD'] === 'POST' and both the $_POST and $_FILES arrays are empty, it is likely that the post_max_size was exceeded. you can use this as the condition to setup and display a message that the total size of the post data was too large. the Content-Length is available in $_SERVER['CONTENT_LENGTH'] (which is in bytes.) if it is set, this is the value that the web server compares with the post_max_size value to attempt to abort requests that are too large. both the upload_max_filesize and post_max_size can be either in bytes or K/k, M/m, or G/g abbreviations, therefore you must convert these to the same units in order to compare them. your post method form processing should - detect if a post method from was submitted detect if there is $_POST/$_FILES data. test the $_FILES[...]['error'] element validate the uploaded file information i recommend that you use an array to hold user/validation errors. after the end of all the validation logic, if the array is empty, there were no errors and you can use the submitted form data. the ['type'] element comes from the request, can be set to anything, and cannot be trusted. you should determine the mime type on the server. based on the use of the back-button history for navigation, your form and form processing code are on different pages. these should be on the same page in order to simplify the code, make it easier to secure the code, and provide a better user experience. Quote Link to comment https://forums.phpfreaks.com/topic/316067-post_max_size-error-checking/#findComment-1606957 Share on other sites More sharing options...
ohno Posted March 31, 2023 Author Share Posted March 31, 2023 I think I'll need to merge the two files to get this to work but not sure how? Current form page (I tried adding the error checking here, it didn't work) : - <?php ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); $site_root = 'https://'.$_SERVER['SERVER_NAME']; // including db config file include_once("../db-config.php"); // including import controller file include_once("../import-controller.php"); // creating object of DBController class $db = new DBController(); // calling connect() function using object $conn = $db->connect(); // creating object of import controller and passing connection object as a parameter $importCtrl = new ImportController($conn); ?> <!DOCTYPE html> <html> <head> <style> .button { background-color: #00A5FF; border-radius: 4px; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; } </style> <title>Import IP Location Database CSV</title> </head> <body> <p style="text-align:center">Upload New Cart IP Geo Tracking Database Here. This Will Import IP Info In CSV Format!</p> <div class="row"> <div class="col-md-10 offset-md-5"> <a href="https://lite.ip2location.com/ip2location-lite" target="_blank"><button class="button">Download New DB!</button></a> <a href="<?php echo $site_root; ?>/cartsystem/admin/orders.php"><button class="button">BACK!</button></a> </div> </div> <div class="container"> <?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { $file_size = $_FILES['file']['size']; $max_size = 1024 * 1024; // 1 MB if ($file_size > $max_size) { echo '<div class="alert alert-danger">The uploaded file is too large (max size: 1MB).</div>'; } else { $importResult = $importCtrl->index(); } } ?> <form method="post" enctype="multipart/form-data"> <div class="row mt-5"> <div class="col-md-6 m-auto border shadow"> <label> Import Data - CAUTION! This Affects LIVE Site!</label> <div class="form-group"> <input type="file" name="file" class="form-control"> </div> <div class="form-group"> <button type="submit" name="import" class="btn btn-success"> Import Data </button> </div> </div> </div> <div class="row mt-4"> <div class="col-md-10 m-auto"> <?php if (isset($importResult)) { echo $importResult; } ?> </div> </div> </form> </div> </body> </html> and the current import-controller file (again, with added error checking, again, it didn't work) <?php ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); $site_root = 'https://'.$_SERVER['SERVER_NAME']; // check maximum upload size $max_upload = (int)(ini_get('upload_max_filesize')); $max_post = (int)(ini_get('post_max_size')); $max_size = min($max_upload, $max_post); $max_size_bytes = $max_size * 1024 * 1024; // server size in bytes if ($_SERVER['REQUEST_METHOD'] === 'POST' && empty($_POST) && empty($_FILES)) { // Post data exceeds the maximum post size limit echo "<center><img src='".$site_root."/images/cartwarningred.png' alt='Error!' /> <b>Post data exceeds the maximum post size limit of $max_post MB. Please contact your server administrator to increase the limit.</b></center>"; echo "<center><a href='javascript:window.history.back();'><button class='button'>BACK!</button></a></center>"; echo $style; exit; } // display maximum upload size echo "<center><b>Maximum Upload File Size: $max_upload MB</b></center>"; echo "<center><b>Maximum Post Size: $max_post MB</b></center>"; echo "<center><b>Maximum Size Bytes: $max_size_bytes</b></center>"; $style = '<style> .button { background-color: #00A5FF; border-radius: 4px; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; } </style> <title>ERROR DETECTED!</title> '; if (isset($_FILES["file"])) { $fileName = $_FILES["file"]["tmp_name"]; $fileType = $_FILES["file"]["type"]; $allowedTypes = array('text/csv', 'application/vnd.ms-excel'); if ($_FILES["file"]["error"] !== UPLOAD_ERR_OK) { $error_message = ''; switch ($_FILES["file"]["error"]) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: $error_message = "The uploaded file exceeds the maximum file size. Maximum file size allowed is $max_size MB"; break; case UPLOAD_ERR_PARTIAL: $error_message = "The uploaded file was only partially uploaded."; break; case UPLOAD_ERR_NO_FILE: $error_message = "No file selected, no file was uploaded."; break; case UPLOAD_ERR_NO_TMP_DIR: $error_message = "Missing a temporary folder."; break; case UPLOAD_ERR_CANT_WRITE: $error_message = "Failed to write file to disk."; break; case UPLOAD_ERR_EXTENSION: $error_message = "File upload stopped by extension."; break; default: $error_message = "Unknown upload error."; break; } echo "<center><img src='".$site_root."/images/cartwarningred.png' alt='Error!' /> <b>File upload failed with error: ".$error_message."</b></center>"; echo "<center><a href='javascript:window.history.back();'><button class='button'>BACK!</button></a></center>"; echo $style; exit; } else if (!in_array($fileType, $allowedTypes)) { echo "<center><img src='".$site_root."/images/cartwarningred.png' alt='Error!' /> <b>File upload failed with error: Only CSV files are allowed</b></center>"; echo "<center><a href='javascript:window.history.back();'><button class='button'>BACK!</button></a></center>"; echo $style; exit; } else if ($_FILES["file"]["size"] > $max_size * 1024 * 1024) { echo "<center><img src='".$site_root."/images/cartwarningred.png' alt='Error!' /> <b>File upload failed with error: The uploaded file exceeds the maximum file size. Maximum file size allowed is $max_size MB</b></center>"; echo "<center><a href='javascript:window.history.back();'><button class='button'>BACK!</button></a></center>"; echo $style; exit; } else { $file = fopen($fileName, "r"); } } class ImportController { private $conn; // getting connection in constructor function __construct($conn) { $this->conn = $conn; } // function for reading csv file public function index() { $fileName = ""; // if there is any file if(isset($_FILES['file'])) { // reading tmp_file name $fileName = $_FILES["file"]["tmp_name"]; } $counter = 0; // if file size is not empty if (isset($_FILES["file"]) && $_FILES["file"]["size"] > 0) { $file = fopen($fileName, "r"); // eliminating the first row of CSV file fgetcsv($file); ?> <table class="table"> <thead> <th> IP From </th> <th> IP To </th> <th> Country Code </th> <th> Country Name </th> <th> Response </th> </thead> <?php // prepare the statement $stmt = $this->conn->prepare("REPLACE INTO ip2location (ip_from, ip_to, country_code, country_name) VALUES (?, ?, ?, ?)"); while (($column = fgetcsv($file, 10000, ",")) !== FALSE) { $counter++; // assigning csv column to a variable $ip_from = $column[0]; $ip_to = $column[1]; $country_code = $column[2]; $country_name = $column[3]; // bind the values to the statement parameters and execute $stmt->bind_param("ssss", $ip_from, $ip_to, $country_code, $country_name); $result = $stmt->execute(); if($result == 1): ?> <tr> <td> <?php echo $ip_from; ?> </td> <td> <?php echo $ip_to; ?> </td> <td> <?php echo $country_code; ?> </td> <td> <?php echo $country_name; ?> </td> <td> <?php echo "<label class='text-success'>Success </label> " .date('d-m-Y H:i:s');?> </td> </tr> <?php endif; } $stmt->close(); // close the statement ?> </table> <?php } } } ?> If anyone has the time to take a look and post what code is required it would be much appreciated! Quote Link to comment https://forums.phpfreaks.com/topic/316067-post_max_size-error-checking/#findComment-1606962 Share on other sites More sharing options...
ohno Posted March 31, 2023 Author Share Posted March 31, 2023 This works with all error scenarios..but doesn't actually update the database when the correct file is selected! <?php ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); $site_root = 'https://'.$_SERVER['SERVER_NAME']; // check maximum upload size $max_upload = (int)(ini_get('upload_max_filesize')); $max_post = (int)(ini_get('post_max_size')); $max_size = min($max_upload, $max_post); $max_size_bytes = $max_size * 1024 * 1024; // server size in bytes $style = ' <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> <style> .button { background-color: #00A5FF; border-radius: 4px; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; } </style> <title>ERROR DETECTED!</title> '; $postMaxSize = trim(ini_get('post_max_size')); if (strlen($postMaxSize)>0) { $postMaxSizeValue = substr($postMaxSize, 0, -1); $postMaxSizeUnit = strtolower(substr($postMaxSize, -1)); $postMaxSize = 0; if (false !== filter_var($postMaxSizeValue, FILTER_VALIDATE_INT, array('options' => array( 'min_range' => 0)))) { switch ($postMaxSizeUnit) { case 'g': $postMaxSizeValue*=1024; case 'm': $postMaxSizeValue*=1024; case 'k': $postMaxSizeValue*=1024; break; default: if ($postMaxSizeUnit>='0' && $postMaxSizeUnit<='9') { $postMaxSizeValue = (int) $postMaxSizeValue.$postMaxSizeUnit; } else { $postMaxSizeValue = 0; } } $postMaxSize = $postMaxSizeValue; } } else { $postMaxSize = 0; } if (empty($_FILES) && empty($_POST) && isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == 'POST' && isset($_SERVER['CONTENT_LENGTH']) && $_SERVER['CONTENT_LENGTH'] > $postMaxSize) { echo "<center><img src='".$site_root."/images/cartwarningred.png' alt='Error!' /> <b>The uploaded file exceeds the maximum post file size. Maximum post file size allowed is ".$max_post." MB (".$postMaxSize." bytes)<br><br />Increase 'post_max_size' setting on the server!</b></center>"; echo "<center><a href='javascript:window.history.back();'><button class='button'>BACK!</button></a></center>"; echo $style; exit(1); } // display maximum upload size echo "<center><b>Maximum Upload File Size: $max_upload MB</b></center>"; echo "<center><b>Maximum Post Size: $max_post MB</b></center>"; echo "<center><b>Maximum Size Bytes: $max_size_bytes</b></center>"; if (isset($_FILES["file"])) { $fileName = $_FILES["file"]["tmp_name"]; $fileType = $_FILES["file"]["type"]; $allowedTypes = array('text/csv', 'application/vnd.ms-excel'); if ($_FILES["file"]["error"] !== UPLOAD_ERR_OK) { $error_message = ''; switch ($_FILES["file"]["error"]) { case UPLOAD_ERR_INI_SIZE: case UPLOAD_ERR_FORM_SIZE: $error_message = "The uploaded file exceeds the maximum file size. Maximum file size allowed is $max_size MB<br />Increase 'upload_max_filesize' setting on the server!"; break; case UPLOAD_ERR_PARTIAL: $error_message = "The uploaded file was only partially uploaded."; break; case UPLOAD_ERR_NO_FILE: $error_message = "No file selected, no file was uploaded."; break; case UPLOAD_ERR_NO_TMP_DIR: $error_message = "Missing a temporary folder."; break; case UPLOAD_ERR_CANT_WRITE: $error_message = "Failed to write file to disk."; break; case UPLOAD_ERR_EXTENSION: $error_message = "File upload stopped by extension."; break; default: $error_message = "Unknown upload error."; break; } echo "<center><img src='".$site_root."/images/cartwarningred.png' alt='Error!' /> <b>File upload failed with nnerror: ".$error_message."</b></center>"; echo "<center><a href='javascript:window.history.back();'><button class='button'>BACK!</button></a></center>"; echo $style; exit; } else if (!in_array($fileType, $allowedTypes)) { echo "<center><img src='".$site_root."/images/cartwarningred.png' alt='Error!' /> <b>File upload failed with error: Only CSV files are allowed</b></center>"; echo "<center><a href='javascript:window.history.back();'><button class='button'>BACK!</button></a></center>"; echo $style; exit; } else { $file = fopen($fileName, "r"); } } class ImportController { private $conn; // getting connection in constructor function __construct($conn) { $this->conn = $conn; } // function for reading csv file public function index() { $fileName = ""; // if there is any file if(isset($_FILES['file'])) { // reading tmp_file name $fileName = $_FILES["file"]["tmp_name"]; } $counter = 0; // if file size is not empty if (isset($_FILES["file"]) && $_FILES["file"]["size"] > 0) { $file = fopen($fileName, "r"); // eliminating the first row of CSV file fgetcsv($file); ?> <table class="table"> <thead> <th> IP From </th> <th> IP To </th> <th> Country Code </th> <th> Country Name </th> <th> Response </th> </thead> <?php // prepare the statement $stmt = $this->conn->prepare("REPLACE INTO ip2location (ip_from, ip_to, country_code, country_name) VALUES (?, ?, ?, ?)"); while (($column = fgetcsv($file, 10000, ",")) !== FALSE) { $counter++; // assigning csv column to a variable $ip_from = $column[0]; $ip_to = $column[1]; $country_code = $column[2]; $country_name = $column[3]; // bind the values to the statement parameters and execute $stmt->bind_param("ssss", $ip_from, $ip_to, $country_code, $country_name); $result = $stmt->execute(); if($result == 1): ?> <tr> <td> <?php echo $ip_from; ?> </td> <td> <?php echo $ip_to; ?> </td> <td> <?php echo $country_code; ?> </td> <td> <?php echo $country_name; ?> </td> <td> <?php echo "<label class='text-success'>Success </label> " .date('d-m-Y H:i:s');?> </td> </tr> <?php endif; } $stmt->close(); // close the statement ?> </table> <?php } } } ?> <!DOCTYPE html> <html> <head> <style> .button { background-color: #00A5FF; border-radius: 4px; border: none; color: white; padding: 15px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer; } </style> <title>Import IP Location Database CSV</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"> </head> <body> <p style="text-align:center">Upload New Cart IP Geo Tracking Database Here. This Will Import IP Info In CSV Format!</p> <div class="row"> <div class="col-md-10 offset-md-5"> <a href="https://lite.ip2location.com/ip2location-lite" target="_blank"><button class="button">Download New DB!</button></a> <a href="<?php echo $site_root; ?>/cartsystem/admin/orders.php"><button class="button">BACK!</button></a> </div> </div> <div class="container"> <form method="post" enctype="multipart/form-data"> <div class="row mt-5"> <div class="col-md-6 m-auto border shadow"> <label> Import Data - CAUTION! This Affects LIVE Site!</label> <div class="form-group"> <input type="file" name="file" class="form-control"> </div> <div class="form-group"> <button type="submit" name="import" class="btn btn-success"> Import Data </button> </div> </div> </div> <div class="row mt-4"> <div class="col-md-10 m-auto"> <?php if (isset($importResult)) { echo $importResult; } ?> </div> </div> </form> </div> </body> </html> Quote Link to comment https://forums.phpfreaks.com/topic/316067-post_max_size-error-checking/#findComment-1606964 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.