University of Oregon

PHP redirects if the headers have already been sent.

I ran in to a situation with some inherited code today.
The developer wanted to redirect users to a course listing page if they landed on a date/time listing that couldn’t be found.
See this code below; they check for an empty $dateTime var and create a log message before attempting to redirect the user.

if (empty($dateTime)) {
  $logger->err('DateTime with the id of '.$_REQUEST['dt_id'].' cannot be located.');
  Header( 'Location: course_list.php'); // Go back to the course list

Unfortunately the headers had already been sent to the browser and the Header function call was ignored and the user only saw a partially loaded web page with no body content.

In the past I had implemented a fall-back with a meta and js redirect but I thought that could be improved upon.
Stack Overflow had some nice responses to a previous question and one of them included Redirect function that checked if the headers were already sent: headers_sent().
I liked that. So I added my fall back to that function.

Next I swapped that Header function call with the Redirect function call:

if (empty($dateTime)) {
  $logger->err('DateTime with the id of '.$_REQUEST['dt_id'].' cannot be located.');
  Redirect('course_list.php'); // Go back to the course list

Problem solved.

Here’s the function (note: it’s wrapped in a function_exists() call to make sure I don’t declare this twice at any point):

  function Redirect($url, $code = 302) //from
    #echo 'redirecting';
    if (strncmp('cli', PHP_SAPI, 3) !== 0)
      #echo 'cli';
      if (headers_sent() !== true)
        if (strlen(session_id()) > 0) // if using sessions
            session_regenerate_id(true); // avoids session fixation attacks
            session_write_close(); // avoids having sessions lock other requests
        if (strncmp('cgi', PHP_SAPI, 3) === 0)
            header(sprintf('Status: %03u', $code), true, $code);
      header('Location: ' . $url, true, (preg_match('~^30[1237]$~', $code) > 0) ? $code : 302);
      } else { //headers have already been sent. Use Meta refresh with js location.href fallback
        <em>This page has moved.</em><br />
        If you are not redirected automatically please follow this link: <a href=\"<?php echo $url; ?>"><?php echo $url; ?></a>.
        <meta http-equiv="Refresh" content="1;
        URL=<?php echo $url; ?>">
        <script language=javascript>
        setTimeout("location.href='<?php echo $url; ?>'",1);
      }//end if headers_sent


PHP: html_entity_decode plus single quotes and other missing chars

I wanted to replace entities for use in a plain text email and html_entity_decode() ignored ‘‘’ and ‘’’. I dug around and found some ideas under get_html_translation_table:
I took the ideas of ‘yes at king22 dot com’ – 10-Apr-2007 03:33 and ‘Maurizio Siliani at trident dot it’ – 20-Jul-2007 03:43 to make a fast replacement of chars missed by html_entity_decode().

Added a cache-control header to the fmla database

The FMLA database front end wasn’t displaying the most recent participants when selecting letters. So I added some cache-control code to the header.

This tries to force the browser to reload the page every time, by passing the cache.
This only became a problem recently and it may be related to the latest firefox update.

Utilizing the LDAP Proxy to display directory details

We have an application that queries LDAP to verify affiliation and then captures the relevant data to enroll the user in a course.
We only store the username and user id, so LDAP is queried again when we want to send emails or view rosters that contain title, department, address, phone, etc…
I also wanted to pull in that directory info when we’re looking at a user’s info page but since the array returned from the ldap search only includes the attribute name and value, I copied the descriptions and usage (ie. ‘white pages’) from each attribute off the LDAP Information page and put it into an array. I added my own title to each attribute and appended some of my own uses (‘registration’,’system’). Then I put the array in a function that returns the these attributes (description:string, title:string, use:array(strings)) when called for each element.
So now when I display the user’s ldap info I can grab a human readable title and use the description for help text.
For example: getLdapDesc(‘uoempldept1’); returns
Description: Primary job department.
Title: Department
Use: (array)
0: white pages
1: registration

I only display fields designated as white page fields so that keeps all the other junk out of there.
I also ksorted the LDAP results array and the order is suitable.
The alternative would be to add an order element to the array but that’s overkill for my purposes.

Anyhow this way I’m more or less ready for any new attributes that may get added (or removed) from my account and I don’t have to hard code the display table.

If you think that’s of any value it would be nice to keep the array in a central location but better yet maybe we could get the title, descriptions and uses included in the ldap feed itself.

Here’s the code that outputs the directory info: (more…)

Simple Password protection using PHP

I needed to protect a page with something more challenging than javascript and less troublesome that .htaccess so I went looking for a quick php script that would do the trick with session management.

Here’s what I found: – Simple Password protection using PHP.

Unfortunately it was written in php4 with 4 year old html. So I updated it and it works great. Though I don’t know if it’s any less effort that .htaccess… but it’s quick

Drupal – modify the forum listing

We’ve decided not to display the commenter’s name on our forum comments. Initially I tried to accomplish this with css:


But that only takes care of hiding from view when reviewing comments. It also doesn’t remove it from the source and it shows up in the comment lists and rss feed as well.
So while I’m still using this on the forum post directly more drastic measures were needed to take care of the forum comment list pages…

Edit CSS and removing line breaks to process through js

I wanted to append the head of a doc with some styles but I didn’t want any line breaks.
So I used this function:

function removeLB($content){
	$content = str_replace(chr(10), " ", $content); //remove carriage returns
	$content = str_replace(chr(13), " ", $content); //remove carriage returns
	return $content;

That way I could edit with line breaks but send it through the jQuery append without.

Dynamically retrieve a protected pdf

My goal is to present the viewer with the latest course catalog pdf from our eLearning system.

Users can already log in and search for courses or drill down to a course and it’s details but there’s no overview readily available.

Administrators can open the latest course catalog in the client community.

Since we subscribe to all the courses I feel comfortable posting that catalog for our users.

But I don’t feel comfortable doing that by hand.

Enter php’s cURL.

  1. Open the page and determine the file to be downloaded.
  2. Download the file
  3. set the mimetype and return the file to the user

Simple right? Yes indeed, once you have your tools in order.

Dynamic vars in PHP

I was looking for the equivalent to ColdFusion’s setVariable for php and I found you can use {brackets} or double dollar signs.
Here’s a weird example:

Here’s a coldfusion example of the three types of setVar options I’ve used:

				&lt;!---  ---&gt;<!--- old outdated method -->
				&lt;!---  ---&gt;	<!--- newer method but #'s on the left side irk some people -->
					<!--- Works -->

Protected: Adding Shibboleth SSO to your drupal site

This content is password protected. To view it please enter your password below: