Skip to main content

Posts

Showing posts with the label PHP

PHP script to upload file securely

How to Write a Secure PHP Script for File Uploads File uploads are a common feature in web applications, but they can introduce significant security risks if not handled properly. In this article, we'll walk through the steps to securely upload files to a server using PHP. We'll cover key security measures such as file validation, limiting file types, setting file size limits, and managing file storage. We will also create reusable functions to handle the upload process. 1. Create the HTML Form First, we need an HTML form that allows users to select and upload a file. Ensure that the form uses the POST method and includes the enctype="multipart/form-data" attribute. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Secure File Upload</title> </head> <body> <form action="upload.php" method="post" enctype="multipart/

Find the dates ( month start and end dates) between the given two dates using PHP

When you want to pull the dates between two dates, where the between dates are connecting dots. If you want to list the complete date ranges through months. For example, to find the dates between below dates date1 = '2022-12-29'; date2 = '2023-02-20'; expected output would be  Start Date End Date 2022-12-29 2022-12-31 2023-01-01 2023-01-31 2023-02-01 2023-02-20 <?php /* * Returns array of month's start & end dates between provided dates. * * @param string $start_date * @param string $end_date * * * @return array */ function getDates($start_date, $end_date){ $start_date_obj = new DateTime($start_date); $end_date_obj = new DateTime($end_date); $diff = $end_date_obj->diff($start_date_obj); $months = (($diff->y) * 12) + ($diff->m); $dates[] = array('start_date' => $start_date, 'end_date' => date('Y-m-t', strtotime($start_date)), 'suffix' =

PHP Code Review Guidelines

General  The code works  The code is easy to understand  Follows coding conventions  Names are simple and if possible short  Names are spelt correctly  Names contain units where applicable  There are no usages of magic numbers  No hard coded constants that could possibly change in the future  All variables are in the smallest scope possible  There is no commented out code  There is no dead code (inaccessible at Runtime)  No code that can be replaced with library functions  Variables are not accidentally used with null values  Variables are immutable where possible  Code is not repeated or duplicated  There is an else block for every if clause even if it is empty  No complex/long boolean expressions  No negatively named boolean variables  No empty blocks of code  Ideal data structures are used  Constructors do not accept null/none values  Catch clauses are fine grained and catch specific exceptions  Exceptions are not eaten if caught, unless explicitly documente

Week dates between two dates

To list week's start date & end date between given two dates. It also includes number of dates in every set. It allows you to list only those weeks having total seven days. Here the starting day of the week is Monday & the end day of the week is Sunday. /* * Returns array of week's start & end dates with number of days between those. * * @param string $start_date * @param string $end_date * @param boolean $only_full_week * * @return array */ function getWeekDates($start_date, $end_date, $only_full_week = false) { $stime = strtotime($start_date); $etime = strtotime($end_date); $weeks = array(); $i = 0; $j = 1; while ($stime <= $etime) { if ($i == 0 && $j == 1) { $weeks[$i]['start_date'] = date('Y-m-d', $stime); $weeks[$i]['end_date'] = date('Y-m-d', $stime); $weeks[$

Format Sentences, format number and remove extra spaces. All in one solution

We had a requirement, where we were asked to format the content from a big database table. And the format includes making sentences to sentence case, format simple numbers to comma separated numbers within those sentences and remove the extra spaces. Here is the solution. Hope this helps you. function formatString($string){ //number formatting $string1 = preg_replace_callback('/\d+/', function($match){return number_format($match[0]);}, $string); //removing extra spaces $string2 = preg_replace('/\s+/', ' ', $string1); //sentence case $sentences = preg_split('/([.?!]+)/', $string2, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE); $new_string = ''; foreach ($sentences as $key => $sentence) { $new_string .= ($key & 1) == 0? ucfirst(strtolower(trim($sentence))) : $sentence.' '; } return trim($new_string); } $str = "it was an awesome day. i bought shares f

Huge data Excel download using PHP

Ah! It was always a problem to download huge data in excel format. Tried the best library available 'PHPExcel' but the issue persists with memory limit and time taken to generate and download. But here is the promising solution found after spending ages searching on Google. You can find it here . The author himself says "Never run out of memory with PHPExcel again". You need to download it and include  xlsxwriter.class.php   where you want to fetch the data from DB and through it on to browser or save to a particular location. Let's get started. Below is the logic to generate the file and store in the current directory. If you want to store is at the desired location, specify the location for the method writeToFile. include_once("xlsxwriter.class.php"); $writer = new XLSXWriter(); $data = array( array('year','month','amount'), array('2003','1','220'), array('2003','2'

Generate documentation for PHP Code using phpDocumentor

What is phpDocumentor? phpDocumentor is the simple and best tool to generate API documentation for PHP source code.  Downloading & installing phpDocumentor: There are several dependencies to install phpDocumentor you can find them on official website i.e., here To install phpDocumentor using PEAR type below command In windows, run command prompt as administrator. Goto xampp/php folder and type pear channel-discover pear.phpdoc.org pear install phpdoc/phpDocumentor In linux, open terminal and type (if install xampp for linux then goto xampp/bin folder) pear channel-discover pear.phpdoc.org pear install phpdoc/phpDocumentor Generate API using phpDocumentor: In windows, goto  phpdoc.bat folder and run phpdoc  command for source directory to destination phpdoc -d <source directory of php code> -t <destination directory> In Linux, goto [phpdocumentor installation folder]/bin/ and run command phpdoc -d <source directory of php> -t <destinatio

Google like Pagination

In the beginning of my career, every technical interview has this question; "How do you write pagination script in PHP?". I think you too faced the same issue. It was very important to answer this because every application is developed to list set of information and off-course you can't show every thing in a single page. It will irritate the user to scroll to the bottom of page to read. So, the pagination. Divide the list of items in number of pages and navigate to each by clicking on each page number displayed. At the beginning, the pagination was simple was limited to 10-15 pages, but after some time in real time the requirement has grown to 10 multiple pages. Solution was to show first few page numbers, last few page numbers and in middle show the ellipsis(...). As you navigate to any page it would show definite page numbers to both the sides. /** * Pagination file * * This file provides the google like pagination solution * * @category Saral * @packag

Sorting second dimension array

We can sort the second dimension array like table, for example $users = array( array('name' => 'Mr. B', 'age' => 34), array('name' => 'Mr. A', 'age' => 33), array('name' => 'Mr. C', 'age' => 32) ); If you want to sort the array based on the name or age, here is the solution: function arraySortByColumn(&$arr, $col, $dir = SORT_ASC){ $sort_col = array(); foreach ($arr as $key => $row) { $sort_col[$key] = $row[$col]; } array_multisort($sort_col, $dir, $arr); } arraySortByColumn($users, 'name', SORT_DESC); print_r($users);

Find relative duration of an event using PHP for given date time (seconds ago, minutes ago, hours ago, days ago, weeks ago, months ago, years ago)

You might have seen that many of the live applications shows the time relative to when it was posted as seconds ago, minutes ago, hours ago, days ago, weeks ago, month ago, year ago and so on. Instead of showing the whole date and time of any possible action on the application it is shown with smaller units, more simpler ones like a minute ago, 15 minutes and 10 seconds ago etc. Here is how we achieve it using PHP, below are two methods that can be used, it requires a Date Time string in YYYY-MM-DD HH:II:SS format. Method One: /** * returns the time ago in string * @param string $date_time * * @return string */ function timeAgo($date_time) { $time_ago = strtotime($date_time); $cur_time = time(); $time_elapsed = $cur_time - $time_ago; $seconds = $time_elapsed; $minutes = round($time_elapsed / 60); $hours = round($time_elapsed / 3600); $days = round($time_elapsed / 86400); $weeks = r

Convert Date Time to GMT/UTC

If you want to convert any date time to GMT/UTC for given timezone (observing DST/not). /**      * coverts the given date time to GMT/UTC based on timezone provided      * @param string $date      * @param string $timezone      * @return string      */     function getGMT($date, $timezone){         date_default_timezone_set("UTC");         $daylight_savings_offset_in_seconds = timezone_offset_get( timezone_open( $timezone ), new DateTime() );         return $new_date = date('Y-m-d H:i:s', strtotime('-'.$daylight_savings_offset_in_seconds.' seconds', strtotime($date)));     } $date = "2014-11-30 23:50:00"; //yyyy-mm-dd //$date = "11/30/2014 23:50:00"; //mm/dd/yyyy //$date = "30-11-2014 23:50:00"; //dd-mm-yyyy $timezone = "Asia/Kolkata"; //$timezone = "Australia/Adelaide"; //$timezone = "America/New_York"; echo getGMT($date, $timezone);

Find Random Coordinates in the proximity

If you are asked to find the random coordinates (latitude & longitude) considering that your latitude & longitude as the center and with in the given proximity (radius), then this service will help to get one such coordinate. An example, you are at X location (17.414472, 78.449024) and radius 1 mile.  /**      * picks the random latitude & longitude with respect to given within the provided radius      *      * @param array $centre    (lat, lng)      * @param number $radius                 * @return array:      */     function getCoordinates($centre, $radius)     {         $radius_earth = 3959; // miles                                       // Pick random distance within $distance;         $distance = lcg_value() * $radius;                 // Convert degrees to radians.         $centre_rads = array_map('deg2rad', $centre);                 // First suppose our point is the north pole.         // Find a random point $distance miles away         $lat_rads = (pi()

Get Latitude & Longitude from address

function getLatLong($address){     $prep_addr = str_replace(' ','+',$address);     $geocode = file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$prep_addr.'&sensor=false');     $output= json_decode($geocode);     $lat = $output->results[0]->geometry->location->lat;     $long = $output->results[0]->geometry->location->lng;     return array("latitude" => $lat, "longitude" => $long); }

Read .docx file as string

I found it after googling for a day, finally a function that reads the .docx file and return you a string. Hats off to the original author of this function. function readDocx($file_name){     $striped_content = '';     $content = '';     if(!$file_name || !file_exists($file_name))         return false;     $zip = zip_open($file_name);     if (!$zip || is_numeric($zip))         return false;     while ($zip_entry = zip_read($zip)) {         if (zip_entry_open($zip, $zip_entry) == FALSE)             continue;         if (zip_entry_name($zip_entry) != "word/document.xml")             continue;         $content .= zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));         zip_entry_close($zip_entry);     }// end while     zip_close($zip);     $content = str_replace('</w:r></w:p></w:tc><w:tc>', " ", $content);     $content = str_replace('</w:r></w:p>', "\r\n", $content);     $stripe

Convert object to multi dimensional array

   /**     *     * Convert an object to an array     *     * @param    object  $object The object to convert     * @reeturn      array     *     */      function  objectToArray (  $object  )     {         if( ! is_object (  $object  ) && ! is_array (  $object  ) )         {             return  $object ;         }         if(  is_object (  $object  ) )         {              $object  =  get_object_vars (  $object  );         }         return  array_map (  'objectToArray' ,  $object  );     }      /*** convert the array to object ***/      $array  =  objectToArray (  $obj  );      /*** show the array ***/      print_r (  $array  );   Taken from phpro.org

Windows Azure SQL Database PDO

I faced a problem while trying to connect Windows Azure SQL Database from local system using PDO. Here I'm using PHP 5.4+ and Apache 2.4 on Windows 8. I didn't find better tutorial for trouble shooting. Following are the steps that explains you what to do.. Download php_pdo_sqlsrv_54_ts.dll and placed it in php/ext directory. Here you can find it http://www.microsoft.com/en-us/download/details.aspx?id=20098 Download SQLSRV30.EXE and extracted to php/ext directory Open the php/php.ini file and added the following line extension=php_pdo_sqlsrv_54_ts.dll It needs Microsoft SQL Server 2012 Native Client, to go further. So download it from http://www.microsoft.com/en-us/download/confirmation.aspx?id=29065 for 32bits(x86) http://go.microsoft.com/fwlink/?LinkID=239647&clcid=0x409 for 64bits(x64) http://go.microsoft.com/fwlink/?LinkID=239648&clcid=0x409 Restart the Apache server. Write the following code in php file to connect. $server_url = "xxxxxx

Download file using PHP

Downloading a file can be done in two ways: Direct download Indirect download Direct Download: Assumptions: File location: c:/xampp/htdocs/project/docs/test.doc URL: http://localhost/project/docs/test.doc Code:   <a href='http://localhost/project/docs/test.doc'>click here</a> Indirect Download: (recommended) Assumptions: File location: c:/xampp/htdocs/project/docs/test.doc PHP file for the download code: location: c:/xampp/htdocs/project/download.php <?php   $file_name = $_GET['file'];   $file_path = "docs/".$file_name;  //setting the content type   header('content-type: application/octet-stream');   //downloads file as attachment   header("content-disposition: attachment; filename='$file_name'");   //actual file path   readfile($file_path); ?> Note: content-type application/octet-stream can be used for any type of file. To use the above file for download. Create link like as be

PHP Best Practices

This guide will give you solutions to common  PHP  design problems. It also provides a sketch of an application layout that I developed during the implementation of some  project s. php .ini quirks Some settings in the  php .ini control how  PHP  interpretes your scripts. This can lead to unexpected behaviour when moving your application from development to the productive environment. The following measures reduce dependency of your code on  php .ini settings. short_open_tag Always use the long  PHP  tags:  php echo "hello world"; ?> Do not use the echo shortcut  . asp_tags Do not use ASP like tags:  <% echo "hello world"; %> gpc_magic_quotes I recommend that you include code in a global include file which is run before any $_GET or $_POST parameter or $_COOKIE is read. That code should check if the gpc_magic_quotes option is enabled and run all $_GET, $_POST and $_COOKIE values through the  stripslashes  function. register_globals Never rely on this o