Posts

Showing posts from October, 2023

PHP Data Caching

Sometimes it becomes necessary to limit the number of queries to an external data source. Especially if they do not change constantly. For example, the exchange rate in the central bank. Or simply speed up the page loading, giving the script an already generated file. $expires = 3600; //Cache lifetime in seconds $curTime = time(); $cacheFile = 'data.json'; function writeCache($cacheFile) { //get fresh data file_put_contents($cacheFile, file_get_contents('http://somesite.com/api')); } if (!file_exists($cacheFile)) { writeCache($cacheFile); } else { $fMtime = filemtime($cacheFile); if (($curTime - $fMtime) > $expires) { writeCache($cacheFile); } } This caching method is based on comparing the date of the file change with the cache with the current time.

Uploading files to the server

Consider uploading files to a PHP server using the POST method. This will require a form with the file field type and an enctype attribute with a multipart/form-data value. HTML <form method="POST" enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="2097152" /> <input type="file" name="uploaded_file"> <input type="submit" name="submit" value="send"> </form> The field with name="MAX_FILE_SIZE" must be placed above the input type="file" , the value is set in bytes. The field is optional and the check must be still on the server. After sending the data of the uploaded file get into the $_FILES array if(isset($_FILES["uploaded_file"])){ //field´s name type="file" $maxsize = 1024 * 1024* 2; //limited the allowed file size to 2 MB $errors = []; //valid file exten