Home > Tags > PHP
Page 4

Pushing Updates to the Web Page with HTML5 Server-Sent Events

The HTML5 Server-Sent event model allows you to push realtime data updates from the server to the browser.

In this tutorial we will work through the process, with the EventSource object handling received data and writing it to the page. We will use HTML5 and JavaScript at client side, with PHP at server side.

With existing models such as AJAX, the code in a Web page would continually ask the server to supply new data, but the onus was on the client to request the information. With Server-Sent requests, you can stream data from your server, with updates pushed from there without the code at client side having to keep requesting it. Once your page initiates the Server-Sent event, the server script can continue sending updates. Your JavaScript code can write this new data into the page whenever it receives it.

Create an HTML5 Page

Create your HTML5 page as follows:

<!DOCTYPE html> <html> <head> </head> <body> </body> </html>

Add an Element to Display the Server-Sent Data

We will display the data received from the server in a dedicated page element, so add the following in the body section of your page:

<div id="serverData">Here is where the server sent data will appear</div>

You can put any content you like in your element, as long as it has an ID attribute so that you can identify it in your script. The placeholder text should only appear when the page first loads, but will disappear when the script runs.

Add a Script to the Page

Because we want the function to continue receiving and handling updates, we add the script section in the body of the page. Of course your own pages may execute functions on user interaction, but for the purposes of this demonstration add the following script at the end of your page, before the closing body tag:

<script type="text/javascript"> //functions here </script>

The script will execute when the browser renders the page, so the Server-Sent events will be initiated straight away. Next add the JavaScript code inside this script section:

//check for browser support if(typeof(EventSource)!=="undefined") { //create an object, passing it the name and location of the server side script var eSource = new EventSource("send_sse.php"); //detect message receipt eSource.onmessage = function(event) { //write the received data to the page document.getElementById("serverData").innerHTML = event.data; }; } else { document.getElementById("serverData").innerHTML="Whoops! Your browser doesn't receive server-sent events."; }

The script first checks that the browser supports the EventSource model. If it doesn’t, an error message is written to the server data page element instead. If the browser does support the function, the Server-Sent process begins. First, the script creates an object of the EventSource class, passing it the URL of the server side script that will be providing the streamed data updates. Then the script sets up an event listener function to execute when the EventSource object receives an update from the server. When this happens, the script simply gets a reference to the update page element and writes the new data to it.

Create a Server Side Script

We now need to create the server side PHP script to send updates to the page. Create a new file and save it “send_sse.php” or another name of your choice, as long as you amend the JavaScript EventSource code above to reflect the correct name and location. Enter the following outline in your PHP file:

<?php //streaming code ?>

Begin your PHP script by setting the headers as follows:

header('Content-Type:...
more →
MIke says: It's really horrible when you make a tutorial that is the #1 google result, and it isn't even correct. As stated in the...

Embed Analytics Using the Google Analtyics API

Google Analtyics gives so much data that sometimes it becomes hard to digest. For larger sites it is easy to become so overwhelmed that you can’t find the time to look up the analtyics for each page.

Or maybe you have many editors for a site who don’t have access to your Google Analtyics account and you want to provide them with data so they can see how well their pages are performing.

With the Google Analytics API we can easily display some basic analytics right in each page.  Google offers many libraries for exporting your data or you can use a community developed library like the GAPI PHP library created by Stig Manning which I’ll be using in this example.

The final result will be a nice graph and data that tells us some useful information about how well each page is performing:

Starting off, pulling the data

Download the latest version of GAPI and extract it to a location in your site folder. Open your page template file and find where you want to place your analtyics and then include the class you just extracted:

require('gapi.class.php');

In order to connect to Google Analytics we have to supply login information and the profile id of the specific account profile we want to connect to. While we’re defining variables, let’s also define the page URL that we want to retrieve analytics for.

$ga_email = 'youremail@gmail.com'; $ga_password = 'yourpassword'; $ga_profile_id = '12345678'; $ga_url = $_SERVER['REQUEST_URI'];

I’m not a fan of hardcoding login information into my code, but this method prevents other users from needing login access to your account to retrieve the data.

To find the profile id in Google Analytics, go to the settings page of your profile (gear icon in top right) then click on the Profile Settings tab and you will see the profile id.

Now let’s use the GAPI class to create a query and pull five metrics: pageviews, unique pageviews, exit rate, average time on page and the bounce rate. All of these metrics will be based upon the page we’re viewing. The GAPI documentation shows how to structure the query using the requestReportData() function:

requestReportData($report_id, $dimensions, $metrics, $sort_metric=null, $filter=null, $start_date=null, $end_date=null, $start_index=1, $max_results=30)

So here’s our query which we’ll save the results to the $results variable:

$ga = new gapi($ga_email,$ga_password); $ga->requestReportData($ga_profile_id, 'pagePath', array('pageviews', 'uniquePageviews', 'exitRate', 'avgTimeOnPage', 'entranceBounceRate'), null, 'pagePath == '.$ga_url); $results = $ga->getResults();

If no start and end date are given, GAPI will  return the results for the last 30 days by default.

Displaying the data

Before we display these results let’s create a function to convert seconds into minutes. This will be useful for displaying the average time on page, which by default returns the result in seconds.

function secondMinute($seconds) { $minResult = floor($seconds/60); if($minResult < 10){$minResult = 0 . $minResult;} $secResult = ($seconds/60 - $minResult)*60; if($secResult < 10){$secResult = 0 . round($secResult);}...
more →
Ratan Thapa says: Hi there, I am getting such error in http://localhost Fatal error: Uncaught exception 'Exception' with message 'GAPI: Failed...

PHP Ad Tracker: Reports and Records

In the previous lesson, we examined the basic functions of our banner ad tracking system, including the retrieval of records for both banner ads and advertisers.

In this lesson, we will look at the functions responsible for generating reports and manipulating the data in the ads table and advertiser table.

The getClientsList() function retrieves active client records and sorts them alphabetically by client name:

function getClientsList() { // get clients from db $sql = "SELECT ad_client_id, ad_client_name FROM devdrive_ads_clients WHERE deleted=0 and status=1 ORDER BY ad_client_name"; if (DB::isError($rsTmp = $this->_oConn->query($sql))) { catchExc($rsTmp->getMessage()); return false; } // loop through results and build return array $i = 0; while ($aRow = $rsTmp->fetchRow(DB_FETCHMODE_ASSOC)) { $return[$i]["Client Id"] = $aRow["ad_client_id"]; $return[$i]["Client"] = $aRow["ad_client_name"]; ++$i; } return $return; }

The getAdsReport() function retrieves the data to display an activity report for a particular banner ad campaign, including the banner ad data, client data and activity data.

function getAdsReport() { // get report data $sql = "SELECT a.ad_title, a.ad_url, a.created_dt, c.ad_client_name, c.ad_client_contact, c.ad_client_email, c.ad_client_phone, r.ad_view_cnt, r.ad_click_cnt, r.ad_activity_month, r.ad_activity_year FROM devdrive_ads...
more →

PHP Ad Tracker Part IV: Displaying and Linking Ads

In our last session, we looked at the process of entering information on ad banners and ad clients, as well as generating ad activity reports. This week, we examine how to retrieve a random banner ad. We will also learn how to delete, activate and deactivate ads and clients.

The getRandomAd() function retrieves a random ad by using the PHP rand() function. The function returns the ad’s primary key ID, client ID, title, URL and redirect path.

The function also updates the activity table for this banner ad. If no entry in the activity table exists for this ad (i.e. this is the first time this ad has appeared), the function inserts a new record for this ad into the activity table.

function getRandomAd() { $sql = "SELECT ad_id, ad_client_id, ad_title, ad_url, ad_path FROM devdrive_ads WHERE status=1 AND deleted=0 ORDER BY rand() LIMIT 0, 1"; if (DB::isError($rsTmp = $this->_oConn->query($sql))) { catchExc($rsTmp->getMessage()); return false; } // assign result to array $aRow = $rsTmp->fetchRow(DB_FETCHMODE_ASSOC); // assign return array values $return["Ad Id"] = $aRow["ad_id"]; $return["Client Id"] = $aRow["ad_client_id"]; $return["Title"] = $aRow["ad_title"]; $return["URL"] = $aRow["ad_url"]; $return["Path"] = $aRow["ad_path"]; // update advertisement activity $sql = "UPDATE devdrive_ads_activity SET ad_view_cnt=ad_view_cnt+1, ad_activity_month=".date("m").", ad_activity_year=".date("Y")." WHERE ad_id=".$aRow["ad_id"]." AND ad_activity_month=".date("m")."...
more →
Mattias Geniar says: Please consider avoiding the use of 'ORDER BY rand()' in queries. It is far more effective to generate a random integer in PHP...

How to Create and Use WordPress Custom Menus

WordPress 3.0 introduced users to a powerful feature: custom menus.

Now, without the need for plugins, we can exclude, include, and rearrange our page links at will, displaying a different menu for different pages, and with some code, even different users entirely.

How to Create a Custom WordPress Menu

Creating a custom menu is simple. Log into your WordPress Administrative Dashboard and select “Menus” under the appearance tab. From here, select the “Menu Name” input and give your new custom menu a title. Anything works, but let’s use “Main Menu” for the purposes of this tutorial. Once you’ve typed that in, hit the blue “Create Menu” button.

Alright, now we’ve got a new custom menu setup, but we need to add some links. There are three types of things we can add to our menu: Custom Links, Pages, and Categories. Custom Links let you link to external pages (great for incorporating network websites, related projects, and affiliate links). Pages lets you add WordPress pages to the menu. Categories lets you add links to a specific category archive.

To add a custom link, type in the destination URL then assign the menu item a label (the text that will appear in your navigation menu for that URL). Finally, click “Add to menu.”

To add a page or category, toggle the checkbox next to the item you want to add, then hit the “add to menu” button.

To modify a navigation item’s label, simply click on the item to expand its options, then change the “navigation label” input to whatever text you want to appear on your website. You can also assign each menu link a title attribute (text that appears when you hover over a link) for added SEO and usability benefit.

Tip: automatically include any new parent pages you make by checking the “automatically add top level pages” box next to the menu title.

How to Create Drop-Down Menus with WordPress

If your theme supports drop-down menus, you can easily arrange parents and children by simply clicking and dragging menu items into an indented position. Similar to moving widgets into a widget area or moving around boxes in the admin dashboard, gray rectangles will appear beneath each menu item, creating a position for you to drop the menu item into. From there, your theme will generate the necessary code for drop-down positioning between parent and child.

How to Use Custom WordPress Menus

Now that you’ve created your menu, you have to assign it to a location on your website. This is where the “theme locations” tab comes into play. Depending on the theme you’re using, there could be just one (twenty-eleven has just a main menu area) or multiple (headway themes gives you the ability to add as many navigation menus as you want on your website).

Choose the area you want to assign your menu to, and click the dropdown field. It will display all of the custom menus you’ve created. Select the menu you wish to assign (in our case, we only have Main Menu created, so we’ll use this one) and then hit the “save” button.

Theme locations that have no menu assigned will, by default, show all public pages that have been published.

How to Make Your Theme Custom Menu Compatible

When developing your own themes, developing your own theme locations could be important to the creation of your theme. The basics of integrating menu support involve defining menus (the name of our theme locations) and then calling them in our templates.

First, let’s define some menus. Add the following code to your theme’s functions.php file:

function register_my_menus() { register_nav_menus( array( 'top-menu' => __( 'Top Menu' ), 'footer-menu' => __( 'Footer Menu' ) ) ); } add_action( 'init', 'register_my_menus' );

This function assumes that we’re going to be building two menus, one for the main navigation and one for the footer. Now if we were to call the menu in our header.php or footer.php files, they would look like this:

<?php wp_nav_menu( array( 'theme_location' => 'top-menu' )); ?>

or

<?php wp_nav_menu( array( 'theme_location' => 'footer-menu' )); ?>

Creating your own menu locations for themes can be used in a variety of ways, especially if WordPress conditional tags are employed. For example, let’s say we wanted a user to see a menu only if they’re logged in. We could place the following code in the header.php file:

<?php if ( is_user_logged_in() ) { wp_nav_menu(array('theme_location'=>'user-menu')); } else { wp_nav_menu(array('theme_location'=>'main-menu')); } ?>

Conditional tags offer us the ability to show different menus on all kinds of system pages like archives, categories, specific pages, etc. You can find a list of conditional tags on the WordPress Codex.

How are you using custom menus to enhance your WordPress theme? What questions do you have about developing with custom menus? Share your thoughts and experiences in the comments below.

...
more →
Steve says: I would like the top level item (the one which appears in the menu bar) to not be a link or a page of any kind, but just a title...

Developing a Responsive Website Part 2: Navigation and Content

Now that we’ve got our background images squared away and set to break themselves down nicely across various devices and screen resolutions we can look in to populating our home page with some content.

Let’s begin with our header. I always like using a separate file for all the things that will stay uniform throughout my site, header, logo, navigation, etc. That way if I need to make a minor edit down the road I just have to edit the header file, which is then pulled in to every page with a simple PHP include script.

To start, let’s create a new php file, I named my “header.php” in order to keep things simple. In my header.php file I have placed my header, which simply contains the logo (I used the Developer Drive logo for this tutorial). After my logo is my navigation, a simple list will suffice for this tutorial. I chose a few basic links that someone may want to include in their site, but feel free to include what ever links are relative to you. My header.php code looks as follows.

<div id="logo"><img src="images/logo.png" alt="Developer Drive" /></div> <nav> <ul> <li><a href="#">Home</a></li> <li><a href="#">Portfolio</a></li> <li><a href="#">Services</a></li> <li><a href="#">About</a></li> <li><a href="#">Blog</a></li> <li class="last"><a href="#">Contact</a></li> </ul> </nav>

Go ahead and save that file, and feel free to close it since we’re done working in there.

Open your index.php file and let’s begin adding the content. We’ll start by adding a container div after our background image, then place the php include for our header, and finish it off by putting in our little blurb bubble. When all is said and done you should have something similar to this.

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width; initial-scale=1; maximum-scale=1"> <title>Responsive Web Design</title> <link href="main.css" rel="stylesheet"...
more →
Peter says: fyi, if you're working locally, you won't be able to run any php files unless you have Apache running locally (like WAMP of MAMP.)

Developing a Responsive Website: Background Images

A while back we took A Look at Responsive Web Design and how different designers utilize it in different ways.  Now that we’ve seen a few examples in action, let’s create a responsive website of our own. 

In this installment we’re going to set up the structure of our homepage and add in a few media queries that will help the site load quicker, navigate better, and keep our desired appearance across multiple devices, platforms, and resolutions.

Before we dive in to the HTML, let’s cover the “viewport” meta tag.  The Apple iPhone and iPod touch are programmed to automatically scale down websites in the iOS version of Safari. 

This will allow the user to see the site as it’s intended, but scaled down in order to fit in the smaller screen.  Since we’re going to create a media query specifically for the screen, we don’t want the iPhone to scale it.  The viewport meta tag will also allow you to set parameters on how much a viewer is able to zoom in or out, as well as what scale your site should initially load in.  For this tutorial we’re going to tell it not to scale at all.

Beginning with the HTML, you’ll notice that it’s pretty basic HTML5 stuff with the exception of our viewport meta tag and our main background div.

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Responsive Web Design</title> <link href="main.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="mainBG" class="homeContent" data-type="background"> </div><!--end div "mainBG"--> </body> </html>

With our HTML in place, let’s create our CSS file.  I like to reset my CSS by getting rid of unwanted margins, padding, and borders with this basic bit of code to start off my CSS file.

body, div, img, h1, h2, h3, h4, h5, h6, p, ul, ol, li, dl, dd, dt, blockquote, fieldset, legend, label, input, textarea { margin: 0; padding: 0; border: 0; } sh1, h2, h3, h4, h5, h6, p { margin: 0 0 1em 0; } h1{font-size: 200%;} h2{font-size: 170%;} h3{font-size: 160%;} h4{font-size: 140%;} h5{font-size: 120%;}

Now that we’re starting from scratch we can open up our body tag and add some style to it.  I set my background color to white and chose a dark gray for my text coloring.  Using a white background with black text often is too sharp of a contrast and can put a strain no the eyes of a viewer, going with a dark gray helps avoid that issue.

html, body { height: 100%; }

You’ll also notice that I set my font size using em, this is a crucial step when developing a responsive site because it is percentage based and will dynamically adjust itself on the fly.  If you were to set your font to a specific pixel size, once your site was scaled down to mobile phone dimensions it won’t flow as nicely with the rest of your design and may fill the entire screen, or the letters may overlap each other.

We can also add the style to our .homeContent class as well as our #mainBG id.  I’ve defined the height of the page, set the width to 100% and centered the content within the .homeContent class.  The #mainBG id pulls in our background image, which is a stock photo I got from 123RF.  I also set the background-size property to “cover”, which will scale the image to fill the screen and allow our background image to maintain proper proportions in larger resolutions.  The size of my “big.jpg” background image is 1920 x 1189.

.homeContent {    ...
more →
Brad Frost says: It seems like there are some opportunities to reduce the complexity of the code here. It's a good idea to start with a...