Tutorial Simple Zipcode Range Tester

by in , 0

This regex below tests the provided zip code if it starts with the numbers 096 and that there are exactly 2 numbers after it. If it does, it echos Yes, if not, it echos No. In this test case, it would echo Yes.

<?php
$zipcode='09607';
echo 'Zipcode in range?<br />';
if(preg_match('/^096[0-9]{2}$/', $zipcode))
       echo "Yes";
else
       echo "No";
?>

Tutorial Server Side Image Resizer

by in , 0

The code uses PHP to resize an image (currently only jpeg). Using this method, the resized image is of much better quality than a browser-side resizing. The file size of the new downsized image is also smaller (quicker to download).

The code comes in two parts:

imageResizer() is used to process the image loadimage() inserts the image url in a simpler format
<?php

   function imageResizer($url, $width, $height) {

		header('Content-type: image/jpeg');

		list($width_orig, $height_orig) = getimagesize($url);

		$ratio_orig = $width_orig/$height_orig;

		if ($width/$height > $ratio_orig) {
		  $width = $height*$ratio_orig;
		} else {
		  $height = $width/$ratio_orig;
		}

		// This resamples the image
		$image_p = imagecreatetruecolor($width, $height);
		$image = imagecreatefromjpeg($url);
		imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig);

		// Output the image
		imagejpeg($image_p, null, 100);
		
	}

	//works with both POST and GET
	$method = $_SERVER['REQUEST_METHOD'];
	
	if ($method == 'GET') {

		imageResize($_GET['url'], $_GET['w'], $_GET['h']);
		
	 } elseif ($method == 'POST') {

	    imageResize($_POST['url'], $_POST['w'], $_POST['h']);
	 }

	// makes the process simpler
	function loadImage($url, $width, $height){
         echo 'image.php?url=', urlencode($url) ,
         '&w=',$width,
         '&h=',$height;
	}

?>

Usage

Above code would be in a file called image.php.

Images would be displayed like this:

<img src="<?php loadImage('image.jpg', 50, 50) ?>"

Tutorial Separate First and Last Name

by in , 0

$name = "John S Smith";

list($fname, $lname) = split(' ', $name,2);

echo "First Name: $fname, Last Name: $lname";

Works with or without middle name.

Tutorial Send Email

by in , 0

1) HTML Form with Inputs

<form action="" method="post">
  <label for="name">Name:</label>
  <input type="text" name="name" id="name" />

  <label for="Email">Email:</label>
  <input type="text" name="email" id="email" />

  <label for="Message">Message:</label><br />
  <textarea name="message" rows="20" cols="20" id="message"></textarea>

  <input type="submit" name="submit" value="Submit" />
</form>

2) Process with PHP

This could be in a seperate file (e.g. sendemail.php) in which you'd set the action URL of the form to go there. Or, have the form submit to itself (leave action URL blank) and test for one of the values of the form being POSTed and process there.

<?php
       // from the form
       $name = trim(strip_tags($_POST['name']));
       $email = trim(strip_tags($_POST['email']));
       $message = htmlentities($_POST['message']);

       // set here
       $subject = "Contact form submitted!";
       $to = 'your@email.com';

       $body = <<<HTML
$message
HTML;

       $headers = "From: $email\r\n";
       $headers .= "Content-type: text/html\r\n";

       // send the email
       mail($to, $subject, $body, $headers);

       // redirect afterwords, if needed
       header('Location: thanks.html');
?>

3) Test it

And make sure to keep up with security news around the web.

Tutorial Send a Text Message

by in , 0

You'll need a TextMagic account and to download their PHP helper which they provide after signing up.

// Include the TextMagic PHP lib
require('textmagic-sms-api-php/TextMagicAPI.php');

// Set the username and password information
$username = 'myusername';
$password = 'mypassword';

// Create a new instance of TM
$router = new TextMagicAPI(array(
	'username' => $username,
	'password' => $password
));

// Send a text message to '999-123-4567'
$result = $router->send('Wake up!', array(9991234567), true);

// result:  Result is: Array ( [messages] => Array ( [19896128] => 9991234567 ) [sent_text] => Wake up! [parts_count] => 1 )

Reference URL

Tutorial Sanitize Database Inputs

by in , 0

1) Function for stripping out malicious bits

<?php
function cleanInput($input) {
 
  $search = array(
    '@<script[^>]*?>.*?</script>@si',   // Strip out javascript
    '@<[\/\!]*?[^<>]*?>@si',            // Strip out HTML tags
    '@<style[^>]*?>.*?</style>@siU',    // Strip style tags properly
    '@<![\s\S]*?--[ \t\n\r]*>@'         // Strip multi-line comments
  );
 
    $output = preg_replace($search, '', $input);
    return $output;
  }
?>

2) Sanitization function

Uses the function above, as well as adds slashes as to not screw up database functions.

<?php
function sanitize($input) {
    if (is_array($input)) {
        foreach($input as $var=>$val) {
            $output[$var] = sanitize($val);
        }
    }
    else {
        if (get_magic_quotes_gpc()) {
            $input = stripslashes($input);
        }
        $input  = cleanInput($input);
        $output = mysql_real_escape_string($input);
    }
    return $output;
}
?>

Usage

<?php
  $bad_string = "Hi! <script src='http://www.evilsite.com/bad_script.js'></script> It's a good day!";
  $good_string = sanitize($bad_string);
  // $good_string returns "Hi! It\'s a good day!"

  // Also use for getting POST/GET variables
  $_POST = sanitize($_POST);
  $_GET  = sanitize($_GET);
?>

Reference URL

Tutorial Return Only One Variable from MySQL Query

by in , 0

Function

function mysql_get_var($query,$y=0){
       $res = mysql_query($query);
       $row = mysql_fetch_array($res);
       mysql_free_result($res);
       $rec = $row[$y];
       return $rec;
}

Usage

$name = mysql_get_var("SELECT name from people where email = 'roger@freekrai.net'");

Will return the name field, so what gets returned will be "Roger" (if that was my name in the database).

Reference URL