- Licence Fondamentale d'Informatique
dimanche 6 avril 2014

How to run WAMP Server on Windows 8

As you might know that the post I made previously was just a way to get around this strange problem. After a long time, I've finally managed to find out the actual reason for this problem, which I want to share with all of you.


The thing is that Windows 8 is an IPV6-first Operating System and WAMP is, by default, configured to run with IPV4 only. This creates a conflict and hence we face this problem. To confirm that Windows 8 uses IPV6. Open the command prompt and type ping localhost and press the Enter key. You'll receive a reply from ::1 which is the loopback address for IPV6. 

So in order to properly tackle this problem, there's no need to follow the steps I mentioned in    my earlier post. Although my older post might have solved your problem, it isn't a proper solution. Here's what you should actually be doing.

Step # 1 - Changes in httpd.conf file

  • Goto the WAMP folder (in my case, I've installed it in my E drive) > inside it double click the bin folder > then apache > apache2.2.22 (or whatever version you have) > conf > inside this folder, you'll see a file named httpd which has a file type of CONF. Right-click on this file and open it with Notepad.
httpd file inside conf folder

  • After you've opened the httpd file in Notepad, press Ctrl + F or goto Edit > Find and search for Listen 80 text. After you find this text, just add a # (hash symbol) at the start of this line to comment/or make it inactive. Then type the following text on the next line - Listen 0.0.0.0:80. Save and close this file and close Notepad.

Editing in httpd file

Step # 2 - Changes in the hosts file
  • Open Notepad again, but this time as an administrator, and open the hosts file. To do this in Windows 8, press the Window Key + W to open the Search app or alternatively, press the Window Key and directly type your search term. In this case we want to search for Notepad
Search for Notepad in Windows 8

  • After you see the Notepad application icon, right-click on it and you'll see some options at the bottom of the screen. One of them reads Run as administrator. Click on it and Notepad will run as an administrator.
How to run an app as an administrator

  • Inside Notepad, click on File > Open and go to the following location, C: > Windows > System32 > Drivers > etc. Inside this etc folder you won't probably see any file which is because the file type in the bottom-right corner is set to Text Document (.txt). Select the dropdown again and select the option of All. You'll immediately see a file named hosts. Double click on it to open it in Notepad.
Open Dialog of Notepad


  • Inside the hosts file, make sure that the line with ::1 localhost written on it is commented (by using the # symbol as explained above) and the line that has 127.0.0.1 localhost is uncommented (in simple words it should not have # sign at the start of the line). Save and close this file as well as Notepad. 
Editing in hosts file using Notepad
Step # 3 (Final Step) - Restart WAMP
  • I don't think this needs any explaination. But I'll explain it anyway. Click on the WAMP system tray icon at the bottom-right of the screen and select the Restart All Services option. That's it. You're done.

Restart WAMP

After restarting WAMP, open your browser of choice and type localhost. And there you go. As for the phpmyadmin, don't worry, just type localhost/phpmyadmin and yes it works too. 

Well I hope that this method will work for all of you guys because this time we've actually handled this problem the right way. I would love to see your comments about this update. See ya next time.



Older Version of this post (not a proper solution)

I've recently started using Windows 8 on my PC and was very happy because of its great new look and feel.  But it was until I tried to open WAMP Sever on my machine. 

The problem I encountered was that WAMP's icon wasn't becoming green. Rather than that, it got stuck as an orange icon.


WAMP Server's Orange Icon  not turning Green

When I was using Windows 7,  I found out that this only happens whenever some other service or software is using our computer's Port 80 (HTTP port) and mostly it was Skype because of which I wasn't able to run WAMP properly.

On Windows 8 however, I wasn't able to find any solution to this problem. But then I came across a blog where someone had posted a solution for this, which I thought I should share with others as well. Here it is.

1. Left click on the WAMP Server system tray icon, then goto Apache > Service > Test port 80.


Checking which service is using Port 80

When you'll click on the Test Port 80 option, you'll see a cmd line screen that will display the name of the service that is using Port 80.  See the screenshot below:



Screen displaying information about Port 80


By doing this, you'll get to know which service (if any) is using Port 80. In Windows 8, by default, IIS 8 Server uses this port. When we install Windows 8, IIS 8 is also installed with it and unfortunately it automatically runs at the startup. So the only way we can make WAMP server run properly, is by Disabling this IIS 8 server.

How to Disable IIS 8 Server 


1. Open the Control Panel by Right clicking on the bottom-left corner of the screen and select the option of Control Panel. Refer to the screenshot below:


Open Control Panel (Windows 8)

2. In the Control Panel window, search for administrative tools and click on the resultant Administrative Tools icon.


Search for Administrative Tools in Control Panel

3. After the Administrative Tools window is opened, double-click on Services. Another way to access the Services window is by going to Start -> Run -> and type services.msc in the run window. Click OK and the same Services window will open.


Administrative Tools Window

4. After the Services window is opened, scroll at the bottom and double-click on World Wide Web Publishing Service.


Services Window

How to view WWWPublishing Service in Services window

This step is optional and only for those who can't find World Wide Web Publishing Service in the Services window. Jump to point number 5 if you're not one of them. Anyway, here's how to solve this problem.

4a.  Open Control Panel (as explained above). 

4b. In the Control Panel window, click on Programs (refer to the screenshot below)


Control Panel window

4c. In the Programs window, click on Turn Windows features on or off under the Programs and Features heading. (refer to the screenshot below)


Programs window

4d. When you'll click on the Turn on Windows features on or off button, a small window will pop-up. It'll contain a list of Windows Features. Scroll down until you find Internet Information Services and click on the plus (+) icon to the left of it to expand it. On expanding the menu, you'll see that one of the options will be World Wide Web Services. Just click on the checkbox on the left of it and press OK button. Windows will load for sometime and it may ask you to reboot. Reboot it if you like. And you're done.


Windows Features window

Back to our main topic

5. In the World Wide Web Publishing Service window, locate the Startup type dropdown menu and select the option that says Disable and click OK.


World Wide Web Publishing Service Window

After Disabling the IIS 8 Server, restart your computer and then open WAMP server again. Hopefully it'll run properly. To make sure that no service is using Port 80, re-run the Test Port 80 window (as described above) and you'll see a screen similar to the one below:


Test Port 80 window that shows that the port is free now


How to run Localhost on Windows 8

After Port 80 is free, I tried to run localhost in my browser but I continuously received error messages as shown below:



Error Message I received even when the WAMP icon was Green



After getting the message that is shown above, I uninstalled Skype and reinstalled the latest version of WAMP Server but still I got the following message in my browser.



Forbidden error after uninstalling Skype

After spending hours and hours on trying to solve this problem, what I found out in the end was very frustrating for me. The only thing I had to do was Left-click on the WAMP Server system tray icon and click on Put Online option (as shown below). 


Select Put Online option from WAMP Server tray icon

After that, just go to your browser of choice, and type localhost in the address bar and Voila!! It works.


Finally, localhost works!!!!
But there's still one problem, even though your localhost has started working, it is possible that you won't be allowed to access phpmyadmin. To get around this problem, just type127.0.0.1/phpmyadmin in your browser's address bar and hopefully it'll work.
   Anyway, that's it for today. Hope you enjoyed this post. Please comment if you have any questions/suggestions.
mercredi 26 mars 2014

Bind jQuery Chart to MySql Database using PHP

In this post we will show you how to connect our jQuery Chart to MySql Database using PHP. We will obtain the data from MySql Database and especially the Northwind Database. You can download the Northwind database .sql script here and run it into MySQL to create the database.
The first thing we need to do is create the file we’ll connect with. We’ll call this file connect.php.
<?php
# FileName="connect.php"
$hostname = "localhost";
$database = "northwind";
$username = "root";
$password = "";
?>
Now we have our file to do the connection for us and we need to create the file that will run the query and bring the data so our Chart can be populated. We will call the file data.php.
<?php
 #Include the connect.php file
 include('connect.php');
 #Connect to the database
 //connection String
 $connect = mysql_connect($hostname, $username, $password)
 or die('Could not connect: ' . mysql_error());
 //Select The database
 $bool = mysql_select_db($database, $connect);
 if ($bool === False){
    print "can't find $database";
 }

 $query = "SELECT * FROM  `invoices` ORDER BY OrderDate LIMIT 0 , 100";
 $result = mysql_query($query) or die("SQL Error 1: " . mysql_error());

 // get data and store in a json array
 while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
  $orders[] = array(
   'OrderDate' => $row['OrderDate'],
   'ProductName' => $row['ProductName'],
   'Quantity' => $row['Quantity']
    );
 }

 echo json_encode($orders);
?>
The data is returned as JSON. This is it for the connection and data gathering. Let’s see how to add the data we just gathered into our jQuery Chart. Create the index.php file and add references to the following javascript and css files.
<link rel="stylesheet" href="styles/jqx.base.css" type="text/css" />
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="jqxcore.js"></script>
<script type="text/javascript" src="jqxchart.js"></script>
<script type="text/javascript" src="jqxdata.js"></script>
Create a div tag for the Chart.
<div id="jqxChart"></div>
Create your Chart and load the data. We define a source object for the Chart and bind that source to the data.php which returns the JSON data. We also set up the settings object and define the chart’s categoryAxis(horizontal X axis), valueAxis(vertical Y axis) and the chart serie. For more information about the Chart’s initialization visit this help topic: jquery-chart-getting-started.htm
<script type="text/javascript">
 $(document).ready(function () {
  var source =
  {
    datatype: "json",
    datafields: [
     { name: 'OrderDate', type: 'date'},
     { name: 'Quantity'},
     { name: 'ProductName'}
   ],
   url: 'data.php'
  };  

    var dataAdapter = new $.jqx.dataAdapter(source,
  {
   autoBind: true,
   async: false,
   downloadComplete: function () { },
   loadComplete: function () { },
   loadError: function () { }
  });

  // prepare jqxChart settings
  var settings = {
   title: "Orders by Date",
   showLegend: true,
   padding: { left: 5, top: 5, right: 5, bottom: 5 },
   titlePadding: { left: 90, top: 0, right: 0, bottom: 10 },
   source: dataAdapter,
   categoryAxis:
    {
     text: 'Category Axis',
     textRotationAngle: 0,
     dataField: 'OrderDate',
     formatFunction: function (value) {
      return $.jqx.dataFormat.formatdate(value, 'dd/MM/yyyy');
     },
     showTickMarks: true,
     tickMarksInterval: Math.round(dataAdapter.records.length / 6),
     tickMarksColor: '#888888',
     unitInterval: Math.round(dataAdapter.records.length / 6),
     showGridLines: true,
     gridLinesInterval: Math.round(dataAdapter.records.length / 3),
     gridLinesColor: '#888888',
     axisSize: 'auto'
    },
   colorScheme: 'scheme05',
   seriesGroups:
    [
     {
      type: 'line',
      valueAxis:
      {
       displayValueAxis: true,
       description: 'Quantity',
       //descriptionClass: 'css-class-name',
       axisSize: 'auto',
       tickMarksColor: '#888888',
       unitInterval: 20,
       minValue: 0,
       maxValue: 100
      },
      series: [
        { dataField: 'Quantity', displayText: 'Quantity' }
        ]
     }
    ]
  };

  // setup the chart
  $('#jqxChart').jqxChart(settings);
 });
</script>
The result is a nice looking jQuery Chart.
jquery-chart-php-mysql

Using PHP to hook up charts to MySQL data base

The purpose of this article is to show you how you can hook up your client-side charts to the database servers on your back end using server-side scripting languages.
We’ll be using MySQL and PHP. However the principles outlined in this article will be applicable to any combination of server-side technologies, like ASP.NET+MSSQL, etc.
We’re gonna follow this natural progression:
  1. Create and populate sample MySQL table, that we will be using for tests.
  2. Create PHP scripts, that load data off the DB server and generate data suitable, for charts.
  3. Implement a plain vanilla JavaScript data loader to load the data from the server.
  4. Hook it all together to a working serial chart prototype.

#1: The database

For testing purposes, I’m going to create a very basic 3 column database table "my_chart_data": 1 column for category and 2 value columns. I’m also going to populate it with some random data:
CREATE TABLE IF NOT EXISTS `my_chart_data` (
  `category` date NOT NULL,
  `value1` int(11) NOT NULL,
  `value2` int(11) NOT NULL
);
Then we’ll populate with some data:
INSERT INTO `my_chart_data` (`category`, `value1`, `value2`) VALUES
('2013-08-24', 417, 127),
('2013-08-25', 417, 356),
('2013-08-26', 531, 585),
('2013-08-27', 333, 910),
('2013-08-28', 552, 30),
('2013-08-29', 492, 371),
('2013-08-30', 379, 781),
('2013-08-31', 767, 494),
('2013-09-01', 169, 364),
('2013-09-02', 314, 476),
('2013-09-03', 437, 759);

#2: Generating the data

In this step we’re going to create a PHP script that connects to MySQL server, loads the data and outputs the data in JSON format, which is a de facto standard for JavaScript-based applications.
<?php
// Connect to MySQL
$link = mysql_connect( 'localhost', 'root', '' );
if ( !$link ) {
  die( 'Could not connect: ' . mysql_error() );
}

// Select the data base
$db = mysql_select_db( 'test', $link );
if ( !$db ) {
  die ( 'Error selecting database \'test\' : ' . mysql_error() );
}

// Fetch the data
$query = "
  SELECT *
  FROM my_chart_data
  ORDER BY category ASC";
$result = mysql_query( $query );

// All good?
if ( !$result ) {
  // Nope
  $message  = 'Invalid query: ' . mysql_error() . "\n";
  $message .= 'Whole query: ' . $query;
  die( $message );
}

// Print out rows
while ( $row = mysql_fetch_assoc( $result ) ) {
  echo $row['category'] . ' | ' . $row['value1'] . ' | ' .$row['value2'] . "\n";
}

// Close the connection
mysql_close($link);
?>
This prints out the data from our table nicely:
2013-08-24 | 417 | 127
2013-08-25 | 417 | 356
2013-08-26 | 531 | 585
2013-08-27 | 333 | 910
2013-08-28 | 552 | 30
2013-08-29 | 492 | 371
2013-08-30 | 379 | 781
2013-08-31 | 767 | 494
2013-09-01 | 169 | 364
2013-09-02 | 314 | 476
2013-09-03 | 437 | 759
That’s nice, but that’s not JSON, we’re aiming for. Let’s modify our script to produce a valid JSON output:
// Print out rows
$prefix = '';
echo "[\n";
while ( $row = mysql_fetch_assoc( $result ) ) {
  echo $prefix . " {\n";
  echo '  "category": "' . $row['category'] . '",' . "\n";
  echo '  "value1": ' . $row['value1'] . ',' . "\n";
  echo '  "value2": ' . $row['value2'] . '' . "\n";
  echo " }";
  $prefix = ",\n";
}
echo "\n]";
Now it produces a nicely formatted, valid JSON data:
[{
  "category": "2013-08-24",
  "value1": 417,
  "value2": 127
}, {
  "category": "2013-08-25",
  "value1": 417,
  "value2": 356
}, {
  "category": "2013-08-26",
  "value1": 531,
  "value2": 585
}, {
  "category": "2013-08-27",
  "value1": 333,
  "value2": 910
}, {
  "category": "2013-08-28",
  "value1": 552,
  "value2": 30
}, {
  "category": "2013-08-29",
  "value1": 492,
  "value2": 371
}, {
  "category": "2013-08-30",
  "value1": 379,
  "value2": 781
}, {
  "category": "2013-08-31",
  "value1": 767,
  "value2": 494
}, {
  "category": "2013-09-01",
  "value1": 169,
  "value2": 364
}, {
  "category": "2013-09-02",
  "value1": 314,
  "value2": 476
}, {
  "category": "2013-09-03",
  "value1": 437,
  "value2": 759
}]
Let’s go and verify the output if it’s a valid JSON. Yup, it is.
php1

#3: Loading the data in browser via JavaScript

I’m going to create data loader functions in the AmCharts namespace, so to avoid any potential conflicts with your and 3rd party JavaScript code.
Let’s create a function that first loads the target URL data then parses it. Please note that JSON is essentially JavaScript, so we’re just going to use eval() function to “parse” the data.
AmCharts.loadJSON = function(url) {
  // create the request
  if (window.XMLHttpRequest) {
    // IE7+, Firefox, Chrome, Opera, Safari
    var request = new XMLHttpRequest();
  } else {
    // code for IE6, IE5
    var request = new ActiveXObject('Microsoft.XMLHTTP');
  }

  // load it
  // the last "false" parameter ensures that our code will wait before the
  // data is loaded
  request.open('GET', url, false);
  request.send();

  // parse adn return the output
  return eval(request.responseText);
};
NOTE: Make sure this code is executed after the amcharts.js libarry is included, so the AmCharts object is already available.
Now let’s start building out the chart code by using the above function:
 AmCharts.ready(function() {
   // load the data
   var chartData = AmCharts.loadJSON('data.php');

   // this is a temporary line to verify if the data is loaded and parsed correctly
   // please note, that console.debug will work on Safari/Chrome only
   console.debug(chartData);

   // build the chart
   // ...
 });
Let’s check browser’s console:
php2
Beautiful!
NOTE #2: Due to JavaScript security restrictions, the above function will not work if you load the page locally (via file:///). You need to have it loaded via web server (http://)

#4: Build a fully functional chart using loaded data

Here’s the full code for the chart:
var chart;

// create chart
AmCharts.ready(function() {

  // load the data
  var chartData = AmCharts.loadJSON('data.php');

  // SERIAL CHART    
  chart = new AmCharts.AmSerialChart();
  chart.pathToImages = "http://www.amcharts.com/lib/images/";
  chart.dataProvider = chartData;
  chart.categoryField = "category";
  chart.dataDateFormat = "YYYY-MM-DD";

  // GRAPHS

  var graph1 = new AmCharts.AmGraph();
  graph1.valueField = "value1";
  graph1.bullet = "round";
  graph1.bulletBorderColor = "#FFFFFF";
  graph1.bulletBorderThickness = 2;
  graph1.lineThickness = 2;
  graph1.lineAlpha = 0.5;
  chart.addGraph(graph1);

  var graph2 = new AmCharts.AmGraph();
  graph2.valueField = "value2";
  graph2.bullet = "round";
  graph2.bulletBorderColor = "#FFFFFF";
  graph2.bulletBorderThickness = 2;
  graph2.lineThickness = 2;
  graph2.lineAlpha = 0.5;
  chart.addGraph(graph2);

  // CATEGORY AXIS 
  chart.categoryAxis.parseDates = true;

  // WRITE
  chart.write("chartdiv");
});
And here’s, Ladies and Gentlemen, the final output:
php4
If you’re not big on copying and pasting the code, you can download the complete working example with all the files used in this tutorial here: tutorial_assets_external-data.zip
vendredi 21 mars 2014

PHP: Step-by-step OAuth for Dummies based on LinkedIn API (Part II)

Part II: Getting LinkedIn Access Token

This guide is a follow up from Part I: Redirecting User to LinkedIn. At this point, it is assume that we have gotten our LinkedIn Consumer Key and Consumer Secret as PHP constants LINKEDIN_KEY and LINKEDIN_SECRET respectively. We should have also gotten your request token and request token secret saved in session variables $_SESSION[‘linkedin_oauth_token’] and $_SESSION[‘linkedin_oauth_token_secret’].
In Part I, we ended with redirecting user to LinkedIn authorization page, after user login and granted access, he/she will be brought back to the callback URI we specified earlier on. LinkedIn will pass in some parameters in the URI as GET parameters. This guide is about the basic steps to get the access token in the callback script.
Step 1 - Validate Parameters Passed Back by LinkedIn
If everything is correct and user granted our website the access, LinkedIn will redirect him/her back to the callback URI with some parameters. The 2 important parameters are $_GET[‘oauth_token’] and $_GET[‘oauth_verifier’]. The $_GET[‘oauth_token’] should be the same as the request token we used pass to LinkedIn when redirecting user to the authorization page.  We start by making sure these parameters are there and the token is the same.
if (empty($_GET['oauth_token']) || empty($_GET['oauth_verifier']) || $_GET['oauth_token']!=$_SESSION['linkedin_oauth_token']) {
  echo 'You must grant us access to proceed on.'; exit();
}
Step 2 - Prepare OAuth Parameters
The require parameters are listed in the code. It is quite similar with those used in Part I, but without oauth_callback and with oauth_token and oauth_verifier.
$params = array(
  'oauth_consumer_key'=>LINKEDIN_KEY,
  'oauth_nonce'=>sha1(microtime()),
  'oauth_signature_method'=>'HMAC-SHA1',
  'oauth_timestamp'=>time(),
  'oauth_token'=>$_GET['oauth_token'],
  'oauth_verifier'=>$_GET['oauth_verifier'],
  'oauth_version'=>'1.0'
);
Step 3 - Prepare The Base String
This is the similar as Part I. But with the URL replaced by the access token URL. Notice that $links[‘access_token’] was defined in Part I, you need to re-define it in the callback script if you are separating the Part I and Part II code as 2 files. I will show how to combine Part I and Part II codes in one script at the end.
// sort parameters according to ascending order of key
ksort($params);

// prepare URL-encoded query string
$q = array();
foreach ($params as $key=>$value) {
  $q[] = urlencode_oauth($key).'='.urlencode_oauth($value);
}
$q = implode('&',$q);

// generate the base string for signature
$parts = array(
  'POST',
  urlencode_oauth($links['access_token']),
  urlencode_oauth($q)
);
$base_string = implode('&',$parts);
Step 4 - Get The Signature
Again, this step is quite similar to Part I. In Part I, we don’t have any token secret, so we ended up using only the Consumer Key concatenate with an empty string. Now, we need to make use of the request token secret we obtained and saved in session in Part I.
$key = urlencode_oauth(LINKEDIN_SECRET) . '&' . urlencode_oauth($_SESSION['oauth_token_secret']);
$signature = base64_encode(hash_hmac('sha1',$base_string,$key,true));
Step 5 - Put the Signature into Parameters and Prepare Authorization Header
This step is again similar to Part I with the POST request URL change to /uas/oauth/accessToken.
$params['oauth_signature'] = $signature;
$str = array();
foreach ($params as $key=>$value) {
  $str[] = $key . '="'.urlencode_oauth($value).'"';
}
$str = implode(', ',$str);
$headers = array(
  'POST /uas/oauth/accessToken HTTP/1.1',
  'Host: api.linkedin.com',
  'Authorization: OAuth '.$str,
  'Content-Type: text/xml;charset=UTF-8',
  'Content-Length: 0',
  'Connection: close'
);
Step 6 - Send POST Request To LinkedIn
This step is exactly the same as Part I.
$fp = fsockopen("ssl://api.linkedin.com",443,$errno,$errstr,30);
if (!$fp) { echo 'Unable to connect to LinkedIn'; exit(); }
$out = implode("\r\n",$headers) . "\r\n\r\n";
fputs($fp,$out);

// getting LinkedIn server response
$res = '';
while (!feof($fp)) $res .= fgets($fp,4096);
fclose($fp);
If you do everything correctly, you should get a response like this. The response is quite similar to Part I as well.
HTTP/1.1 200 OK
Server: Apache-Coyote/1.1
Content-Type: text/plain
Content-Length: 236
Date: Sun, 07 Nov 2010 03:25:59 GMT

oauth_token=cd87b123-7623-8fdf-8k6k-73oef1e27a26&oauth_token_secret=1fe0345e-999d-431f-9ae6-9b55fe255c41&oauth_expires_in=0&oauth_authorization_expires_in=0
Step 7 - Parse the Response to Get The Access Token and Secret
$parts = explode("\n\n",str_replace("\r",'',$res);
$res_headers = explode("\n",$parts[0]);
if ($res_headers[0] != 'HTTP/1.1 200 OK') {
  echo 'Error getting access token and secret.'; exit();
}
parse_str($parts[1],$data);
if (empty($data['oauth_token'])) {
  echo 'Failed to get LinkedIn access token.'; exit();
}
Step 8 - Save the Request Token and Secret
At this point, you should have gotten the user access token and access token secret in $data[‘oauth_token’] and $data[‘oauth_token_secret’] respectively. You need to save them as you need to use them in the rest of LinkedIn API to perform protected request like getting user LinkedIn information, posting Shares on behave of user and etc. For this example, I will save it in session, you may in fact, saved it in MySQL database as LinkedIn access token and access token secret do not expire (based on the return above).
$_SESSION['linkedin_access_token'] = $data['oauth_token'];
$_SESSION['linkedin_access_token_secret'] = $data['oauth_token_secret'];

// unset the Request Token (not needed anymore)
unset($_SESSION['linkedin_oauth_token']);
unset($_SESSION['linkedin_oauth_token_secret']);
Combining Part I and Part II
So far, we have discussed Part I and Part II separately. You can combine Part I and Part II in a single script with some control logic.
// Defining all the constants, function and links here
// --- Step 1, 2 and 3 of Part I ---

// Use validation logic in Step 1 of Part II to decide if it
// it is a callback or direct access
if (empty($_GET['oauth_token']) || empty($_GET['oauth_verifier']) || $_GET['oauth_token']!=$_SESSION['linkedin_oauth_token']) {
  // Do the remaining Step 4 and onward of Part I to redirect user to LinkedIn authorization page
  // --- Step 4 and onward of Part I ---
}

// At this point you should have the Request Token in session already.
// Use the Request Token to obtain the Access Token
// --- Step 2 and onward of Part II ---
Important Observation in Part I and Part II
You should have noticed that Part I and Part II is quite similar. For Part I, we started without any token and token secret. So, we used Consumer Secret and empty token secret for signing the base string and did not pass any token to request for the temporary token known as Request Token from LinkedIn. For Part II, we have already gotten the Request Token. Thus, we used Consumer Secret and Request Token Secret to sign the base string. We passed in the request token when requesting for Access Token - the ‘ultimate’ token we wanted to get. Once you get the Access Token, the Request Token has no other use and can be deleted. In fact, for the rest of LinkedIn API, you will be doing similar things as in Part II. To access protected LinkedIn resources or perform action on behalf of user in LinkedIn, you will use Consumer Secret and Access Token Secret to sign the base string and pass in the Access Token when performing GET,POST or PUT request to LinkedIn.
I will write the Part III that showing examples of how to do some common requests like getting user information and posting Share. Follow me in Tumblr if you would like to get notify when it is up.
 
-