Archive

Archive for November, 2010

Autofocus on a textfield after page load [HTML]

November 30, 2010 Leave a comment

Problem

After page load, you want to put the focus on a textfield. For instance you have a form and you want to focus on the first field thus users can type immediately. See for instance the Google search page.

Solution

I tried several variations and this is what worked for me:

<body onload="document.login_form.email.focus()">

Here I suppose to have the following form:

<form name="login_form" action="process.php" method="POST">
    <input type="text" name="email" />
    ...
</form>

This tip is from here.

Categories: html, javascript Tags:

Send HTML form upon confirmation [HTML]

November 29, 2010 Leave a comment

Problem

Before sending a form, you want a confirmation from the user. If his/her reponse is positive, the form will be sent.

Solution

<form action="process.html" method="POST">
    <input type="button" onclick="if (confirm('Are you sure you want to submit this form?')) submit();" value="Submit">
</form>

This tip was taken from here.

Categories: html Tags: , ,

Disable Enter in HTML forms

November 29, 2010 Leave a comment

Problem

You have an HTML form with several submit buttons. Each button sets some variables that you need for processing the form correctly. You want to disable sending the form with Enter, you only want to allow the buttons.

Solution

<script type="text/javascript">

function stopRKey(evt) {
  var evt = (evt) ? evt : ((event) ? event : null);
  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
  if ((evt.keyCode == 13) && (node.type=="text"))  {return false;}
}

document.onkeypress = stopRKey;

</script> 

This tip is from here.

Categories: html Tags: ,

Accept positive integers only (string to int) [PHP]

November 26, 2010 Leave a comment

Problem

You have a form and in a field you want to accept positive integers only. However, in PHP the conversion from string to int is a bit strange:

$a = "1.3";
print (int)$a;		// => 1, no error
$a = "7 sins";
print (int)$a;		// => 7, no error
$a = "0";
print (int)$a;		// => 0
$a = "hello";
print (int)$a;		// => 0 again (Did we convert "0", or is it an error? We don't know.)

There is no exception raised if the input couldn’t be converted correctly.

Solution

if (!( is_numeric($val) and ((string)(int)$val === (string)$val) and ((int)$val > 0) )) 
{
    // not a positive integer
}

Read it like this: (a) $val must be numeric, and (b) the string $val must be converted into the same integer number, and (c) $val must be positive. If it’s not true (see the negation (!)), then $val is not a positive integer.

Credits

Inspired by a comment here.

Categories: php Tags: ,

Foreign keys with phpMyAdmin [MySQL]

November 25, 2010 Leave a comment

Problem

You are using MySQL and you want to set foreign keys with phpMyAdmin.

Solution

By default, phpMyAdmin uses the storage engine MyISAM. If you want foreign keys, you must use the engine InnoDB instead. Steps:

  • choose the table you want to modify
  • choose the tab Operations
  • here, change the Storage Engine to “InnoDB” (do this with all the tables in the current database)
  • choose the tab Structure, then follow the link Relation view
  • now you can set the foreign keys and decide what to do on delete/update
Categories: mysql Tags: ,

Hacking with BackTrack Linux

November 24, 2010 1 comment

I’ve been using Ubuntu for years but I just heard about BackTrack Linux today. It’s an Ubuntu-based distribution with a collection of security and forensics tools. You can install it on your HDD, run it on a live CD, or install it on a USB drive.

Links

Categories: ubuntu Tags: , , ,

Measure execution time in PHP

November 23, 2010 Leave a comment

Problem

You want to measure the execution time of a piece of code.

Method #1

$start = (float) array_sum(explode(' ',microtime())); 
#	
// PHP code whose execution time you want to measure
#
$end = (float) array_sum(explode(' ',microtime()));
print "Processing time: ". sprintf("%.4f", ($end-$start))." seconds."; 

I found this tip here.

Method #2 (update 20110205)

There is a simpler solution; you can also write $start = microtime(true). See the PHP documentation here.

I use this method for simple profiling. For this, I use a class:

class Common
{
   /**
    * Get current microtime as a float. Can be used for simple profiling.
    */
   static public function get_microtime() {
      return microtime(true);
   }

   /**
    * Return a string with the elapsed time.
    * Order of $end and $start can be switched.
    */
   static public function elapsed_time($end, $start) {
      return sprintf("Elapsed time: %.4f sec.", abs($end - $start));
   }
}

Usage example:

$profile_start = Common::get_microtime();
// code to be profiled comes here
$profile_end = Common::get_microtime();
print Common::elapsed_time($profile_end, $profile_start);
Categories: php Tags: , , ,

Validate an e-mail address in PHP [PHP]

November 23, 2010 Leave a comment

Problem

You have an input form with an “e-mail address” field and you want to validate the user input. You want a simple solution that checks if the e-mail is well-formed or not.

Solution

// from wordpress code: wp-includes/formatting.php
function is_email($user_email) 
{
	$chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";

	if (strpos($user_email, '@') !== false && strpos($user_email, '.') !== false) 
	{
		if (preg_match($chars, $user_email)) {
			return true;
		} else {
			return false;
		}
	} else {
		return false;
	}
}

Credits

I found this solution here in a comment.

Categories: php Tags: ,

Send e-mails from PHP via Gmail using Swift Mailer [PHP]

November 21, 2010 Leave a comment

Problem

You have a PHP script from which you want to send e-mails. You want an easy solution, and it’d be nice to send the e-mails via a Gmail account.

Solution

There are several ways to send e-mails from PHP. A sophisticated (and easy) solution is using Swift Mailer, which is an open-source library for sending e-mails from PHP 5 applications. See the docs here.

For my application I created a dedicated Gmail account, I refer to this as me@gmail.com. I put Swift Mailer in the following directory: ~/public_html/Swift. Here is the PHP code:

setUsername('me@gmail.com')
  ->setPassword('pass');

$mailer = Swift_Mailer::newInstance($transport);
$message = Swift_Message::newInstance('Wonderful Subject')
  ->setFrom(array('me@gmail.com' => 'MY NAME'))
  ->setTo(array('to@destination.com' => 'YOU'))
  ->setBody('This is the text of the mail sent by Swift using SMTP transport.');
//$attachment = Swift_Attachment::newInstance(file_get_contents('path/logo.png'), 'logo.png');
//$message->attach($attachment);
$numSent = $mailer->send($message);
printf("Sent %d message(s)\n", $numSent);
?>

Credits

This post is based on this thread.

Links
Some related links, I didn’t test them:

Categories: php Tags: , , ,

Setting rights for public_html

November 21, 2010 2 comments

Problem

In your ~/public_html you have a bunch of stuff and you want them to be accessible for the outside world. You don’t want to set the rights by hand for each file. What to do?

Solution

You need the following script:

#!/bin/bash

# setjog-here.sh

find . -type d -print0 | xargs -0 chmod 755
find . -type f -print0 | xargs -0 chmod 644
chmod 755 .
chmod u+x $0

It works recursively from the directory where you launched it. For folders it sets the right 755, for files 644.

Credits

When I started the university and we got an account to a UNIX machine, a friend of us (Mocsa) wrote a similar script for us. At that time we didn’t know anything about bash programming :)

Categories: bash Tags: ,
Follow

Get every new post delivered to your Inbox.

Join 61 other followers