Archive

Posts Tagged ‘user’

JavaScript Redirects

March 11th, 2009 No comments

There are two main ways in which to redirect the browser using JavaScript, both of which look at the location of the window object. These are the location.href property and location.replace function.

location.href

The following example will cause the page to redirect to another page, keeping the browser history. This might seem like a minor point, but if you redirect a user to another page they will be able to click back, which will mean that they are redirected again.

<script type="text/javascript">
window.location.href="http://www.talkincode.com/";
</script>

location.replace

This works in the same way as location.href, but in this case the redirection will occur and no history will be kept in the browser. This means that if a user visits the page with this code on they will instead see a different page. This means that the user can’t click on the back button and view the page that redirected them. Here is an example of its usage.

<script type="text/javascript">
window.location.replace("http://www.talkincode.com/");
</script>

You can also add this to a link by doing the following, although the user wouldn’t be able to get back to the page that redirected them.

<a href="javascript:window.location.replace('http://www.talkincode.com/')" title="Talk In Code">Talk In Code</a>

It should be noted here that you will probably want to avoid doing this sort of redirect unless you really have to. For example, if you relied on a JavaScript redirect in an important part of a form process and the user has JavaScript turned off then the process is quite likely to break. The ideal situation is to use server side scripts and redirect rules to force the browser to redirect in a more robust manner. Also, in terms of SEO using a JavaScript redirect is pointless as search engine spiders will probably not understand them.

A Useful Error Controller Class For Zend Framework Applications

December 23rd, 2008 7 comments

One useful function of any application is to report on any errors that occurred. Zend Framework comes with a nice error controller system that you can activate by creating an ErrorController class.

The following is an ErrorController class that I use. It detects what sort of error occurred and displays a message to the user. It will also email a detailed report of the error to the server admins.

class ErrorController extends Zend_Controller_Action
{
  public function errorAction()
  {
    // Ensure the default view suffix is used so we always return good
    // content
    $this->_helper->viewRenderer->setViewSuffix('phtml');
 
    // Grab the error object from the request
    $errors = $this->_getParam('error_handler');
 
    switch ($errors->type) {
      case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
      case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
        // 404 error -- controller or action not found
        $this->getResponse()->setHttpResponseCode(404);
        $this->view->message = 'Page not found';
        $this->view->code  = 404;
        if ($errors->type == Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER) {
          $this->view->info = sprintf(
                      'Unable to find controller "%s" in module "%s"',
                      $errors->request->getControllerName(),
                      $errors->request->getModuleName()
                    );
        }
        if ($errors->type == Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION) {
          $this->view->info = sprintf(
                      'Unable to find action "%s" in controller "%s" in module "%s"',
                      $errors->request->getActionName(),
                      $errors->request->getControllerName(),
                      $errors->request->getModuleName()
                    );
        }
        break;
      case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
      default:
        // application error
        $this->getResponse()->setHttpResponseCode(500);
        $this->view->message = 'Application error';
        $this->view->code  = 500;
        $this->view->info  = $errors->exception;
        break;
    }
 
    // send a mail to let someone know that there was a problem!
    $config = Zend_Registry::get('configuration');
    $tr = new Zend_Mail_Transport_Smtp($config->smtp);
    Zend_Mail::setDefaultTransport($tr);
 
    $mail = new Zend_Mail();
    $emailBody = "An error occurred in the system. The error message contained the following output:\n\n";
    $emailBody .= $this->view->message." (".$this->view->code.")\n\n";
    $emailBody .= "Zend Error Type: ".$errors->type."\n\n";
    $emailBody .= "REQUEST_URI: ".$_SERVER['REQUEST_URI']."\n\n";
    if ( isset($_SERVER['HTTP_REFERER']) ) {
      $emailBody .= "HTTP_REFERER: ".$_SERVER['HTTP_REFERER']."\n\n";
    }
    $emailBody .= "Stack trace: \n\n". $errors->exception->getTraceAsString()."\n\n";
 
    // find the user to blame!
    $username = Zend_Auth::getInstance()->getIdentity();
    $emailBody .= "This error was created by ".$username.".";
 
    $mail->setBodyText($emailBody);
    $mail->setFrom('anAddress@example.com', '');
    $mail->addTo($config->adminEmail, $config->adminName);
    $mail->setSubject('An Error Occured');
    // Email
    $mail->send();
 
    $this->view->title = 'Error!';
    $this->view->heading = 'Error!';
 
    // pass the environment to the view script so we can conditionally
    // display more/less information
    $this->view->env   = $this->getInvokeArg('env');
 
    // pass the actual exception object to the view
    $this->view->exception = $errors->exception;
 
    // pass the request to the view
    $this->view->request = $errors->request;
  }

This error controller relies on certain options that have been set up in your configuration file. Add the following options to your configuration file to get these options working.

smtp = my.smtpserver.com
adminEmail = admin@example.com
adminName = 'Your name'

To enable this just call the throwExceptions() function of the Zend_Controller_Front and pass it a value of false. This will cause the framework to look for an error controller rather than try to print out things.

$frontController = Zend_Controller_Front::getInstance();
$frontController->throwExceptions(false);

Finally, you need to add a view so that your errors will be displayed nicely. This will display more if the environment is set to 'test'.

<h3>Error has happened. Inside this application. Sorry about that.</h3>
<p><?=$this->message ?> (<?=$this->code ?>) </p>
<?
if( $this->env == 'test' ) {
 if ( isset($this->info ) ) { ?>
<? if ( 404 == $this->code ) { ?>
  <p><b>Reason:</b> <?= $this->info ?></p>
<? } elseif (500 == $this->code) { ?>
  <p>Bad server, naughty server!<br />No donut for you!</p>
  <p><img src="<?=$this->baseUrl();?>/images/donut.jpg" /></p>
  <h4>Exception information:</h4>
 <p><b>Message:</b> <?= $this->info->getMessage() ?></p>
 <h4>Stack trace:</h4>
 <pre><?= $this->info->getTraceAsString() ?></pre>
<? } ?>
<? } ?>
<? } ?>

Finding Out Where Users Have Come From In PHP

December 12th, 2008 No comments

It is sometimes a good idea to find out where users can come from. When PHP is run the $_SERVER superglobal is always available and if the user has clicked on a link and landed on your page then the HTTP_REFERER value will be set. You can retrieve it like this.

if ( isset($_SERVER[ HTTP_REFERER ]) ) {
 echo $_SERVER['HTTP_REFERER'];
}

Of course you might want to do something useful with this. For example, you might want to know what link a user clicked on when they broke your application.

Categories: PHP Tags: , , ,

The Google Chrome User Agent

September 3rd, 2008 No comments

As the new Google web browser was released last night (I’m writing this post using the new browser) I thought it would be good to update our readers on the user agent string that this web browser has.

The user agent of any browser can be found out by using the userAgent property of the navigator object. This is available in most modern browsers and is thankfully also present in Google Chrome.

navigator.userAgent

As an example the user agent for FireFox 3 on a Windows XP machine looks like this.

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-GB; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1

Using the same code, and the same machine, the user agent produced by Google Chrome is as follows.

Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.27 Safari/525.13

So detecting it should only be a case of looking for the word “chrome”. Just like this:

var ischrome = navigator.userAgent.indexOf("Chrome")? true : false;

If you want to see what the user agent is on your machine then past this code into a web page and hit refresh. It is quite a basic bit of code and should work in most browsers.

<span id="useragent"></span>
<script type="text/javascript">
document.getElementById('useragent').innerHTML = navigator.userAgent;
</script>

Simple Trick To Run Last Command As Sudo

April 10th, 2008 No comments

You can often forget what you are not running as a super user, so if you type in a command that you can’t run with your current set of privileges it will tell give you a permission denied response.

An alternative is to use the !! command to run the last command in the .bash_history. Use this with the sudo command to run the last command as a super user.

> command
Permission denied
 
> sudo !!

Categories: Unix/Linux Tags: , , , ,