Category Archives: PHP

php news, php articals, php certification, php frameworks, php classes, php code, php feed, php update, php array, php string, php function, php oops, php xml, php open projects, PHP SOAP

How to make download file forcefully and securely ?

#   _____ ____  ____  ____  _____   ____  ____  _      _      _     ____  ____  ____ 
#  /    //  _ \/  __\/   _\/  __/  /  _ \/  _ \/ \  /|/ \  /|/ \   /  _ \/  _ \/  _ \
#  |  __\| / \||  \/||  /  |  \    | | \|| / \|| |  ||| |\ ||| |   | / \|| / \|| | \|
#  | |   | \_/||    /|  \_ |  /_   | |_/|| \_/|| |/\||| | \||| |_/\| \_/|| |-||| |_/|
#  \_/   \____/\_/\_\\____/\____\  \____/\____/\_/  \|\_/  \|\____/\____/\_/ \|\____/
#

Warning – Be careful with this script i have modified this just for me but you can use it anyways.

 'pass_protected/myfile_02.zip',
	'2_docs' => 'pass_protected/myfile_32.zip',
	'2_js' => 'pass_protected/my_docs.zip'
);


$file_name = $_GET['file'];
$file_name = isset($zip_files[$file_name]) ? $zip_files[$file_name] : null;
$file_name = $file_name ? Config::ABS_PATH . $file_name : null;

if (!$file_name) {
	exit();
}



// make sure it's a file before doing anything!
if(file_exists($file_name)) {

	/*
		Do any processing you'd like here:
		1.  Increment a counter
		2.  Do something with the DB
		3.  Check user permissions
		4.  Anything you want!
	*/
	
	

	// required for IE
	if(ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', 'Off');	}

	// get the file mime type using the file extension
	switch(strtolower(substr(strrchr($file_name, '.'), 1))) {
		//case 'pdf': $mime = 'application/pdf'; break;
		case 'zip': $mime = 'application/zip'; break;
		//case 'jpeg':
		case 'jpg': $mime = 'image/jpg'; break;
		default: $mime = 'application/force-download';
	}
	header('Pragma: public'); 	// required
	header('Expires: 0');		// no cache
	header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
	header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($file_name)).' GMT');
	header('Cache-Control: private',false);
	header('Content-Type: '.$mime);
	header('Content-Disposition: attachment; filename="'.basename($file_name).'"');
	header('Content-Transfer-Encoding: binary');
	header('Content-Length: '.filesize($file_name));	// provide file size
	header('Connection: close');
	readfile($file_name);		// push it out
	exit();

}

?>
Share

How protect files using php and .htaccess ?

phpmind-password-dialog

htaccess-logo
You can secure any file using this script.
It will not allow you to access without username and password.

1st step is to create .htaccess file in a folder which you want to protected.
2nd step is add index.php as shown in example. This will not work as it is but you can modify.

/*******************************************************/


.htaccess file

/********************************************************/

Options -Indexes 

RewriteEngine On

RewriteCond $0 !^(favicon\.ico|favicon\.png|media|robots\.txt|crossdomain\.xml|css|js)

RewriteRule .* index.php?file=$0 [QSA,L] # pass everything thru php
 

 


Share

How to use PHP to output an mp4 video ?

phpmind-mp4
I want my videos URL to keep hidden from the users while still, they can able to see the video. 

It have 2 parts.

1. PHP code and
2. HTML video Code

0||$end<$size)
  header('HTTP/1.0 206 Partial Content');
else
  header('HTTP/1.0 200 OK');

header("Content-Type: video/mp4");
header('Accept-Ranges: bytes');
header('Content-Length:'.($end-$begin));
header("Content-Disposition: inline;");
header("Content-Range: bytes $begin-$end/$size");
header("Content-Transfer-Encoding: binary\n");
header('Connection: close');

$cur=$begin;
fseek($fm,$begin,0);

while(!feof($fm)&&$cur<$end&&(connection_status()==0))
{ print fread($fm,min(1024*16,$end-$cur));
  $cur+=1024*16;
  usleep(1000);
}
die();
?>



Share

How to rotate flight marker towards arrival airport in leaflet ?

 

flight_market_heading

First it is important to know how it works –

    1. Check out Leaflet Rotated Marker  plugin https://github.com/bbecquet/Leaflet.RotatedMarker
    2. L.marker([48.8631169, 2.3708919], {
          rotationAngle: 45
      }).addTo(map);
      
      

rotationAngle property need a value and this is key. You will have to generate that dynamically based on aircraft position and destination airport.  Function below does the same calculate  and give rotationAngle.

Function in Python

def computeHeading(lat1, long1, lat2, long2):
    import math
    
    rlat1 = math.radians(lat1)
    rlat2 = math.radians(lat2)
       
    dlong = math.radians(long2 - long1)
    
    y = math.cos(rlat2) * math.sin(dlong)
    x = math.cos(rlat1) * math.sin(rlat2) - math.sin(rlat1) * math.cos(rlat2) * math.cos(dlong)
    heading = round(math.degrees(math.atan2(y, x)) + 360, 4) % 360
    
    return heading

Keep in mind that lat1 and long1 are the aircraft’s position. And lat2, long2 are airport destination where aircraft is heading.

 

Function in PHP

function computeHeading($lat1, $long1, $lat2, $long2) // lat1 and long1 are the aircraft's position
{

    $rlat1 = deg2rad($lat1);
    //$rlat2 = radians($lat2);

    //$rlat1 = radians($lat1);
    $rlat2 = deg2rad($lat2);

    $dlong = deg2rad($long2 - $long1);
    //$dlong = radians(long2 - long1);

    $y = cos($rlat2) * sin($dlong);
    $x = cos($rlat1) * sin($rlat2) - sin($rlat1) * cos($rlat2) * cos($dlong);
    $heading = round(degrees(atan2($y, $x)) + 360, 4) % 360;

    return $heading;

}

Function in JavaScript

  function computeHeading(lat1, long1, lat2, long2)
    {

        // Converts from degrees to radians.
        Math.radians = function(degrees) {
            return degrees * Math.PI / 180;
        };

        // Converts from radians to degrees.
        Math.degrees = function(radians) {
            return radians * 180 / Math.PI;
        };


       var rlat1 = Math.radians(lat1);
       var rlat2 = Math.radians(lat2);

       var dlong = Math.radians(long2 - long1);

       var y = Math.cos(rlat2) * Math.sin(dlong);
       var x = Math.cos(rlat1) * Math.sin(rlat2) - Math.sin(rlat1) * Math.cos(rlat2) * Math.cos(dlong);
       var heading = Math.round(Math.degrees(Math.atan2(y, x)) + 360, 4) % 360;

        return heading;

    }
Share

Export php array to CSV – Download CSV File

Export php array to CSV
CSV (comma-separated values) is the most widely supported format for transferring tabular data. Exporting data in CSV format is very common in web applications. This simple example will help you get started with CSV and PHP. The main goal is to create a simple way to export data from your website or web application into a CSV that can be downloaded by the user.


    $data = array(
        array('name' => 'A', 'mail' => 'a@gmail.com', 'age' => 43),
        array('name' => 'C', 'mail' => 'c@gmail.com', 'age' => 24),
        array('name' => 'B', 'mail' => 'b@gmail.com', 'age' => 35),
        array('name' => 'G', 'mail' => 'f@gmail.com', 'age' => 22),
        array('name' => 'F', 'mail' => 'd@gmail.com', 'age' => 52),
        array('name' => 'D', 'mail' => 'g@gmail.com', 'age' => 32),
        array('name' => 'E', 'mail' => 'e@gmail.com', 'age' => 34),
        array('name' => 'K', 'mail' => 'j@gmail.com', 'age' => 18),
        array('name' => 'L', 'mail' => 'h@gmail.com', 'age' => 25),
        array('name' => 'H', 'mail' => 'i@gmail.com', 'age' => 28),
        array('name' => 'J', 'mail' => 'j@gmail.com', 'age' => 53),
        array('name' => 'I', 'mail' => 'l@gmail.com', 'age' => 26),
    );

$fileName_1 = 'Manifest.csv';
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header('Content-Description: File Transfer');
        header("Content-type: text/csv");
        header("Content-Disposition: attachment; filename={$fileName_1}");
        header("Expires: 0");
        header("Pragma: public");
        $fh1 = @fopen( 'php://output', 'w' );
        $headerDisplayed1 = false;

        foreach ( $data as $data1 ) {
            // Add a header row if it hasn't been added yet
            if ( !$headerDisplayed1 ) {
                // Use the keys from $data as the titles
                fputcsv($fh1, array_keys($data1));
                $headerDisplayed1 = true;
            }

            // Put the data into the stream
            fputcsv($fh1, $data1);
        }
    // Close the file
        fclose($fh1);
    // Make sure nothing else is sent, our file is done
        exit;

Share

php how to return all dates between two dates in an array ?

add($interval);

    $period = new DatePeriod(
         new DateTime($start),
         $interval,
         $realEnd
    );

    foreach($period as $date) { 
        $array[] = $date->format('Y-m-d'); 
    }

    return $array;
}

// Call the function
$dates = getDatesFromRange('2015-10-01', '2015-12-05');

// Print the output
print_r($dates);

Array
(
    [0] => 2015-10-01
    [1] => 2015-10-02
    [2] => 2015-10-03
    [3] => 2015-10-04
    [4] => 2015-10-05
    [5] => 2015-10-06
    [6] => 2015-10-07
    [7] => 2015-10-08
    [8] => 2015-10-09
    [9] => 2015-10-10
    [10] => 2015-10-11
    [11] => 2015-10-12
    [12] => 2015-10-13
    [13] => 2015-10-14
    [14] => 2015-10-15
    [15] => 2015-10-16
    [16] => 2015-10-17
    [17] => 2015-10-18
    [18] => 2015-10-19
    [19] => 2015-10-20
    [20] => 2015-10-21
    [21] => 2015-10-22
    [22] => 2015-10-23
    [23] => 2015-10-24
    [24] => 2015-10-25
    [25] => 2015-10-26
    [26] => 2015-10-27
    [27] => 2015-10-28
    [28] => 2015-10-29
    [29] => 2015-10-30
    [30] => 2015-10-31
    [31] => 2015-11-01
    [32] => 2015-11-02
    [33] => 2015-11-03
    [34] => 2015-11-04
    [35] => 2015-11-05
    [36] => 2015-11-06
    [37] => 2015-11-07
    [38] => 2015-11-08
    [39] => 2015-11-09
    [40] => 2015-11-10
    [41] => 2015-11-11
    [42] => 2015-11-12
    [43] => 2015-11-13
    [44] => 2015-11-14
    [45] => 2015-11-15
    [46] => 2015-11-16
    [47] => 2015-11-17
    [48] => 2015-11-18
    [49] => 2015-11-19
    [50] => 2015-11-20
    [51] => 2015-11-21
    [52] => 2015-11-22
    [53] => 2015-11-23
    [54] => 2015-11-24
    [55] => 2015-11-25
    [56] => 2015-11-26
    [57] => 2015-11-27
    [58] => 2015-11-28
    [59] => 2015-11-29
    [60] => 2015-11-30
    [61] => 2015-12-01
    [62] => 2015-12-02
    [63] => 2015-12-03
    [64] => 2015-12-04
    [65] => 2015-12-05
)
Share

How to enable cross-origin resource sharing using php

I was working on parsing KML data file from different resources which had different urls and Cesiumjs was unable to read/parse, that is how i come to know enabling cross-origin resource sharing.
It is also called CORS. Here is more details .

Following these steps you can enable “CORS”.
1. First check if you have apache module installed, using php.

  

2. Use command line to check if you have “Access-Control-Allow-Origin: *”

Command is - curl -I http://yourwebsite.com

3. If you don’t see this line “Access-Control-Allow-Origin: *” in curl -I output you need to add and enable it in either in PHP file ot .htacces file.

HTTP/1.1 302 Found
Date: Sat, 19 Sep 2015 00:31:41 GMT
Server: Apache
Access-Control-Allow-Origin: *
Set-Cookie: PHPSESSID=k1ejs4ra2gsu2id387h472one2; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Location: https://phpmind.com/index.php
Content-Type: text/html; charset=UTF-8
Set-Cookie: BIGipServer~DART-Dev~DART=1241032896.20480.0000; path=/

4. Now its time to add code and enable your missing part!

In .htaccess

 

    Header set Access-Control-Allow-Origin "*"

In PHP file

header("Access-Control-Allow-Origin: *"); // for all

header('Access-Control-Allow-Origin: http://www.rnai.technology'); // For particular URL
header('Access-Control-Allow-Origin: http://phpmind.com');
header('Access-Control-Allow-Origin: http://maps.google.com');

After that you need to test using

Command is - curl -I http://yourwebsite.com

You must see Access-Control-Allow-Origin: *” with headers.

Share

How to check which apache modules are installed using php?

If you don’t have command line access use this code to see which apache modules are installed.

  

This will show a list like that.
By the way this not my server 🙂

Array
(
[0] => core
[1] => prefork
[2] => http_core
[3] => mod_so
[4] => mod_auth_basic
[5] => mod_auth_digest
[6] => mod_authn_file
[7] => mod_authn_alias
[8] => mod_authn_anon
[9] => mod_authn_dbm
[10] => mod_authn_default
[11] => mod_authz_host
[12] => mod_authz_user
[13] => mod_authz_owner
[14] => mod_authz_groupfile
[15] => mod_authz_dbm
[16] => mod_authz_default
[17] => util_ldap
[18] => mod_authnz_ldap
[19] => mod_include
[20] => mod_log_config
[21] => mod_logio
[22] => mod_env
[23] => mod_ext_filter
[24] => mod_mime_magic
[25] => mod_expires
[26] => mod_deflate
[27] => mod_headers
[28] => mod_usertrack
[29] => mod_setenvif
[30] => mod_mime
[31] => mod_dav
[32] => mod_status
[33] => mod_autoindex
[34] => mod_info
[35] => mod_dav_fs
[36] => mod_vhost_alias
[37] => mod_negotiation
[38] => mod_dir
[39] => mod_actions
[40] => mod_speling
[41] => mod_userdir
[42] => mod_alias
[43] => mod_substitute
[44] => mod_rewrite
[45] => mod_proxy
[46] => mod_proxy_balancer
[47] => mod_proxy_ftp
[48] => mod_proxy_http
[49] => mod_proxy_ajp
[50] => mod_proxy_connect
[51] => mod_cache
[52] => mod_suexec
[53] => mod_disk_cache

Share

How to Convert Seconds to Minute ?

There are 2 ways to convert Seconds into minute. Its super simple.

One - 
$seconds = "110";
$minutes = floor($seconds/60);
$secondsleft = $seconds%60;
if($minutes<10)
    $minutes = "0" . $minutes;
if($secondsleft<10)
    $secondsleft = "0" . $secondsleft;
echo "$minutes:$secondsleft Sec";
echo "
"; Two - echo gmdate("i.s", $seconds);
Share