php

PHP Encryption - Example Using Mcrypt
Submitted by devans on Mon, 2008-07-21 12:48What now follows is an example of how to use the Mcrypt encryption function that is part of the PHP scripting language. In order to use Mcrypt with PHP you will need to include the mcrypt library files by editing the php.ini file accordingly.
If you need a primer in what the Mcrypt function is capable of performing I suggest you check out http://us.php.net/manual/en/book.mcrypt.php as I will only be providing an example on how to use the encryption and decryption functionality.
The encryption function used is simply called - mcrypt_encrypt
The decryption function used is simply called - mcrypt_decrypt
Here's an example PHP script that performs both the encryption and decryption function in the same script so you can see it at work.
<?php
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
$key = hash ("md5", "It's all just apples and oranges.");
$text = "The quick brown fox jumps over the lazy dog.";
echo "<p><b>Initialization Vector Size = </b>" .$iv_size." characters</p>";
echo "<p><b>Initialization Vector = </b>" .$iv ."</p>";
echo "<p><b>KEY (Password Used after MD5 Hash) = </b>" .$key. "</p>";
echo "<p><b>Plain Text String Length = </b>" .strlen($text) . " characters</p>";
echo "<p><b><u>Plain Text = </u></b><font color='blue'>" .$text."</font></p>";
$crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $text, MCRYPT_MODE_CBC, $iv);
echo "<p><b>Encrypted Text String Length = </b>".strlen($crypttext) . " characters</p>";
echo "<p><b><u>Encrypted Text = </u></b><font color='red'>".$crypttext ."</font></p>";
echo "<i>The Mcrypt_decrypt function pads out the RETURN STRING (decrypttext) with null characters '\0' to pad to the same block size as (crypttext), which is in this case 64 characters in length.</i><br>";
$decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $crypttext, MCRYPT_MODE_CBC, $iv);
$decrypted = rtrim($decrypttext, "\0");
echo "<p><b>Decrypted Text (decrypttext) = </b>" .$decrypttext . " - <i>With the nulls used to pad still present. These need to be trimmed off.</i></p>";
echo "<p><b>Decrypted Text (decrypttext) = </b>" .$decrypted . " - <i>With the nulls used to pad out the blocksize of the encrypted text removed.</i></p>";
?>
And here is the what the script returns:
Initialization Vector Size = 32 characters
Initialization Vector = $pÍ£Ûö¹Ôe¤º¨yr ízkO½Z6¨“szö
KEY (Password Used after MD5 Hash) = c54dcf123bf2548c7cdb862ef36e87e0
Plain Text String Length = 44 characters
Plain Text = The quick brown fox jumps over the lazy dog.
Encrypted Text String Length = 64 characters
Encrypted Text = ÙPKàoB,ãU0šÎmÑç{ÛîêPnëkèu¸–…ê`~ì÷Ni‡dݹ!ò×V@ˆKWH„õ„Ò
The Mcrypt_decrypt function pads out the RETURN STRING (decrypttext) with null characters '�' to pad to the same block size as (crypttext), which is in this case 64 characters in length.
Decrypted Text (decrypttext) = The quick brown fox jumps over the lazy dog.�������������������� - With the nulls used to pad still present. These need to be trimmed off.
Decrypted Text (decrypttext) = The quick brown fox jumps over the lazy dog. - With the nulls used to pad out the blocksize of the encrypted text removed.
As you step through the script (top) compare the output above for a self explanatory view of the results of each line. A basic understanding of PHP should be all that is required to grasp what is happening here.
Enjoy!

MySQL Database Connection
Submitted by devans on Mon, 2008-07-14 17:14The script that follows provides for an example way to use PHP to connect to a MySQL database through the use of a PHP Function.
The code that follows I will call db.php
<?php
function connect($sql)
{
// The following values should all be adjusted to suit your MySQL install.
$host="localhost";
$user="root";
$pass="password";
$db="users";
if(!($connect=mysql_connect($host,$user,$pass))){
printf("Error connecting to the database");
email_error("Server Connection Error", mysql_error());
}
if(!($dbselect = mysql_select_db($db, $connect))){
printf("<p>Error connecting to the database</p>");
email_error("Database Connection Error", mysql_error());
}
$result=mysql_query($sql);
if (mysql_errno() == 0){
return $result;
}
else {
email_error($sql, mysql_error());
$result = "Null";
}
}
?>
Being the ever vigilant system administrator we want the site to alert us of failed connection errors, which may be hack attempts. To do so we can get the web server to send out via it's predefined mail connector (look in your php.ini file) an email message with the error details. This could very easily be included as part of another file but sometimes it is just easier to have all of your functions reside in one location and include them from there.
<?php
// Begin the function that will send us email alerts following failure
function email_error($reason, $error)
{
$from = "alert@mydomain.com";
$headers = 'MIME-Version: 1.0\n';
$headers.= "Content-type: text/plain; charset=iso-8859-1\n";
$headers.= "X-Priority: 3\n";
$headers.="X-MSMail-Priority: Normal\n";
$headers.="X-Mailer: php\n";
$headers.="From:\"".$from."\"<".$from.">\n";
$sendto = "me@mydomain.com";
$subject = "MyDomain Error Notice";
$time = date("Y-m-d H:m");
$m1 = 'Site Error - Application Functionality Failed At '.$time."\n\n";
$m2 = 'GENERAL ERROR MESSAGE: '."\n".$reason."\n\n";
$m3 = 'MySQL ERROR MESSAGE: '."\n".$error."\n\n";
$m4 = 'Regards,'."\n\n";
$m5 = 'Automatic Pilot';
$message = $m1.$m2.$m3.$m4.$m5;
mail($sendto, $subject, $message, $headers);
die("<p>There was a problem with the database</p>");
}
?>
Then to use the above database connection function (with integrated email alerts) you would call it in a manner like this:
Example.php
<?php
//include the database connection function file db.php
include("include/db.php");
//remember that the connect function relies on the input supplied through the variable $sql.
$sql = "select * from member where username='dave.evans'";
$resultset = connect($sql);
if ($resultset){
// Do something
while($row=mysql_fetch_array($resultset)) {
echo ("Resultset is: ".$row['username']."<br>");}
}
else {
// Do something else or nothing at all
}
?>
That's all there is to it. Enjoy!

File Upload Form
Submitted by devans on Mon, 2008-07-14 11:42What follows below is a simple upload form and the server-side script necessary for processing the uploaded file.
Code for Upload.html
<html>
<form enctype='multipart/form-data' action='upload.php' method='post'>
<input type='hidden' name='MAX_FILE_SIZE' value='1000000' />
Choose a file to upload: <input name='uploaded_file' type='file' />
<input type='submit' value='Upload' />
</form>
</html>
Code for Upload.php
<?php
//Сheck that we have a file
if((!empty($_FILES["uploaded_file"])) && ($_FILES['uploaded_file']['error'] == 0)) {
//Check if the file is JPEG image and it's size is less than 350Kb
$filename = basename($_FILES['uploaded_file']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext == "jpg") && ($_FILES["uploaded_file"]["type"] == "image/jpeg") &&
($_FILES["uploaded_file"]["size"] < 350000)) {
//Determine the path to which we want to save this file
$newname = dirname(__FILE__).'/upload/'.$filename;
//Check if the file with the same name is already exists on the server
if (!file_exists($newname)) {
//Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$newname))) {
echo "It's done!<p> The file has been saved as: </p>".$newname;
} else {
echo "Error: A problem occurred during file upload!";
}
} else {
echo "Error: File ".$_FILES["uploaded_file"]["name"]." already exists";
}
} else {
echo "Error: Only .jpg images under 350Kb are accepted for upload";
}
} else {
echo "Error: No file uploaded";
}
?>
Hopefully as you read through the above the comments interspersed throughout will provide sufficient explanation as to what is occurring through each step of the script. Also, don't forget to create the 'upload' folder inside your script directory so that upload.php has somewhere to save the file.
Simple, and to the point. Secure, not by a long shot but I'll cover that more soon in another script example.
Enjoy!

RSS Feed

