Friday, May 30, 2008

How to Encrypt Passwords in the Database

If you are developing a password-protected web site, you have to make a decision about how to store user password information securely.

What is "secure," anyway? Realize that the data in your database is not safe. What if the password to the database is compromised? Then your entire user password database will be compromised as well. Even if you are quite certain of the security of your database, your users' passwords are still accessible to all administrators who work at the Web hosting company where your database is hosted. Scrambling the passwords using some home-brewed algorithm may add some obscurity but not true "security." Another approach would be to encrypt all passwords in your database using some industry-standard cipher, such as the Message-Digest Algorithm 5 (MD5).

MD5 encryption is a one-way hashing algorithm. Two important properties of the MD5 algorithm are that it is impossible to revert back an encrypted output to the initial, plain-text input, and that any given input always maps to the same encrypted value. This ensures that the passwords stored on the server cannot be deciphered by anyone. This way, even if an attacker gains reading permission to the user table, it will do him no good.

MD5 does have its weaknesses. MD5 encryption is not infallible: if the password is not strong enough, a brute force attack can still reveal it. So, you can ask: "Why should I use MD5 if I know it is not the most secure?" The answer is fairly straightforward: it's fast, it's easy, and it can be powerful if salted. The greatest advantage of MD5 is its speed and ease of use.

It is vitally important to understand that password encryption will not protect your website, it can protect your passwords only. If your website does not have sufficient protection, password encryption will not make it safe from cracking. If your system has been cracked, a hacker can inflict a irreparable damage to it and also gain an access to confidential information, including passwords database. But if you store this information encrypted, hackers practically cannot make use of it. Cracking an encrypted password takes a large amount of time and processing power, even on today's computers.

So, let's start. First of all, you need to add a new account to your database. The following code allows to do it.

<?php

define("DB_SERVER", "localhost");

define("DB_USER", "your_name");

define("DB_PASS", "your_pass");

define("DB_NAME", "your_db");

define("TBL_USERS", "users_table_name");



$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());

mysql_select_db(DB_NAME, $connection) or die(mysql_error());



...



function addNewUser($username, $password){

global $connection;

$password = md5($password);

$q = "INSERT INTO ".TBL_USERS." VALUES ('$username', '$password')";

return mysql_query($q, $connection);

}

?>

Now, when a new user completes the registration form, his password will be encrypted automatically.

After that we should write code that validates a given username/password pair.


<?php

function checkUserPass($username, $password){

global $connection;



$username = str_replace("'","''",$username)

$password = md5($password);



// Verify that user is in database

$q = "SELECT password FROM ".TBL_USERS." WHERE username = '$username'";

$result = mysql_query($q, $connection);

if(!$result || (mysql_numrows($result) < 1)){

return 1; //Indicates username failure

}



// Retrieve password from result

$dbarray = mysql_fetch_array($result);



// Validate that password is correct

if($password == $dbarray['password']){

return 0; //Success! Username and password confirmed

}

else{

return 1; //Indicates password failure

}

}

?>


And what if you already have users' database ready and want to start using encrypted passwords? To do it, you need to write encypt.php script with the following code and run it in your browser.



<?php

define("DB_SERVER", "localhost");

define("DB_USER", "your_name");

define("DB_PASS", "your_pass");

define("DB_NAME", "your_db");

define("TBL_USERS", "users_table_name");

define("FLD_USER", "username_field_name");

define("FLD_PASS", "password_field_name");



set_magic_quotes_runtime(0);



$connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());

mysql_select_db(DB_NAME, $connection) or die(mysql_error());



$q = "SELECT ".FLD_PASS.",".FLD_USER." FROM ".TBL_USERS."";

$result = mysql_query($q, $connection);



$total=0;

$enc=0;



$doencrypt=false;

if (@$_REQUEST["do"]=="encrypt")

$doencrypt=true;



while($data = mysql_fetch_array($result))

{

if ($doencrypt)

{

$total++;

if (!encrypted($data[0]))

{

$q="UPDATE ".TBL_USERS." SET ".FLD_PASS."='".md5($data[0])."' where ".FLD_USER."='".

str_replace("'","''",$data[1])."'";

mysql_query($q, $connection);

}

$enc++;

}

else

{

$total++;

if (encrypted($data[0]))

$enc++;

}

}



function encrypted($str)

{

if (strlen($str)!=32)

return false;



for($i=0;$i<32;$i++)

if ((ord($str[$i])<ord('0') || ord($str[$i])>ord('9')) && (ord($str[$i])<ord('a') || ord($str[$i])>ord('f')))

return false;



return true;

}

?>



<html>

<head><title>Encrypt passwords</title></head>

<body>

Total passwords in the table - <?php echo $total; ?><br>

<?php if($enc==$total && $total>0) { ?>

All passwords are encrypted.

<?php } else if($total>0) { ?>

Unencrypted - <?php echo $total-$enc; ?><br><br>

Click "GO" to encrypt <?php echo $total-$enc; ?> passwords.<br>

WARNING! There will be no way to decipher the passwords.<br>

<input type=button value="GO" onclick="window.location='encrypt.php?do=encrypt';">

<?php } ?>

</body>

</html>


How to Create Thumbnail Images using PHP

This tutorial will describe how to create thumbnail images on the fly using PHP. Furthermore you will learn how to process a whole folder of images and create their thumbnails. Since this requires the GD library, you will need an installation of PHP with at least GD 2.0.1 enabled.

Below we will create a PHP script that contains two functions. The first one scans a provided directory for any .JPG images and, for each one, creates a thumbnail in the specified folder using the GD image functions. The second function creates an HTML file in the same directory as the script, which contains all of the thumbnails with links to the original images. This could be the basis of advanced photo gallery software.

The code below creates a function named createThumbs that will get three parameters. The first and the second is correspondingly the path to the directory that contains original images and the path to the directory in which thumbnails will be placed. The third parameter is the width you want for the thumbnail images.




<?php

function createThumbs( $pathToImages, $pathToThumbs, $thumbWidth )

{

// open the directory

$dir = opendir( $pathToImages );



// loop through it, looking for any/all JPG files:

while (false !== ($fname = readdir( $dir ))) {

// parse path for the extension

$info = pathinfo($pathToImages . $fname);

// continue only if this is a JPEG image

if ( strtolower($info['extension']) == 'jpg' )

{

echo "Creating thumbnail for {$fname} <br />";



// load image and get image size

$img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );

$width = imagesx( $img );

$height = imagesy( $img );



// calculate thumbnail size

$new_width = $thumbWidth;

$new_height = floor( $height * ( $thumbWidth / $width ) );



// create a new temporary image

$tmp_img = imagecreatetruecolor( $new_width, $new_height );



// copy and resize old image into new image

imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );



// save thumbnail into a file

imagejpeg( $tmp_img, "{$pathToThumbs}{$fname}" );

}

}

// close the directory

closedir( $dir );

}

// call createThumb function and pass to it as parameters the path

// to the directory that contains images, the path to the directory

// in which thumbnails will be placed and the thumbnail's width.

// We are assuming that the path will be a relative path working

// both in the filesystem, and through the web for links

createThumbs("upload/","upload/thumbs/",100);

?>



At first we open the directory with images and iterate through it, looking for all .JPG files. Next we create thumbnails for each image in the directory. To create a thumbnail, we read in the file using the imagecreatefromjpeg() function and calculate the new thumbnail size. imagesx() and imagesy() functions return the width and height of the image respectively. Next we create a new image using the imagecreatetruecolor(). Finally, we copy and resize the original file with the imagecopyresized() function and save thumbnail with imagejpeg().

The second part of the code creates the function named createGallery which gets two parameters (the relative paths to the directories in which images and thumbnails are stored) and creates an HTML page which contains all of the thumbnails with links to the original images.

<?php

function createGallery( $pathToImages, $pathToThumbs )

{

echo "Creating gallery.html <br />";



$output = "<html>";

$output .= "<head><title>Thumbnails</title></head>";

$output .= "<body>";

$output .= "<table cellspacing=\"0\" cellpadding=\"2\" width=\"500\">";

$output .= "<tr>";



// open the directory

$dir = opendir( $pathToThumbs );



$counter = 0;

// loop through the directory

while (false !== ($fname = readdir($dir)))

{

// strip the . and .. entries out

if ($fname != '.' && $fname != '..')

{

$output .= "<td valign=\"middle\" align=\"center\"><a href=\"{$pathToImages}{$fname}\">";

$output .= "<img src=\"{$pathToThumbs}{$fname}\" border=\"0\" />";

$output .= "</a></td>";



$counter += 1;

if ( $counter % 4 == 0 ) { $output .= "</tr><tr>"; }

}

}

// close the directory

closedir( $dir );



$output .= "</tr>";

$output .= "</table>";

$output .= "</body>";

$output .= "</html>";



// open the file

$fhandle = fopen( "gallery.html", "w" );

// write the contents of the $output variable to the file

fwrite( $fhandle, $output );

// close the file

fclose( $fhandle );

}

// call createGallery function and pass to it as parameters the path

// to the directory that contains images and the path to the directory

// in which thumbnails will be placed. We are assuming that

// the path will be a relative path working

// both in the filesystem, and through the web for links

createGallery("upload/","upload/thumbs/");

?>


First, we open the directory with thumbnails. Next we iterate through files in the directory and put the HTML into a string variable. The variable contents then written into a file using fopen(), fwrite(), and fclose() functions.

As you can see, adding on the fly generated thumbnails to your website with GD library and PHP is quite easy to accomplish.



PHP: Sending Email (Text/HTML/Attachments)

Sending a Simple Text Email
At first let's consider how to send a simple text email messages. PHP includes the mail() function for sending email, which takes three basic and two optional parameters. These parameters are, in order, the email address to send to, the subject of the email, the message to be sent, additional headers you want to include and finally an additional parameter to the Sendmail program. The mail() function returns True if the message is sent successfully and False otherwise. Have a look at the example:

<?php

//define the receiver of the email

$to = 'youraddress@example.com';

//define the subject of the email

$subject = 'Test email';

//define the message to be sent. Each line should be separated with \n

$message = "Hello World!\n\nThis is my first mail.";

//define the headers we want passed. Note that they are separated with \r\n

$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";

//send the email

$mail_sent = @mail( $to, $subject, $message, $headers );

//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"

echo $mail_sent ? "Mail sent" : "Mail failed";

?>

As you can see, it very easy to send an email. You can add more receivers by either adding their addresses, comma separated, to the $to variable, or by adding cc: or bcc: headers. If you don't receive the test mail, you have probably installed PHP incorrectly, or may not have permission to send emails.

Sending HTML Email
The next step is to examine how to send HTML email. However, some mail clients cannot understand HTML emails. Therefore it is best to send any HTML email using a multipart construction, where one part contains a plain-text version of the email and the other part is HTML. If your customers have HTML email turned off, they will still get a nice email, even if they don't get all of the HTML markup. Have a look at the example:

<?php

//define the receiver of the email

$to = 'youraddress@example.com';

//define the subject of the email

$subject = 'Test HTML email';

//create a boundary string. It must be unique

//so we use the MD5 algorithm to generate a random hash

$random_hash = md5(date('r', time()));

//define the headers we want passed. Note that they are separated with \r\n

$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";

//add boundary string and mime type specification

$headers .= "\r\nContent-Type: multipart/alternative; boundary=\"PHP-alt-".$random_hash."\"";

//define the body of the message.

ob_start(); //Turn on output buffering

?>

--PHP-alt-<?php echo $random_hash; ?>

Content-Type: text/plain; charset="iso-8859-1"

Content-Transfer-Encoding: 7bit



Hello World!!!

This is simple text email message.



--PHP-alt-<?php echo $random_hash; ?>

Content-Type: text/html; charset="iso-8859-1"

Content-Transfer-Encoding: 7bit



<h2>Hello World!</h2>

<p>This is something with <b>HTML</b> formatting.</p>



--PHP-alt-<?php echo $random_hash; ?>--

<?

//copy current buffer contents into $message variable and delete current output buffer

$message = ob_get_clean();

//send the email

$mail_sent = @mail( $to, $subject, $message, $headers );

//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"

echo $mail_sent ? "Mail sent" : "Mail failed";

?>

In the preceding example we add one additional header of Content-type:multipart/alternative and boundary string that marks the different areas of the email. Note that the content type of the message itself is sent as a mail header, while the content types of the individual parts of the message are embedded in the message itself. This way, mail clients can decide which part of the message they want to display.

Sending Email with Attachment
The last variation that we will consider is email with attachments. To send an email with attachment we need to use the multipart/mixed MIME type that specifies that mixed types will be included in the email. Moreover, we want to use multipart/alternative MIME type to send both plain-text and HTML version of the email. Have a look at the example:

<?php

//define the receiver of the email

$to = 'youraddress@example.com';

//define the subject of the email

$subject = 'Test email with attachment';

//create a boundary string. It must be unique

//so we use the MD5 algorithm to generate a random hash

$random_hash = md5(date('r', time()));

//define the headers we want passed. Note that they are separated with \r\n

$headers = "From: webmaster@example.com\r\nReply-To: webmaster@example.com";

//add boundary string and mime type specification

$headers .= "\r\nContent-Type: multipart/mixed; boundary=\"PHP-mixed-".$random_hash."\"";

//read the atachment file contents into a string,

//encode it with MIME base64,

//and split it into smaller chunks

$attachment = chunk_split(base64_encode(file_get_contents('attachment.zip')));

//define the body of the message.

ob_start(); //Turn on output buffering

?>

--PHP-mixed-<?php echo $random_hash; ?>

Content-Type: multipart/alternative; boundary="PHP-alt-<?php echo $random_hash; ?>"



--PHP-alt-<?php echo $random_hash; ?>

Content-Type: text/plain; charset="iso-8859-1"

Content-Transfer-Encoding: 7bit



Hello World!!!

This is simple text email message.



--PHP-alt-<?php echo $random_hash; ?>

Content-Type: text/html; charset="iso-8859-1"

Content-Transfer-Encoding: 7bit



<h2>Hello World!</h2>

<p>This is something with <b>HTML</b> formatting.</p>



--PHP-alt-<?php echo $random_hash; ?>--



--PHP-mixed-<?php echo $random_hash; ?>

Content-Type: application/zip; name="attachment.zip"

Content-Transfer-Encoding: base64

Content-Disposition: attachment



<?php echo $attachment; ?>

--PHP-mixed-<?php echo $random_hash; ?>--



<?php

//copy current buffer contents into $message variable and delete current output buffer

$message = ob_get_clean();

//send the email

$mail_sent = @mail( $to, $subject, $message, $headers );

//if the message is sent successfully print "Mail sent". Otherwise print "Mail failed"

echo $mail_sent ? "Mail sent" : "Mail failed";

?>

As you can see, sending an email with attachment is easy to accomplish. In the preceding example we have multipart/mixed MIME type, and inside it we have multipart/alternative MIME type that specifies two versions of the email. To include an attachment to our message, we read the data from the specified file into a string, encode it with base64, split it in smaller chunks to make sure that it matches the MIME specifications and then include it as an attachment.

Saturday, May 24, 2008

PHP substr() Function

The substr() function returns a part of a string.

<?php  echo substr("Hello world!",6);  ?>

<?php  echo substr("Hello world!",6,5);  ?>

PHP strstr() Function

The strstr() function searches for the first occurrence of a string inside another string.

This function returns the rest of the string (from the matching point), or FALSE, if the string to search for is not found.

<?php  echo strstr("Hello world!","world");  ?>

<?php  echo strstr("Hello world!",111);  ?>


Calculating difference between two dates using PHP

If you want to get the difference between to dates use this script:
Example:

<?


$date1 = date("Y/m/d");

$date2 = date("Y/m/d");


echo datediff($date1, date2);


function datediff($sdate,$edate){

$rs = $this->execute("select to_days('$edate') - to_days('$sdate') as diff");

if($row = $this->row($rs)){

return $row["diff"];

}else{

return "0";

}

}


?>

Add Days in PHP Date,

<?


$edate = date('Y/m/d');


$ndate = adddays( $edate,1);

$pdate1 = adddays( $edate,-1);




function adddays($date,$days){

$rs = $this->execute("select DATE_FORMAT(DATE_ADD('$date',INTERVAL $days DAY),'%Y-%m-%d') as newdate");

if($row = $this->row($rs)){

return $row["newdate"];

}else{

return "0000-00-00";

}

}


?>

Date Formatting in PHP, Change Date Format

you can easily change date format (mm/dd/yy) to (dd/mm/yy) ...

Example:

<?


formatdate(date('Y/m/d'));


function formatdate($mysql_stamp,$type=1)

{

//$type = 1 date + time

//$type = 2 date

//$type = 3 time

// split mysql DATETIME stamp into date and time

if($mysql_stamp==""){

return "";

}

@list($date, $time) = split ('[ ]', $mysql_stamp);

@list($year, $month, $day) = split ('[-]', $date);

if( isset($time) && $time != "" )

{

list($hour, $minute, $second) = split ('[:]', $time);

if($hour>=12)

{

$ext = "PM";

$hour = $hour - 12;

}

else

{

$ext = "AM";

}

$time = " ".$hour.":".$minute." ".$ext;

}

else

{

$hour="";

$minute= "" ;

$ext = "";

$time = "";

}



if($type == 1)

$formatted_stamp = "$day/$month/$year".$time;

elseif($type==2)

{

$formatted_stamp = "$day/$month/$year";

}

elseif($type==3)

$formatted_stamp = $time;


return $formatted_stamp;

}


?>

Create a Scrolling News Ticker in PHP

This document describes how to Create a Scrolling News Ticker in PHP. The script is compatible with both Internet Explorer and FireFox.

You can add this scrolling news ticker with your own text in your web pages.
Features:

  • Easy to embed into an HTML document;
  • Compatible with Internet Explorer and FireFox;
  • Full PHP & JavaScript: no plugin
  • Supports full HTML, including images, links and any other tags;
  • Smooth scrolling;
  • Very small script - fast to download;
  • Easy to customize;
  • Free for personal and commercial use.
FREE TO DOWNLOAD

Index.php

<html>

<body>

<table border="1" cellpadding="0" cellspacing="0" width="100%">

<tr>

<td><marquee behavior="scroll" scrollamount="3" scrolldelay="10" onMouseOver="stop()" onMouseOut="start()"><span id="scrollingtext">asd</span></marquee></td>

</tr>

</table>

<script language="javascript">

var xmlHttp


function GETTEXT()

{

te = document.getElementById("scrollingtext").innerHTML;

xmlHttp=GetXmlHttpObject();

if (xmlHttp==null)

{

alert ("Your browser does not support AJAX!");

return;

}

var url="gettext.php";

url=url+"?te="+te;

url=url+"&sid="+Math.random();

xmlHttp.onreadystatechange=stateChanged;

xmlHttp.open("GET",url,true);

xmlHttp.send(null);

//alert("calling");

setTimeout("GETTEXT()",5000);

}

GETTEXT();

function stateChanged()

{

if (xmlHttp.readyState==4){

if(xmlHttp.responseText!=""){

document.getElementById("scrollingtext").innerHTML=xmlHttp.responseText;

}

}

}


function GetXmlHttpObject()

{

var xmlHttp=null;

try

{

// Firefox, Opera 8.0+, Safari

xmlHttp=new XMLHttpRequest();

}

catch (e)

{

// Internet Explorer

try

{

xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");

}

catch (e)

{

xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");

}

}

return xmlHttp;

}

</script>

</body>

</html>



gettext.php
<?

$extext = $_GET["te"];

$text_file = "ticker.txt";

if(!($fp = fopen($text_file, "r"))) die ("Cannot open $counter_file.");

$list = fread($fp, filesize ($text_file));

if($extext!=$list){

echo $list;

}

fclose($fp);

?>

Create ticker.txt file
this file contains your scrolling text...

Thursday, May 22, 2008

Put watermark on images using PHP

If you are a professional or a newbie photographer you will probably want to protect your photos from being stolen and used for free. Using PHP you can create different types of watermarks on all of your images. I am going to show you a way how to dynamically put a text messages on your images. What you need is a JPG image file and a font file used for generate the watermark message. I am going to use arial font which you can also download.

Below you can find a watermarkImage() image function which takes 3 parameters ($SourceFile, $WaterMarkText, $DestinationFile) and creates an watermarked image from the source image specified. The first parameter - $SourceFile - is the full server path to the JPG image that you are going to watermark. The second one - $WaterMarkText - is the text message that you want to use for the watermark. And the last parameter - $DestinationFile - can either be blank or full server path to a new file which will be the source file with watermark text on it. What this function does is to read the source file, then create a new image object (using the imagecopyresampled() function). Then using the Arial.ttf font file and the imagettftext() function it writes the WaterMarkText onto the image. The last IF statement checks if it should save a new watermarked file or should just display it on the screen.

function watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile) {
list($width, $height) = getimagesize($SourceFile);
$image_p = imagecreatetruecolor($width, $height);
$image = imagecreatefromjpeg($SourceFile);
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height);
$black = imagecolorallocate($image_p, 0, 0, 0);
$font = 'arial.ttf';
$font_size = 10;
imagettftext($image_p, $font_size, 0, 10, 20, $black, $font, $WaterMarkText);
if ($DestinationFile<>'') {
imagejpeg ($image_p, $DestinationFile, 100);
} else {
header('Content-Type: image/jpeg');
imagejpeg($image_p, null, 100);
};
imagedestroy($image);
imagedestroy($image_p);
};
?>

You need to download the arial.ttf file and upload it on your server. Then create a new PHP file and copy and paste the above function in it. Next 4 lines are used to set the Source file, Watermark text message and Destination file. If you want to just display the watermarked image you need to leave the $DestinationFile variable empty ($DestinationFile=''; ). Also please make sure that for source file and destination file you include the full server path and the image file name. If you want to change the position of the watermark message on your images you can chage that line imagettftext($image_p, $font_size, 0, 10, 20, $black, $font, $WaterMarkText);

$SourceFile = '/home/user/www/images/image1.jpg';
$DestinationFile = '/home/user/www/images/image1-watermark.jpg';
$WaterMarkText = 'Copyright phpJabbers.com';
watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile);
?>

Protecting Your Images with PHP Watermarks

As an amateur photographer, I've been looking for practical ways to display my work as well as protect them from potential copyright infringement. There are a hundred ways to superimpose a watermark on an image, but this requires a process of doing that to each of your images before you place them on your website. Being the lazy fellow that I am, I was seeking a way for this to occur on-the-fly without me having to do anything but scale my preview/thumbnail images (which I do automatically with my gallery software).

I investigated various ways to use CGI to handle this, which is an easy way to do it, but it can lead to unweidly URLs. A simple method might be to link to is such as this:

Basically, you're passing the CGI the file you want to have watermarked and the .cgi does its thing, printing the header "Content-type: image/jpeg" and then the JPEG data to standard out. I would have to come up with a way to have the CGI do this watermarking automatically. It would work, but its inelegant and makes for ugly URLs. Close, but no cigar.

Another method I came up with was using PHP to do a similar function, instead of using CGI, I would use PHP's internal image manipulation routines to generate watermarked image. Unfortunately, the URL would essentially be the same:

Then it dawned on me that because my URLs for this would be fairly consistent, why couldn't I use Apache's Mod_Rewrite module to automatically convert my normal image source tags into the php URL and mask this from the browser?

This method would get me two things:

1) The URL for the image would be normal, such as
2) Any direct requests for the image would result in a watermarked image

So if a person tried to do something like:

wget http://www.mysite.com/image/statue.jpg

They would be served up the watermarked image, despite the fact that the original statue.jpg on the server is unmodified!

The PHP script that watermarks the image

The PHP script, which I call "wm.php" that I use for watermarking was written by "thunder", but was modified with some pathing enhancements by myself. There are only a few variables needed to be changed in the script, the base directory of your HTML and the name of the watermark image you wish to use, which should be located in that base directory.

Setting up Apache and Mod_Rewrite to "mask" the PHP


Mod_rewrite can be configured in your server's httpd.conf or your local .htaccess. If you don't have access to httpd.conf, modifying your .htaccess is your only alternative.

Lets say my URL is something like this:

http://www.bigisp.com/users/johndoe/index.html

Basically, the rule is pretty straight forward:

RewriteEngine on
RewriteBase /johndoe
RewriteRule ^(watermarked.*)/(.*\.[jJ].*)$ /~liem/wm.php?p=$1&i=$2

I'm using the RewriteBase directive here because all of my documents and images are based out of the /johndoe/ directory.

Because I won't want all of the images on my site watermarked, I only put the images I want to be watermarked in the "watermarked" subdirectory. The path and filename information are passed to the wm.php script so that they're properly handled.


Wednesday, May 21, 2008

PHP file upload Script :: online picture upload

File upload is very common requirement of many web sites. We may require to upload pictures online to websites. Image upload is very common requirement and many sites are using this to allow members or visitors to upload files. Picture rating, picture gallery site uses this feature to allow multiple file uploads. What we need to allow file upload or online picture upload to a site? This file upload script explained in a step by step way to accomplish this online uploading to a web server. We can even create thumbnail images of the uploaded image file by php. The main requirement is to allow the members to browse the local computer and point to the file required for uploading.

* Check the file if it is allowed for upload or not. We can check for file size, file extension, file name etc.
* Copy the file to server.
* Place the file in required directory and then give necessary file permission.

Before starting we must add file permission to the directory where we plan to store the files after uploading it. Let us give the directory name upload and give write permission to it. If it is a Window server nothing is required and by default window gives all permissions. For Linux and Uinx we have to give write (Chmod) permission to allow uploaded files to store.

If you are uploading large files then read about maximum file execution time allowed and its adjuestments.

Let us add the html code to show the browse button for the visitors to point to file required for uploading. Here is the code


Upload this file:



This html code will display a text area with file upload button. The form tag is bit different than the normal form tag used ( see the encrypte =).

Now let us go to the php part to handle the uploaded file. We have In PHP 3, the following variables will be defined within the destination script upon a successful upload, assuming that register_globals is turned on in php.ini. If track_vars is turned on, they will also be available in PHP within the global

array $HTTP_POST_VARS. Note that the following variable names assume the use of the file upload name 'userfile', as used in the example above ( inside the form):

* $userfile - The temporary filename in which the uploaded file was stored on the server machine.
* $userfile_name - The original name or path of the file on the sender's system.
* $userfile_size - The size of the uploaded file in bytes.
* $userfile_type - The mime type of the file if the browser provided this information. An example would be "image/gif".



With all these info we will make our script ready to handle the files.
Let us check the file size and we will not allow file size more than 250 KB to get uploaded to our server. Here we are using a flag $file_upload to false for processing the file upload.


if ($userfile_size >250000){$msg=$msg."Your uploaded file size is more than 250KB so please reduce the file size and then upload. Visit the help page to know how to reduce the file size.
";

$file_upload="false";}

Now let us check the file extension and only jpg or gif file pictures we will allow into our server. We will check this by using $userfile_type extension

if (!($userfile_type =="image/pjpeg" OR $userfile_type=="image/gif")){$msg=$msg."Your uploaded file must be of JPG or GIF. Other file types are not allowed
";

$file_upload="false";}

We will limit ourselves to these two type checks and if we find our $file_upload variable is not "false" then we can upload the file. This part is very simple in PHP and can be done in one step. Before that let us decide the file directory name where we will be placing the file. $add is the path with the file name relative to the script running this code where the uploaded file will be stored.


$add="upload/$userfile_name"; // the path with the file name where the file will be stored, upload is the directory name.

Now let us copy the file to server. The command move_uploaded_file will does that job for us and if the action is successful then it will return true.

if(move_uploaded_file ($userfile, $add)){
// do your coding here to give a thanks message or any other thing.
}else{echo "Failed to upload file Contact Site admin to fix the problem";}

Thats all... the file is placed in our directory (name: upload)

PHP Login and logout script and example

Depending on the visitors session condition whether logged in or not we can display different messages to the members.We should show an welcome messages to a logged in user like "Welcome john" with a logout button. Same way we if the member has not logged in then we can show login input box in that place or show the link to login page.
In PHP 5 and above the session checking has to be done line this

if(!isset($_SESSION['userid'])){
// session not logged in so display form

}else{
// session logged
}


Here is the code




if(isset($session[userid])){ // Member is logged in so we have to display welcome message with userid and one logout link
echo "


";

}else { // Member has not logged in so we can display the login form allowing member to login with user id and password

echo "











";
Welcome $session[userid]
LOGOUT
Username
Password
Forgot password




} // End of else condtiion

echo "";
?>


PHP Login Script (MORE DETAILED)

The Database
We are going to create a simple login system using PHP code on our pages, and a MySQL database to store our users information. We will track the users who are logged in with cookies.

Before we can create a login script, we first need to create a database to store users. For the purpose of this tutorial we will simply need the fields "username" and "password", however you can create as many fields as you wish.

CREATE TABLE users (ID MEDIUMINT NOT NULL AUTO_INCREMENT PRIMARY KEY, username VARCHAR(60), password VARCHAR(60))

This will create a database called users with 3 fields: ID, username, and password.

Registration Page 1


// Connects to your Database
mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());

//This code runs if the form has been submitted
if (isset($_POST['submit'])) {

//This makes sure they did not leave any fields blank
if (!$_POST['username'] | !$_POST['pass'] | !$_POST['pass2'] ) {
die('You did not complete all of the required fields');
}

// checks if the username is in use
if (!get_magic_quotes_gpc()) {
$_POST['username'] = addslashes($_POST['username']);
}
$usercheck = $_POST['username'];
$check = mysql_query("SELECT username FROM users WHERE username = '$usercheck'")
or die(mysql_error());
$check2 = mysql_num_rows($check);

//if the name exists it gives an error
if ($check2 != 0) {
die('Sorry, the username '.$_POST['username'].' is already in use.');
}

// this makes sure both passwords entered match
if ($_POST['pass'] != $_POST['pass2']) {
die('Your passwords did not match. ');
}

// here we encrypt the password and add slashes if needed
$_POST['pass'] = md5($_POST['pass']);
if (!get_magic_quotes_gpc()) {
$_POST['pass'] = addslashes($_POST['pass']);
$_POST['username'] = addslashes($_POST['username']);
}

// now we insert it into the database
$insert = "INSERT INTO users (username, password)
VALUES ('".$_POST['username']."', '".$_POST['pass']."')";
$add_member = mysql_query($insert);
?>


Registered


Thank you, you have registered - you may now login.




Registration Page 2


}
else
{
?>


" method="post">




Username:

Password:

Confirm Password:





}
?>

The Login Page 1


// Connects to your Database
mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());

//Checks if there is a login cookie
if(isset($_COOKIE['ID_my_site']))

//if there is, it logs you in and directes you to the members page
{
$username = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error());
while($info = mysql_fetch_array( $check ))
{
if ($pass != $info['password'])
{
}
else
{
header("Location: members.php");

}
}
}

//if the login form is submitted
if (isset($_POST['submit'])) { // if form has been submitted

// makes sure they filled it in
if(!$_POST['username'] | !$_POST['pass']) {
die('You did not fill in a required field.');
}
// checks it against the database

if (!get_magic_quotes_gpc()) {
$_POST['email'] = addslashes($_POST['email']);
}
$check = mysql_query("SELECT * FROM users WHERE username = '".$_POST['username']."'")or die(mysql_error());

//Gives error if user dosen't exist
$check2 = mysql_num_rows($check);
if ($check2 == 0) {
die('That user does not exist in our database. Click Here to Register');
}
while($info = mysql_fetch_array( $check ))
{
$_POST['pass'] = stripslashes($_POST['pass']);
$info['password'] = stripslashes($info['password']);
$_POST['pass'] = md5($_POST['pass']);

//gives error if the password is wrong
if ($_POST['pass'] != $info['password']) {
die('Incorrect password, please try again.');
}

The Login Page 2

else
{

// if login is ok then we add a cookie
$_POST['username'] = stripslashes($_POST['username']);
$hour = time() + 3600;
setcookie(ID_my_site, $_POST['username'], $hour);
setcookie(Key_my_site, $_POST['pass'], $hour);

//then redirect them to the members area
header("Location: members.php");
}
}
}
else
{

// if they are not logged in
?>
" method="post">





Login

Username:

Password:






}

?>

Members Area


// Connects to your Database
mysql_connect("your.hostaddress.com", "username", "password") or die(mysql_error());
mysql_select_db("Database_Name") or die(mysql_error());

//checks cookies to make sure they are logged in
if(isset($_COOKIE['ID_my_site']))
{
$username = $_COOKIE['ID_my_site'];
$pass = $_COOKIE['Key_my_site'];
$check = mysql_query("SELECT * FROM users WHERE username = '$username'")or die(mysql_error());
while($info = mysql_fetch_array( $check ))
{

//if the cookie has the wrong password, they are taken to the login page
if ($pass != $info['password'])
{ header("Location: login.php");
}

//otherwise they are shown the admin area
else
{
echo "Admin Area

";
echo "Your Content

";
echo "Logout";
}
}
}
else

//if the cookie does not exist, they are taken to the login screen
{
header("Location: login.php");
}
?>

Logout Page


$past = time() - 100;
//this makes the time in the past to destroy the cookie
setcookie(ID_my_site, gone, $past);
setcookie(Key_my_site, gone, $past);
header("Location: login.php");
?>

Date Function / Date Formats / Date Formatting

Getting the Current Date


Syntax

date('format options');

Example:

1.date('y m d'); Output: 05 04 23

2. date('Y M D'); Output: 2005 Apr Sat

3.date('Y m d h: s: m'); Output: 2005 04 23 02: 18: 04 (Date and Time)


Number of days in a month


Syntax

cal_days_in_month( CAL_GREGORIAN, $intMonth, $intYear);

Example:

cal_days_in_month ( CAL_GREGORIAN, 1, 2005); Output: 31

Check the date format


Syntax

checkdate ($intMonth,$date, $intYear);

Example:

1. checkdate (1, 30,2005); Output: (1 means true)

2. checkdate (2, 30,2005); Output: (null means false)

Welcome! PHP has nice built in date function which allows you to display dates in human readable formats.

CODE:
echo date("Y-m-d");
echo date("Y/m/d");
echo date("M d, Y");
echo date("F d, Y");
echo date("D M d, Y");
echo date("l F d, Y");
echo date("l F d, Y, h:i:s");
echo date("l F d, Y, h:i A");
?>
OUTPUT:
2008-05-21
2008/05/21
May 21, 2008
May 21, 2008
Wed May 21, 2008
Wednesday May 21, 2008
Wednesday May 21, 2008, 04:42:26
Wednesday May 21, 2008, 04:42 AM

PHP Date Function Parameters
ormat - The first parameter, format, in the date function specifies how to display the date/time. It uses different letters to represent the date and time. Some of the letters used above are described here.
  • d - The day of the month, i.e. 01-31
  • m - Month representation in numbers, i.e. 01-12
  • Y - Year in four digits

PHP date function explained

With PHP's date function you format timestamps, so they are more human readable.
The following tutorial will teach you how to display the current time, formating PHP's timestamp, and show you all the various date arguments for reference purposes.

PHP Date - The Timestamp

The date function always formats a timestamp, whether you supply one or not. What's a timestamp? Good question!

  • Timestamp: A timestamp is the number of seconds from January 1, 1970 at 00:00. Otherwise known as the Unix Timestamp, this measurement is a widely used standard that PHP has chosen to utilize.

PHP Date - What Time Is It?

The date function uses letters of the alphabet to represent various parts of a typical date and time format. The letters we will be using in our first example are:

  • d: The day of the month. The type of output you can expect is 01 through 31.
  • m: The current month, as a number. You can expect 01 through 12.
  • y: The current year in two digits ##. You can expect 00 through 99

We'll tell you the rest of the options later, but for now let's use those above letters to format a simple date! The letters that PHP uses to represent parts of date and time will automatically be converted by PHP.

However, other characters like a slash "/" can be inserted between the letters to add additional formatting. We have opted to use the slash in our example.

date("m/d/y"); ?>

If the 2010 Winter Olympics were just finishing up, you would see something like:

02/27/10

Be sure to test this out on your own PHP enabled server, it's really great to see the instant results available with PHP date!

PHP Date - Supplying a Timestamp

As our first example shows, the first argument of the date function tells PHP how you would like your date and time displayed. The second argument allows for a timestamp and is optional.

This example uses the mktime function to create a timestamp for tomorrow. To go one day in the future we simply add one to the day argument of mktime. For your future reference, we have the arguments of mktime.

Note: These arguments are all optional. If you do not supply any arguments the current time will be used to create the timestamp.

  • mktime(hour, minute, second, month, day, year, daylight savings time)

PHP Code:


$tomorrow = mktime(0, 0, 0, date("m"), date("d")+1, date("y"));

echo "Tomorrow is ".date("m/d/y", $tomorrow);

?>

Notice that we used one letter at a time with the function date to get the month, day and year. For example the date("m") will return the month's number 01-12.

If we were to run our new script just after the 2010 Winter Olympics our display would look like:

Tomorrow is 02/28/10

~PHP Date - Reference~~~~~~~

Now that you know the basics of using PHP's date function, you can easily plug in any of the following letters to format your timestamp to meet your needs.

Important Full Date and Time:
  • r: Displays the full date, time and timezone offset. It is equivalent to manually entering date("D, d M Y H:i:s O")
Time:
  • a: am or pm depending on the time
  • A: AM or PM depending on the time
  • g: Hour without leading zeroes. Values are 1 through 12.
  • G: Hour in 24-hour format without leading zeroes. Values are 0 through 23.
  • h: Hour with leading zeroes. Values 01 through 12.
  • H: Hour in 24-hour format with leading zeroes. Values 00 through 23.
  • i: Minute with leading zeroes. Values 00 through 59.
  • s: Seconds with leading zeroes. Values 00 through 59.
Day:
  • d: Day of the month with leading zeroes. Values are 01 through 31.
  • j: Day of the month without leading zeroes. Values 1 through 31
  • D: Day of the week abbreviations. Sun through Sat
  • l: Day of the week. Values Sunday through Saturday
  • w: Day of the week without leading zeroes. Values 0 through 6.
  • z: Day of the year without leading zeroes. Values 0 through 365.
Month:
  • m: Month number with leading zeroes. Values 01 through 12
  • n: Month number without leading zeroes. Values 1 through 12
  • M: Abbreviation for the month. Values Jan through Dec
  • F: Normal month representation. Values January through December.
  • t: The number of days in the month. Values 28 through 31.
Year:
  • L: 1 if it's a leap year and 0 if it isn't.
  • Y: A four digit year format
  • y: A two digit year format. Values 00 through 99.
Other Formatting:
  • U: The number of seconds since the Unix Epoch (January 1, 1970)
  • O: This represents the Timezone offset, which is the difference from Greenwich Meridian Time (GMT). 100 = 1 hour, -600 = -6 hours

We suggest that you take a few minutes to create several timestamps using PHP's mktime function and just try out all these different letters to get your feet wet with PHP's date function.

timestamp - The second parameter, timestamp, is an optional parameter. Timestamp is the number of seconds since January 1, 1970 at 00:00:00 GMT. This is also known as the Unix Timestamp.

PHP Date: Finding Date / Time


Using the 2nd timestamp parameter we can do things like say find exactly what date or day it was yesterday or a week ago or what date it will be 1 month from today.

There are two ways we can do that.

  • Using the PHP strtotime function.
  • Using the PHP mktime function.
  1. strtotime - Convert any English textual datetime description into a Unix timestamp.
  2. mktime - Get Unix timestamp for a date.

PHP Date: Using strtotime to find date/time

Let's see some of the examples to find out dates using date and strtotime function.

Find Yesterday’s date


echo "yesterday was ".date("Y-m-d", strtotime("-1 days"));

?>

Output

yesterday was 2008-05-20

Find Date one week ago


echo "1 week form today was ".date("Y-m-d", strtotime("-1 weeks"));

?>

Output

1 week form today was 2008-05-14

Find Date one month after


echo "1 month from today will be ".date("Y-m-d", strtotime("+1 months"));

?>

Output

1 month form today will be 2008-06-21

PHP Date: Using mktime to find date/time

mktime could be used to find more specific things like find the next leap year in the calendar.

Find Leap Year


$day = "";

/*
* since leap year falls ever 4 years so loop for 4 times
*/

for($i=0; $i<4; $i++)
{
//get day timestamp for feburary 29 for this year
$day = date("d", mktime(0, 0, 0, 2, 29, date("Y")+$i));

/*
* check if day equals 29.
* If day is 29 then it must be the leap year. if day is 01, then it not a leap year.
*/

if($day == 29)
{
$year = date("Y")+$i;
break;
}
}

echo "next leap year is in year $year";

?>

Output

next leap year is in year 2008

The mktime takes 6 arguments. The parameters are explained as below.

  1. hour - The number of the hour.
  2. minute - The number of the minute.
  3. second - The number of seconds past the minute.
  4. month - The number of the month.
  5. day - The number of the day.
  6. year - The number of year.