Like us on Facebook and stand a chance to win pen drives!

Showing posts with label PHP. Show all posts
HTTP Cache
HTTP Cache
HTTP Cache can be troublesome during development in some occasions specially in developing and testing web services, testing endpoints. We can use PHP headers to prevent and disable HTTP cache. 

header("Content-Type: application/json");
header("Expires: 0");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");

 Other than the above, there are other techniques of prevent  browser caching.
CodeIgniter
CodeIgniter



class FlashMessage {

    public static function render() {
        if (!isset($_SESSION['my_my_messages'])) {
            return null;
        }
        $my_messages = $_SESSION['my_messages'];
        unset($_SESSION['my_messages']);
        return implode('<br/>', $my_messages);
    }

    public static function add($message) {
        if (!isset($_SESSION['my_messages'])) {
            $_SESSION['my_messages'] = array();
        }
        $_SESSION['my_messages'][] = $message;
    }

}


<?php
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', YOUR_.PEM_FILE);
stream_context_set_option($ctx, 'ssl', 'passphrase', YOUR_PASSPHRASE);
 
$fp = stream_socket_client(
        'ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
 
if (!$fp) {
    exit("Failed to connect: $err $errstr

");
}
 
echo 'Connected to APN
';
 
 
// Create the payload body
$body['aps'] = array(
    'badge' => +1,
    'alert' => 'Testing push notifications',
    'sound' => 'new_wall_paper.wav',
    'action-loc-key' => 'OK'
);
 
$payload = json_encode($body);
 
for ($i = 0; $i < count($tokens); $i++) {
    $msg = chr(0) . pack('n', 32) . pack('H*', $tokens [$i]) . pack('n', strlen($payload)) . $payload;
    fwrite($fp, $msg, strlen($msg));
}
 
echo "Completed sending messages";
fclose($fp);
?>

PHPExcelReader.
PHPExcelReader.


To import Excel data, first you need to have a Excel reader. It should be accurate enough to interpret Excel data as expected. There 's a good old Excel reader.

Download PHPExcelReader.

In the downloaded archive, you only need Excel directory with files including oleread.inc and reader.php.

Just extract it where your web server can access.

Next place your excel file or just create one with some dummy data. Make sure this file is readble by the web server.

Finally create your php script to connect with database, read Excel file and insert data into db.



<?php

require_once 'Excel/reader.php';

$data = new Spreadsheet_Excel_Reader();

$data->setOutputEncoding('CP1251');

$data->read('a.xls');



$conn = mysql_connect("localhost","root","");

mysql_select_db("test",$conn);



for ($x = 2; $x <= count($data->sheets[0]["cells"]); $x++) {

$first = $data->sheets[0]["cells"][$x][1];

$middle = $data->sheets[0]["cells"][$x][2];

$last = $data->sheets[0]["cells"][$x][3];

$sql = "INSERT INTO mytable (First,Middle,Last)

VALUES ('$first','$middle','$last')";

echo $sql."\n";

mysql_query($sql);

}



?>


Symfony Bundles
Symfony Bundles
1. Export to PDF


There are various PHP libraries to create PDF documents. FPDF, MPDF, DomPDF, HTML2PDF are among those popular ones. Each of them has some sort of uniqueness in terms of functionality. This tutorial is just a demo of FPDF using official distribution.

Demo

Create Excel
Create Excel




<?php

header("Content-Type: application/xls");

header("Content-disposition: attachment; filename=data.xls");

echo 'Id' . "\t" . 'Item' . "\t" . 'Qty' . "\n";

echo '001' . "\t" . 'Compaq 610 laptop' . "\t" . '02' . "\n";

?>



In this tutorial, I 'll introduce you to YOURS, an OpenSource directions API. There are few OpenSource directions APIs available such as MapQuest, GeoSmart, Nominatim in addition to YOURS. However in my opinion, YOURS is the best and a good alternative to Google Directions which is the most popular Directions provider obviously.

The flexibility of usage has given more power in YOURS over other APIs in the same family. MapQuest is nice but it is not working for many geographical locations of the world other than North America and Europe. Nominatim is poor in its functional level and has less support for geographical diversity.

According to YOURS doucmentation, the API provide following features.

  • Generate fastest or shortest routes in different modes:

    • using all available roads for Car, Bicycle and Pedestrians .

    • using only national, regional or local cycle routes/networks for Bicycle.

  • Unlimited via points (waypoints) to make complex routes.

  • Drag and drop waypoints moving.

  • Drag and drop waypoint ordering.

  • Geolocation: Lookup street- and placenames to determine their coordinates.

  • Reverse geolocation: Lookup coordinates to determing their street- and placenames.You can read other features in doucmentation.

Example URL


http://www.yournavigation.org/api/1.0/gosmore.php?format=kml&flat=52.215676&flon=5.963946&tlat=52.2573&tlon=6.1799&v=motorcar&fast=1&layer=mapnik

This tutorial provides sample code for accessing the API in JavaScript. As JavaScript does not allow  cross domain requests we 're using a proxy which accepts requests from client, forward it to the API and send back server response. The proxy is written in PHP using CURL which is more safe than file_get_contents() and similar content loading functions.

We are using OpenLayers map with a vector layer which is going get features from server response. The route is drawn on map using vector data.

The API also provides travelling time, distance and turn by turn directions.

Demo

client.html


<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <meta name="description" content="OpenSource Directions API Demo - YOURS Navigation API">
        <title>OpenSource Directions API Demo</title>
        <link rel="stylesheet" href="http://demos.site11.com/assets/css/style.css">
        <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
        <script src="http://openlayers.org/api/OpenLayers.js"></script>
            var lon = 0;
            var lat = 0;
            var zoom = 0;

            var wgs84 = new OpenLayers.Projection("EPSG:4326");
            var mercator = new OpenLayers.Projection("EPSG:900913");

            $(document).ready(function(){
                layer = new OpenLayers.Layer.OSM("OSM");
                geojson_layer = new OpenLayers.Layer.Vector("GeoJSON", {
                    styleMap: new OpenLayers.StyleMap({
                        strokeColor: "#F00",
                        projection: mercator
                    }),
                    strategies: [new OpenLayers.Strategy.Fixed()],
                    protocol: new OpenLayers.Protocol.HTTP({
                        url: 'proxy.php?flat=6.9344&flon=79.8428&tlat=7.2844590&tlon=80.637459&v=motorcar&fast=1&layer=mapnik',
                        format: new OpenLayers.Format.GeoJSON()

                    })
                });

                var options = {
                    div : "map",
                    projection : wgs84,
                    units: "dd",
                    numZoomLevels : 7
                };
                var map = new OpenLayers.Map(options);

                map.addLayers([layer,geojson_layer]);
                map.setCenter(new OpenLayers.LonLat(79.8428, 6.9344).transform(wgs84,mercator), 12);

                //Get Directions
                $.ajax({
                    type: 'GET',

                    dataType: 'json',
                    url: 'proxy.php?flat=6.9344&flon=79.8428&tlat=7.2844590&tlon=80.637459&v=motorcar&fast=1&layer=mapnik',
                    cache: false,
                    success: function(response){
                        $("#travel_time").html(response.properties.traveltime);
                        $("#distance").html(response.properties.distance + ' miles');
                        $("#directions").html(response.properties.description);
                    },error: function(){

                    }
                });

            });

        </script>
        <style type="text/css">
            #map{
                width: 800px;
                height: 400px;
                border: 2px solid black;
                padding:0;
                margin:0;
            }
        </style>
    </head>
    <body>
 <div id="map" style="width: 700px; height: 300px;margin-bottom : 50px;" align="center"></div>
                    <p><b>Travel Time</b></p><div id="travel_time"></div><br>
                    <p><b>Distance</b></p><div id="distance"></div><br>
                    <p><b>Directions</b></p><div id="directions"></div>
  </body>
</html>
Proxy.php

<?php
$flat = $_GET['flat'];
$flon = $_GET['flon'];
$tlat = $_GET['tlat'];
$tlon = $_GET['tlon'];
$v = $_GET['v'];
$fast = $_GET['fast'];
$layer = $_GET['layer'];

$myURL = "http://www.yournavigation.org/api/1.0/gosmore.php?format=geojson&instructions=1&flat=".$flat."&flon=".$flon."&tlat=".$tlat."&tlon=".$tlon."&v=".$v."&fast=".$fast."&layer=".$layer;
$curl = curl_init();

curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $myURL

));

$resp = curl_exec($curl);
curl_close($curl);
echo $resp;
?>
PHP Graphs
PHP Graphs


There are so many PHP graph projects which you can find on internet. At the time of writing this post, JpGraph, phpgraphlib and pChart should appear in top Google search results. In my experience, phpgraphlib is developer-friendly and easy to use whereas JpGraph is more robust than others. pChart seems to be little bit outdated though they have updated their project.

JpGraph

phpgraphlib

Relying on $_SERVER['REMOTE_ADDR'] to find your client's ip address is not always good. Looking for a wide solution?

Then use this function.

function get_ip() {
$ip = '';
if ($_SERVER['HTTP_CLIENT_IP'])
$ip = $_SERVER['HTTP_CLIENT_IP'];
else if($_SERVER['HTTP_X_FORWARDED_FOR'])
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if($_SERVER['HTTP_X_FORWARDED'])
$ip = $_SERVER['HTTP_X_FORWARDED'];
else if($_SERVER['HTTP_FORWARDED_FOR'])
$ip = $_SERVER['HTTP_FORWARDED_FOR'];
else if($_SERVER['HTTP_FORWARDED'])
$ip = $_SERVER['HTTP_FORWARDED'];
else if($_SERVER['REMOTE_ADDR'])
$ip = $_SERVER['REMOTE_ADDR'];
else
$ip = '';
 
return $ip;
}
 
 Swift Mailer
 Swift Mailer

"Swift Mailer integrates into any web app written in PHP 5, offering a flexible and elegant object-oriented approach to sending emails with a multitude of features."

Download Documentation


<!--?php require_once 'swiftmailer/lib/swift_required.php'; // Create the Transport //SMTP /*$transport = Swift_SmtpTransport::newInstance('smtp.example.org', 25) --->setUsername('your username')
->setPassword('your password')
;
 
*/
 
// Sendmail
//$transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
 
// Mail
$transport = Swift_MailTransport::newInstance();
 
// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);
 
// Create a message
$message = Swift_Message::newInstance('Wonderful Subject')
->setFrom(array('john@doe.com' => 'John Doe'))
->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name'))
->setBody('Here is the message itself')
;
 
// Send the message
$result = $mailer->send($message);
?>


HTML Email with Codeigniter


$this->email->to( 'abc@gmail.com' );
$this->email->subject( 'Test' );
$this->email->message( $this->load->view( 'email/message', $data, true ) );
$this->email->send();
Codeigniter Facebook Login Tutorial using Facebook PHP SDK
Codeigniter Facebook Login Tutorial using Facebook PHP SDK

Welcome to my new Codeigniter tutorial for Facebook Login. I assume that you are familar with Codeigniter framework before starting the tutorial. However, you can adopt the source code to use in native PHP application if you are not interested in CI. There is another alternative. Previously, I have published two posts related with Facebook Login. You can also refer those tutorials.

Facebook OAUTH dialog with new Graph API
AJAX Facebook Connect Demo

First you need to create a Facebook application.
Visit this link to  create new app.
This is a straight-forward process.

New App





You need to get the App ID and App Secret of your application.

First create a config file to store App ID and App Secret.

config_facebook.php


$config['appID']    = 'YOUR_APP_ID';
$config['appSecret']    = 'YOUR_APP_SECRET';

Add a controller that handles Facebook login and logout.
fb.php


<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
 
//include the facebook.php from libraries directory
require_once APPPATH . 'libraries/facebook/facebook.php';
 
class Fb extends CI_Controller {
 
public function __construct() {
parent::__construct();
$this->config->load('config_facebook');
}
 
public function index() {
$this->load->view('head');
$this->load->view('fb');
$this->load->view('footer');
}
 
public function logout() {
$signed_request_cookie = 'fbsr_' . $this->config->item('appID');
setcookie($signed_request_cookie, '', time() - 3600, "/");
$this->session->sess_destroy();  //session destroy
redirect('/fb/index', 'refresh');  //redirect to the home page
}
 
public function fblogin() {
 
$facebook = new Facebook(array(
'appId' => $this->config->item('appID'),
'secret' => $this->config->item('appSecret'),
));
// We may or may not have this data based on whether the user is logged in.
// If we have a $user id here, it means we know the user is logged into
// Facebook, but we don't know if the access token is valid. An access
// token is invalid if the user logged out of Facebook.
$user = $facebook->getUser(); // Get the facebook user id
$profile = NULL;
$logout = NULL;
 
if ($user) {
try {
$profile = $facebook->api('/me');  //Get the facebook user profile data
$access_token = $facebook->getAccessToken();
$params = array('next' => base_url('fb/logout/'), 'access_token' => $access_token);
$logout = $facebook->getLogoutUrl($params);
 
} catch (FacebookApiException $e) {
error_log($e);
$user = NULL;
}
 
$data['user_id'] = $user;
$data['name'] = $profile['name'];
$data['logout'] = $logout;
$this->session->set_userdata($data);
redirect('/fb/test');
}
}
 
public function test() {
$this->load->view('test');
}
 
}
 
/* End of file fb.php */
/* Location: ./application/controllers/fb.php */

In this tutorial, I'm using Facebook JavaScript SDK to load the oauth dialog. You need to add the App ID in following code to initiate the SDK successfully.




** Credits goes to original author of this code

test.php

[sourcecode language="php"]
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST" && !empty($_FILES["userfile"])) {
move_uploaded_file($_FILES["userfile"]["tmp_name"], "tmp/" . $_FILES["userfile"]["name"]);
}
?>
<html>
<head>
<title>File Upload Progress Bar</title>
<style type="text/css">
#bar_blank {
border: solid 1px #000;
height: 20px;
width: 300px;
}

#bar_color {
background-color: #006666;
height: 20px;
width: 0px;
}

#bar_blank, #hidden_iframe {
display: none;
}
</style>
</head>
<body>
<div id="bar_blank">
<div id="bar_color"></div>
</div>
<div id="status"></div>
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST"
id="myForm" enctype="multipart/form-data" target="hidden_iframe">
<input type="hidden" value="myForm"
name="<?php echo ini_get("session.upload_progress.name"); ?>">
<input type="file" name="userfile"><br>
<input type="submit" value="Start Upload">
</form>

<script type="text/javascript">
function toggleBarVisibility() {
var e = document.getElementById("bar_blank");
e.style.display = (e.style.display == "block") ? "none" : "block";
}

function createRequestObject() {
var http;
if (navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
http = new XMLHttpRequest();
}
return http;
}

function sendRequest() {
var http = createRequestObject();
http.open("GET", "progress.php");
http.onreadystatechange = function () { handleResponse(http); };
http.send(null);
}

function handleResponse(http) {
var response;
if (http.readyState == 4) {
response = http.responseText;
document.getElementById("bar_color").style.width = response + "%";
document.getElementById("status").innerHTML = response + "%";

if (response < 100) {
setTimeout("sendRequest()", 1000);
}
else {
toggleBarVisibility();
document.getElementById("status").innerHTML = "Done.";
}
}
}

function startUpload() {
toggleBarVisibility();
setTimeout("sendRequest()", 1000);
}

(function () {
document.getElementById("myForm").onsubmit = startUpload;
})();
</script>
</body>
</html>
[/sourcecode]

progress.php

[sourcecode language="php"]
<?php
session_start();

$key = ini_get("session.upload_progress.prefix") . "myForm";
if (!empty($_SESSION[$key])) {
$current = $_SESSION[$key]["bytes_processed"];
$total = $_SESSION[$key]["content_length"];
echo $current < $total ? ceil($current / $total * 100) : 100;
}
else {
echo 100;
}
[/sourcecode]
[caption id="attachment_768" align="alignnone" width="502"]timezone timezone[/caption]

[sourcecode language="php"]
function getOffsetByTimeZone($localTimeZone)
{
$time = new DateTime(date('Y-m-d H:i:s'), new DateTimeZone($localTimeZone));
$timezoneOffset = $time->format('P');
return $timezoneOffset;
}

[/sourcecode]

Call this function passing a local time zone as a string.
eg.
getOffsetByTimeZone('America/New_York');
[caption id="attachment_768" align="alignnone" width="502"]timezone timezone[/caption]

[Extracted from : http://www.mindfiresolutions.com/PHP-function-for-Time-Zone-conversion-56.php]

Convert from GMT to a local timezone

[sourcecode language="php"]
function ConvertGMTToLocalTimezone($gmttime,$timezoneRequired)
{
$system_timezone = date_default_timezone_get();

date_default_timezone_set("GMT");
$gmt = date("Y-m-d h:i:s A");

$local_timezone = $timezoneRequired;
date_default_timezone_set($local_timezone);
$local = date("Y-m-d h:i:s A");

date_default_timezone_set($system_timezone);
$diff = (strtotime($local) - strtotime($gmt));

$date = new DateTime($gmttime);
$date->modify("+$diff seconds");
$timestamp = $date->format("Y-m-d h:i:s A");
return $timestamp;

}
[/sourcecode]

Convert from local timezone to GMT

[sourcecode language="php"]
function ConvertLocalTimezoneToGMT($gmttime,$timezoneRequired)
{
$system_timezone = date_default_timezone_get();

$local_timezone = $timezoneRequired;
date_default_timezone_set($local_timezone);
$local = date("Y-m-d h:i:s A");

date_default_timezone_set("GMT");
$gmt = date("Y-m-d h:i:s A");

date_default_timezone_set($system_timezone);
$diff = (strtotime($gmt) - strtotime($local));

$date = new DateTime($gmttime);
$date->modify("+$diff seconds");
$timestamp = $date->format("Y-m-d h:i:s A");
return $timestamp;
}

[/sourcecode]

Convert from one local timezone to another local timezone


[sourcecode language="php"]
function ConvertOneTimezoneToAnotherTimezone($time,$currentTimezone,$timezoneRequired)
{
$system_timezone = date_default_timezone_get();
$local_timezone = $currentTimezone;
date_default_timezone_set($local_timezone);
$local = date("Y-m-d h:i:s A");

date_default_timezone_set("GMT");
$gmt = date("Y-m-d h:i:s A");

$require_timezone = $timezoneRequired;
date_default_timezone_set($require_timezone);
$required = date("Y-m-d h:i:s A");

date_default_timezone_set($system_timezone);

$diff1 = (strtotime($gmt) - strtotime($local));
$diff2 = (strtotime($required) - strtotime($gmt));

$date = new DateTime($time);
$date->modify("+$diff1 seconds");
$date->modify("+$diff2 seconds");
$timestamp = $date->format("Y-m-d h:i:s A");
return $timestamp;
}
[/sourcecode]
[sourcecode language="php"]
echo ConvertGMTToLocalTimezone("2013-03-16 14:28:00","Asia/Seoul")."
";
echo ConvertLocalTimezoneToGMT("2013-03-16 14:28:00","Asia/Seoul")."
";
echo ConvertOneTimezoneToAnotherTimezone("2013-03-16 14:28:00","Asia/Seoul","Australia/South");
[/sourcecode]
Copyright © 2012 The Code Junction.