Thursday 17 May 2012

Upload multiple images with thumbnail creation included php code

<?php

if(isset($_POST['submit'])){
$destpath = "photos/";

while(list($key,$value) = each($_FILES["file"]["name"])) {
   
if(!empty($value))
{
if (($_FILES["file"]["type"][$key] == "image/gif")
|| ($_FILES["file"]["type"][$key] == "image/jpeg")
|| ($_FILES["file"]["type"][$key] == "image/pjpeg")
|| ($_FILES["file"]["type"][$key] == "image/png")
&& ($_FILES["file"]["size"][$key] < 2000000))
    {



$source = $_FILES["file"]["tmp_name"][$key] ;
$filename = $_FILES["file"]["name"][$key] ;
move_uploaded_file($source, $destpath . $filename) ;
//echo "Uploaded: " . $destpath . $filename . "<br/>" ;
//thumbnail creation start//
$tsrc="photos/thimg/".$_FILES["file"]["name"][$key];   // Path where thumb nail image will be stored
//echo $tsrc;
/*if (!($_FILES["file"]["type"] =="image/jpeg" OR $_FILES["file"]["type"] =="image/png" OR $_FILES["file"]["type"]=="image/gif")){echo "Your uploaded file must be of JPG or GIF. Other file types are not allowed<BR>";
}*/
$n_width=100;          // Fix the width of the thumb nail images
$n_height=100;         // Fix the height of the thumb nail imaage

/////////////////////////////////////////////// Starting of GIF thumb nail creation///////////
$add=$destpath . $filename;
if($_FILES["file"]["type"][$key]=="image/gif"){
//echo "hello";
$im=ImageCreateFromGIF($add);
$width=ImageSx($im);              // Original picture width is stored
$height=ImageSy($im);                  // Original picture height is stored
$newimage=imagecreatetruecolor($n_width,$n_height);
imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
if (function_exists("imagegif")) {
Header("Content-type: image/gif");
ImageGIF($newimage,$tsrc);
}
if (function_exists("imagejpeg")) {
Header("Content-type: image/jpeg");
ImageJPEG($newimage,$tsrc);
}
    }
//chmod("$tsrc",0777);
////////// end of gif file thumb nail creation//////////
$n_width=100;          // Fix the width of the thumb nail images
$n_height=100;         // Fix the height of the thumb nail imaage

////////////// starting of JPG thumb nail creation//////////
if($_FILES["file"]["type"][$key]=="image/jpeg"){
    echo $_FILES["file"]["name"][$key]."<br>";
$im=ImageCreateFromJPEG($add);
$width=ImageSx($im);              // Original picture width is stored
$height=ImageSy($im);             // Original picture height is stored
$newimage=imagecreatetruecolor($n_width,$n_height);                
imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
ImageJpeg($newimage,$tsrc);
chmod("$tsrc",0777);
}
////////////////  End of png thumb nail creation //////////
if($_FILES["file"]["type"][$key]=="image/png"){
//echo "hello";
$im=ImageCreateFromPNG($add);
$width=ImageSx($im);              // Original picture width is stored
$height=ImageSy($im);                  // Original picture height is stored
$newimage=imagecreatetruecolor($n_width,$n_height);
imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
if (function_exists("imagepng")) {
//Header("Content-type: image/png");
ImagePNG($newimage,$tsrc);
}
if (function_exists("imagejpeg")) {
//Header("Content-type: image/jpeg");
ImageJPEG($newimage,$tsrc);
}
    }

// thumbnail creation end---
    }
else{echo "error in upload";}
}
}
echo "files has been uploaded to the photos";
}
?>
<html>
<form name="frm" method="post" enctype="multipart/form-data"  >
<input type="file" name="file[]" multiple="multiple"/>
<input type="submit" name="submit"/>
</form>
</html>

Tuesday 15 May 2012

Using PHP_SELF in the action field of a form

Using PHP_SELF in the action field of a form

In this article shows the usage of PHP_SELF variable and how to avoid PHP_SELF exploits.

What is PHP_SELF variable?

PHP_SELF is a variable that returns the current script being executed. This variable returns the name and path of the current file (from the root folder). You can use this variable in the action field of the FORM. There are also certain exploits that you need to be aware of. We shall discuss all these points in this article.

We will now see some examples.
echo $_SERVER['PHP_SELF'];
a) Suppose your php file is located at the address:
http://www.yourserver.com/form-action.php
In this case, PHP_SELF will contain:
"/form-action.php"
b) Suppose your php file is located at the address:
http://www.yourserver.com/dir1/form-action.php
For this URL, PHP_SELF will be :
"/dir1/form-action.php"

Using the PHP_SELF variable in the action field of the form

A common use of PHP_SELF variable is in the action field of the <form> tag. The action field of the FORM instructs where to submit the form data when the user presses the "submit" button. It is common to have the same PHP page as the handler for the form as well.
However, if you provide the name of the file in the action field, in case you happened to rename the file, you need to update the action field as well; or your forms will stop working.
Using PHP_SELF variable you can write more generic code which can be used on any page and you do not need to edit the action field.
Consider, you have a file called form-action.php and want to load the same page after the form is submitted. The usual form code will be:
<form  method="post" action="form-action.php" >
We can use the PHP_SELF variable instead of "form-action.php". The code becomes:
<form name="form1" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" >

The complete code of "form-action.php"

Here is the combined code, that contains both the form and the PHP script.
<?php
if(isset($_POST['submit']))
{
    $name = $_POST['name'];
    echo "User Has submitted the form and entered this name : <b> $name </b>";
    echo "<br>You can use the following form again to enter a new name.";
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
   <input type="text" name="name"><br>
   <input type="submit" name="submit" value="Submit Form"><br>
</form>
This PHP code is above the HTML part and will be executed first. The first line of code is checking if the form is submitted or not. The name of the submit button is "submit". When the submit button is pressed the $_POST['submit'] will be set and the IF condition will become true. In this case, we are showing the name entered by the user.
If the form is not submitted the IF condition will be FALSE as there will be no values in $_POST['submit'] and PHP code will not be executed. In this case, only the form will be shown.

What are PHP_SELF exploits and how to avoid them

The PHP_SELF variable is used to get the name and path of the current file but it can be used by the hackers too. If PHP_SELF is used in your page then a user can enter a slash (/) and then some Cross Site Scripting (XSS) commands to execute.
See below for an example:
<form name="test" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
Now, if a user has entered the normal URL in the address bar like
http://www.yourdomain.com/form-action.php
the above code will be translated as:
<form name="test" action="form-action.php" method="post">
This is the normal case.
Now consider that the user has called this script by entering the following URL in the browser's address bar:
http://www.yourdomain.com/form-action.php/%22%3E%3Cscript%3Ealert('xss')%3C
/script%3E%3Cfoo%22

In this case, after PHP processing the code becomes:
<form name="test" method="post" action="form-action.php"/>
<script>alert('xss')</script><foo"">
You can see that this code has added a script tag and an alert command. When this page is be loaded, user will see an alert box. This is just a simple example how the PHP_SELF variable can be exploited.
Any JavaScript code can be added between the "script" tag. <script>....HERE....</script>. A hacker can link to a JavaScript file that may be located on another server. That JavaScript file can hold the malicious code that can alter the global variables and can also submit the form to another address to capture the user data, for example.

How to Avoid the PHP_SELF exploits

PHP_SELF exploits can be avoided by using the htmlentities() function. For example, the form code should be like this to avoid the PHP_SELF exploits:
<form name="test" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
The htmlentities() function encodes the HTML entities. Now if the user tries to exploit the PHP_SELF variable, the attempt will fail and the result of entering malicious code in URL will result in the following output:
<form name="test" method="post"
action="form-action.php/&quot;&gt;&lt;script&gt;alert('xss')&
lt;/script&gt;&lt;foo">
As you can see, the script part is now 'sanitized'.
So don't forget to convert every occurrence of "$_SERVER['PHP_SELF']" into "htmlentities($_SERVER['PHP_SELF'])" throughout your script.
NOTE:
Some PHP servers are configured to solve this issue and they automatically do this conversion.But, why take risk? make it a habit to use htmlentities() with PHP_SELF.

PHP Thumbnail Image creation script

PHP Thumbnail Image creation script

Creating thumbnail images is a very common requirement. Many scripts use this to create thumbnails of uploaded images or any stored images. We will learn how to create thumbnail images while uploading images to the server. Please read the tutorials on file upload when register_global is off to know how to upload files to the server with necessary permissions in PHP 5.

The file ( or image ) will be first uploaded to a directory and then one thumbnail image will be created in a different directory. So for creating the thumbnail we will check the file extension ( it is gif or jpeg image ) but to keep the script simple we are not checking here the file size. So if the file size is to be restricted then file size validation is to be added. You can see how the file size checking is done in file upload tutorial.

This script is tested with PHP 5.2.6 with register_global is OFF. Please update your script if you have downloaded the old version of this.

<FORM ENCTYPE="multipart/form-data" ACTION="addimgck.php" METHOD=POST>
Upload this file: <INPUT NAME="userfile" TYPE="file">
<INPUT TYPE="submit" VALUE="Send File"></FORM>

We will now see the addimgck.php file and check the code to create the thumbnail image. We will upload the file to the upimg directory and check to see if file upload is successful or not.

// Below lines are to display file name, temp name and file type , you can use them for testing your script only//////
echo "File Name: ".$_FILES[userfile][name]."<br>";
echo "tmp name: ".$_FILES[userfile][tmp_name]."<br>";
echo "File Type: ".$_FILES[userfile][type]."<br>";
echo "<br><br>";
///////////////////////////////////////////////////////////////////////////
$add="upimg/".$_FILES[userfile][name]; // the path with the file name where the file will be stored, upload is the directory name.
//echo $add;
if(move_uploaded_file ($_FILES[userfile][tmp_name],$add)){
echo "Successfully uploaded the mage";
chmod("$add",0777);

}else{echo "Failed to upload file Contact Site admin to fix the problem";
exit;}

Now the image is uploaded to the directory and from that image we will create thumbnail image of it. We will first set the height and width of the thumbnail  images to be  generated. Then we will check the type of the file and now we are checking for file type of gif and jpeg and if the image is not of this type then we are terminating the script giving an error message.

///////// Start the thumbnail generation//////////////
$n_width=100; // Fix the width of the thumb nail images
$n_height=100; // Fix the height of the thumb nail imaage

$tsrc="thimg/".$_FILES[userfile][name]; // Path where thumb nail image will be stored
//echo $tsrc;
if (!($_FILES[userfile][type] =="image/pjpeg" OR $_FILES[userfile][type]=="image/gif")){echo "Your uploaded file must be of JPG or GIF. Other file types are not allowed<BR>";
exit;}

Now let us start with gif file thumb nail image creation. We will first read the height and width of the uploaded image and then resize it to our thumbnail image size. Note that in some GD library support GIF version is not included so to check that we have used one if condition and  accordingly used jpeg support.  We will be using imagecreatetruecolor to retain the actual color combination of the main picture.

//////////// Starting of GIF thumb nail creation///////////
if (@$_FILES[userfile][type]=="image/gif")
{
$im=ImageCreateFromGIF($add);
$width=ImageSx($im); // Original picture width is stored
$height=ImageSy($im); // Original picture height is stored
$newimage=imagecreatetruecolor($n_width,$n_height);
imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
if (function_exists("imagegif")) {
Header("Content-type: image/gif");
ImageGIF($newimage,$tsrc);
}
elseif (function_exists("imagejpeg")) {
Header("Content-type: image/jpeg");
ImageJPEG($newimage,$tsrc);
}
chmod("$tsrc",0777);
}////////// end of gif file thumb nail creation//////////

////////////// starting of JPG thumb nail creation//////////
if($_FILES[userfile][type]=="image/pjpeg"){
$im=ImageCreateFromJPEG($add);
$width=ImageSx($im); // Original picture width is stored
$height=ImageSy($im); // Original picture height is stored
$newimage=imagecreatetruecolor($n_width,$n_height);
imageCopyResized($newimage,$im,0,0,0,0,$n_width,$n_height,$width,$height);
ImageJpeg($newimage,$tsrc);
chmod("$tsrc",0777);
}
//////////////// End of JPG thumb nail creation //////////

Disable Back Button in Browser using JavaScript


Sometimes we have requirement in developing a website to disable the Back button effect from Browser. This is common in Online Banking Websites and other sites where security is of principal concern. User may hit back and navigate from the page and forget to logout.
Hence sometime it is required that we disable the functionality of Back button. But unfortunately this is not an easy task. There is no direct way of dealing with this problem. We can do few hacks to ensure that user does not get back in the browser.
Following are few tricks that can be used to disable the back button in browser. Please note that we do not literally “disable” the back button, but just nullify its effect is some case and hide it altogether in others.

Open A New Window without Back Button

browser-back-button-viralpatelThis one is very crude technique. But in some case it works like charm. All you have to do is to open the webpage in a new window. This window doesn’t have back button at all because we have hide the toolbar.
This technique does work in some case but user has still a workaround to navigate to previous page. Most of the browser have options of Back in context menu. Thus user can still right click on the page and click Back to go to previous page. We will shortly see the workaround for this issue also.
Following is the code to open webpage in a new window have no toolbar (Back/Next buttons).
?
1
2
window.open ("http://viralpatel.net/blogs/",
"mywindow","status=1,toolbar=0");
Also it is possible to disable the right click on any webpage using Javascript. Add following code in the webpage.
?
1
<body oncontextmenu="return false;">

Disable Back functionality using history.forward

This is another technique to disable the back functionality in any webpage. We can disable the back navigation by adding following code in the webpage. Now the catch here is that you have to add this code in all the pages where you want to avoid user to get back from previous page. For example user follows the navigation page1 -> page2. And you want to stop user from page2 to go back to page1. In this case all following code in page1.
?
1
2
3
4
5
6
7
<SCRIPT type="text/javascript">
    window.history.forward();
    function noBack() { window.history.forward(); }
</SCRIPT>
</HEAD>
<BODY onload="noBack();"
    onpageshow="if (event.persisted) noBack();" onunload="">
The above code will trigger history.forward event for page1. Thus if user presses Back button on page2, he will be sent to page1. But the history.forward code on page1 pushes the user back to page2. Thus user will not be able to go back from page1.
Check the demo for this example.
ONLINE DEMO

Wednesday 9 May 2012

PHP for Beginners: Building Your First Simple CMS

PHP for Beginners: Building Your First Simple CMS

Jan 5 2009

The Magic of PHP + MySQL


It's safe to say that nearly every website that's up-to-date these days is using some form of content management system (CMS). While there are a ton of great free options that provide us with a CMS to power a website (WordPress, Drupal, etc.), it doesn't hurt to peek under the hood and get a feel for how these systems work.
To get our feet wet as back-end developers, we'll be creating a simple PHP class that will:
  • Create a database
  • Connect to a database
  • Display a form with two fields
  • Save the form data in the database
  • Display the saved data from the database



This class is intended to give you a feel for how PHP and MySQL interact together, and to show the basics of a CMS. I'll be skipping explanations of some of the very basic programming stuff, so if at any point you feel lost, head on over to w3schools.com and give yourself a crash-course in PHP. I'll try not to lose anyone, though, I promise.

Building the Class


Our first step is to simply lay out the class in a file named 'simpleCMS.php' so we have a road map to work with.
<?php

class simpleCMS {
  var $host;
  var $username;
  var $password;
  var $table;

  public function display_public() {

  }

  public function display_admin() {

  }

  public function write() {

  }

  public function connect() {

  }

  private function buildDB() {

  }
}

?>
As you can see, we're creating one class with four variables and five methods. I've opted to use PHP's object-oriented approach because it makes for cleaner code in large projects, and, in my opinion, it's just good practice.

The Variables

In this case, all four variables are for connecting to the database: $host, $username, $password, and $table provide a path and access to our database on the server. For now, we'll leave those empty and move on to our database, which is constructed by the method buildDB().

Build the Database

private function buildDB() {
    $sql = <<<MySQL_QUERY
        CREATE TABLE IF NOT EXISTS testDB (
            title VARCHAR(150),
            bodytext TEXT,
            created VARCHAR(100)
    )
    MySQL_QUERY;

    return mysql_query($sql);
}
This function runs a MySQL command that checks the database to see if testDB exists. If so, it simply passes along a notification of success; if not, it creates our table and assigns three columns to hold data.

Connect to the Database


Now that we have a function to build our table, let's create the function that will connect to our database.
public function connect() {
    mysql_connect($this->host,$this->username,$this->password) or die("Could not connect. " . mysql_error());
    mysql_select_db($this->table) or die("Could not select database. " . mysql_error());

    return $this->buildDB();
}
We call mysql_connect() to hook into our database, and then mysql_select_db() to make sure we save our data in the right place. Both of these functions are accompanied by the die() command, which essentially says, "in the event that this function fails, stop execution of this script and display a message."
Our connect() function connects to the database and gets us pointed in the right direction, then runs our buildDB() function. Remember the grammatically awkward "IF NOT EXISTS" part of our MySQL command? Because we're going to run this function every time the page is loaded, we have to make sure we're not overwriting our database with every function call, and that's exactly what that phrase requires.

Build the Form

So, we've got a database. Now we just need to put stuff in it!
public function display_admin() {
    return <<<ADMIN_FORM

    <form action="{$_SERVER['PHP_SELF']}" method="post">
      <label for="title">Title:</label>
      <input name="title" id="title" type="text" maxlength="150" />
      <label for="bodytext">Body Text:</label>
      <textarea name="bodytext" id="bodytext"></textarea>
      <input type="submit" value="Create This Entry!" />
    </form>

ADMIN_FORM;
  }
Again, this is a very simple function. When called, it simply returns the HTML markup to create our form. You'll notice, however, in the action attribute of the form element, that I've used the variable $_SERVER['PHP_SELF']. This is, essentially, a shortcut that references the file you're currently using (in our case, it's display.php). This is useful if you'll be reusing your code across a site and don't necessarily want to rewrite this function for each page.
I'm also going to take a second right now to talk about the method I'm using to return the HTML. It's a format used in PHP called HEREDOC syntax, and I love it.
The primary advantage of HEREDOC is that it allows you to include formatting in your output. This is extraordinarily useful for folks like me who take issue with cluttered source code. You can read more about HEREDOC syntax and its ilk in the PHP manual.

Saving the Data to the Database

Our form will allow us to input information, so how do we save it? That's where our write() method comes in.
public function write($p) {
    if ( $p['title'] )
      $title = mysql_real_escape_string($p['title']);
    if ( $p['bodytext'])
      $bodytext = mysql_real_escape_string($p['bodytext']);
    if ( $title && $bodytext ) {
      $created = time();
      $sql = "INSERT INTO testDB VALUES('$title','$bodytext','$created')";
      return mysql_query($sql);
    } else {
      return false;
    }
}
Let's start with the function call itself—we're passing a variable to this one, which we haven't done so far. Our variable $p is going to hold the information sent from our form via the post method.
Once inside the function, we start with a conditional statement that's checking to see if the the title value was set in the form before it was submitted, and if so, we're setting our $title variable to the $_POST['title'] value (NOTE: we're using the function mysql_real_escape_string() as a precaution against potentially dangerous input, which is important to keep in mind when you're building anything that will allow users to input information). If $_POST['title'] wasn't set, we skip this line, leaving the $title variable unset.
This process is repeated for our second input, and then both variables are checked to make sure nothing is blank before saving to the database. If both variables are set, we then set the $created variable with the current Unix timestamp, which we'll use to sort our entries chronologically when we view them in the future.
We now have three variables, and because we've run checks, we know that all three variables are not empty. Now we can write our MySQL query that will save the entry in the database!

Displaying the Information from the Database


Now that we have the means to put information into our database, we need to create a way to get that information back out. This is where display_public() comes in. This is by far the most complex of our methods, so let's really take our time and figure out what's going on inside.
public function display_public() {
    $q = "SELECT * FROM testDB ORDER BY created DESC LIMIT 3";
    $r = mysql_query($q);

    if ( $r !== false && mysql_num_rows($r) > 0 ) {
      while ( $a = mysql_fetch_assoc($r) ) {
        $title = stripslashes($a['title']);
        $bodytext = stripslashes($a['bodytext']);

        $entry_display .= <<<ENTRY_DISPLAY

    <h2>$title</h2>
    <p>
      $bodytext
    </p>

ENTRY_DISPLAY;
      }
    } else {
      $entry_display = <<<ENTRY_DISPLAY

    <h2>This Page Is Under Construction</h2>
    <p>
      No entries have been made on this page.
      Please check back soon, or click the
      link below to add an entry!
    </p>

ENTRY_DISPLAY;
    }
    $entry_display .= <<<ADMIN_OPTION

    <p class="admin_link">
      <a href="{$_SERVER['PHP_SELF']}?admin=1">Add a New Entry</a>
    </p>

ADMIN_OPTION;

    return $entry_display;
  }
The first thing to note when reading from a database is the way PHP and MySQL interact with each other. First, we ask the database a question (query), to which it replies with a result (resource). However, this result isn't really useful until we've decoded it using one of several methods that "fetch," or organize, the information that's contained inside into a usable form (array).
Our very first action in the above function is to set up our query in the variable $q. The asterisk (*) operator in MySQL means "everything," so our query is asking the database to select everything from entries in the table testDB in reverse chronological order, limited to the first three entries returned.
Now that the query is defined, we send it to the database using the function mysql_query(). The resulting resource is stored in the variable $r. This is where it gets a bit tricky.
We now run a conditional statement that says, "IF mysql_query() didn't fail, AND IF the number of entries returned was greater than zero, process the result, OR ELSE display a default message."
If $r contains entries from the database, we now have to "fetch" that data. Information from the database is returned as an array, which is organized similarly to the database table itself. The function mysql_fetch_assoc() will take the resource and break each entry into an associative array (this means that when we save the result of mysql_fetch_assoc() into the variable $a, the data from the entry will be accessible by the column names in the database, i.e. $a['title']).
However, mysql_fetch_assoc() only gives us one entry at a time. To get all of the returned entries, we have to use a while loop. Essentially, we're saying, "WHILE $r has values we haven't used yet, get the next entry in line and do the following actions with it."
In this case, we're going to check the entry to make sure that data was returned, then remove the slashes that were added when we saved the information to the database using stripslashes(). After that, we simply wrap the variables in some HTML and, voila! we've got screen-ready content!
As a final step, the code adds a link to the bottom that allows users to add an entry. It's worth noting the use of the ".=" operator used in the while loop and when creating the "Add a New Entry" link; a function can only return one variable, so we need to append the new information to the existing variable. If we just used the equals sign ("="), we would overwrite existing data and end up with just a link to the form and no content.
So, you've now written your first CMS class! You can easily write and retrieve data to and from a database. All that's left to do is to try it out!

Using the Class

To use our class, we need to create a separate file. I'm going to call it "display.php", which I'll save in the main web folder, with our class saved as "simpleCMS.php" in a folder called "_class" within the main folder. To start, we just set up a document with plain ol' HTML.
<html>

  <head>
    <title>SimpleCMS</title>
  </head>

  <body>

  </body>

</html>
To use our class, we just have to insert a little PHP between the body tags:
<?php

  include_once('_class/simpleCMS.php');
  $obj = new simpleCMS();
  $obj->host = 'database.host.net';
  $obj->username = 'DB1234567';
  $obj->password = 'DBpassword';
  $obj->table = 'DB1234567';
  $obj->connect();

  if ( $_POST )
    $obj->write($_POST);

  echo ( $_GET['admin'] == 1 ) ? $obj->display_admin() : $obj->display_public();

?>
First and foremost, we have to include the class using the include_once() function. Then, we have to instantiate our object so that our code knows what's going on. Third, we set all of those variables we talked about toward the beginning of this tutorial. You'll have to replace all of those values with the information you get from your own server or hosting company. And fourth, we connect to our database using the connect() method.
After we've connected to the database, we check to see if any $_POST information exists. This is because we're using the same file for input, processing, and display of information. If anything was passed via $_POST, we run the write() function to validate it and save it to the database. Then, we use some shorthand trickery to run a conditional statement. In essence, we're saying, "IF $_GET['admin'] is set to 1, then show the form using display_admin(), OR ELSE show me the stored entries using display_public()."
And that's it! Once you get a feel for it, this sort of basic programming will allow you to start exercising total control over websites you build, whether you decide to really dig in and build your own CMS framework or just improve an existing CMS by, say, writing a WordPress plugin.
Really, when it comes to modern web design, you should have at least some understanding of how things are working behind the curtain—understanding how a site works will better enable you to design sites that have a more fluid integration of form and function. And besides, adding PHP and MySQL to your curriculum vitae definitely won't hurt your credibility...

Tuesday 8 May 2012

PHP Image Convert Function Tutorial Upload Type jpg gif png On the Fly

<!-- -------------------------------------------- -->
<!-- "my_file.php" that has the simple form on it -->
<!-- -------------------------------------------- -->
                     
<form enctype="multipart/form-data" method="post" action="image_upload_script.php">
Choose your file here:
<input name="uploaded_file" type="file"/><br /><br />
<input type="submit" value="Upload It"/>
</form>

<!-- -------------------------------------------- -->
<!-- "image_upload_script.php" -->
<!-- -------------------------------------------- -->


<?php// Access the $_FILES global variable for this specific file being uploaded
// and create local PHP variables from the $_FILES array of information
$fileName $_FILES["uploaded_file"]["name"]; // The file name$fileTmpLoc $_FILES["uploaded_file"]["tmp_name"]; // File in the PHP tmp folder$fileType $_FILES["uploaded_file"]["type"]; // The type of file it is$fileSize $_FILES["uploaded_file"]["size"]; // File size in bytes$fileErrorMsg $_FILES["uploaded_file"]["error"]; // 0 for false... and 1 for true$fileName preg_replace('#[^a-z.0-9]#i'''$fileName); // filter the $filename$kaboom explode("."$fileName); // Split file name into an array using the dot$fileExt end($kaboom); // Now target the last array element to get the file extension

// START PHP Image Upload Error Handling --------------------------------
if (!$fileTmpLoc) { // if file not chosen
    
echo "ERROR: Please browse for a file before clicking the upload button.";
    exit();
} else if(
$fileSize 5242880) { // if file size is larger than 5 Megabytes
    
echo "ERROR: Your file was larger than 5 Megabytes in size.";
    
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
    
exit();
} else if (!
preg_match("/.(gif|jpg|png)$/i"$fileName) ) {
     
// This condition is only if you wish to allow uploading of specific file types  
     
echo "ERROR: Your image was not .gif, .jpg, or .png.";
     
unlink($fileTmpLoc); // Remove the uploaded file from the PHP temp folder
     
exit();
} else if (
$fileErrorMsg == 1) { // if file upload error key is equal to 1
    
echo "ERROR: An error occured while processing the file. Try again.";
    exit();
}
// END PHP Image Upload Error Handling ----------------------------------
// Place it into your "uploads" folder mow using the move_uploaded_file() function
$moveResult move_uploaded_file($fileTmpLoc"uploads/$fileName");// Check to make sure the move result is true before continuingif ($moveResult != true) {
    echo 
"ERROR: File not uploaded. Try again.";
    exit();
}
// Include the file that houses all of our custom image functionsinclude_once("ak_php_img_lib_1.0.php");// ---------- Start Adams Universal Image Resizing Function --------$target_file "uploads/$fileName";$resized_file "uploads/resized_$fileName";$wmax 500;$hmax 500;ak_img_resize($target_file$resized_file$wmax$hmax$fileExt);// ----------- End Adams Universal Image Resizing Function ----------
// ---------- Start Adams Convert to JPG Function --------
if (strtolower($fileExt) != "jpg") {
    
$target_file "uploads/resized_$fileName";
    
$new_jpg "uploads/resized_".$kaboom[0].".jpg";
    
ak_img_convert_to_jpg($target_file$new_jpg$fileExt);
}
// ----------- End Adams Convert to JPG Function -----------
// Display things to the page so you can see what is happening for testing purposes
echo "The file named <strong>$fileName</strong> uploaded successfuly.<br /><br />";
echo 
"It is <strong>$fileSize</strong> bytes in size.<br /><br />";
echo 
"It is an <strong>$fileType</strong> type of file.<br /><br />";
echo 
"The file extension is <strong>$fileExt</strong><br /><br />";
echo 
"The Error Message output for this upload is: $fileErrorMsg";?>
<!-- -------------------------------------------- -->
<!-- "ak_php_img_lib_1.0.php" -->
<!-- -------------------------------------------- -->

<?php// Adam Khoury PHP Image Function Library 1.0
// ----------------------- RESIZE FUNCTION -----------------------
// Function for resizing any jpg, gif, or png image files
function ak_img_resize($target$newcopy$w$h$ext) {
    list(
$w_orig$h_orig) = getimagesize($target);
    
$scale_ratio $w_orig $h_orig;
    if ((
$w $h) > $scale_ratio) {
           
$w $h $scale_ratio;
    } else {
           
$h $w $scale_ratio;
    }
    
$img "";
    
$ext strtolower($ext);
    if (
$ext == "gif"){
    
$img imagecreatefromgif($target);
    } else if(
$ext =="png"){
    
$img imagecreatefrompng($target);
    } else {
    
$img imagecreatefromjpeg($target);
    }
    
$tci imagecreatetruecolor($w$h);
    
// imagecopyresampled(dst_img, src_img, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h)
    
imagecopyresampled($tci$img0000$w$h$w_orig$h_orig);
    if (
$ext == "gif"){
        
imagegif($tci$newcopy);
    } else if(
$ext =="png"){
        
imagepng($tci$newcopy);
    } else {
        
imagejpeg($tci$newcopy84);
    }
}
// ---------------- THUMBNAIL (CROP) FUNCTION ------------------
// Function for creating a true thumbnail cropping from any jpg, gif, or png image files
function ak_img_thumb($target$newcopy$w$h$ext) {
    list(
$w_orig$h_orig) = getimagesize($target);
    
$src_x = ($w_orig 2) - ($w 2);
    
$src_y = ($h_orig 2) - ($h 2);
    
$ext strtolower($ext);
    
$img "";
    if (
$ext == "gif"){
    
$img imagecreatefromgif($target);
    } else if(
$ext =="png"){
    
$img imagecreatefrompng($target);
    } else {
    
$img imagecreatefromjpeg($target);
    }
    
$tci imagecreatetruecolor($w$h);
    
imagecopyresampled($tci$img00$src_x$src_y$w$h$w$h);
    if (
$ext == "gif"){
        
imagegif($tci$newcopy);
    } else if(
$ext =="png"){
        
imagepng($tci$newcopy);
    } else {
        
imagejpeg($tci$newcopy84);
    }
}
// ------------------ IMAGE CONVERT FUNCTION -------------------
// Function for converting GIFs and PNGs to JPG upon upload
function ak_img_convert_to_jpg($target$newcopy$ext) {
    list(
$w_orig$h_orig) = getimagesize($target);
    
$ext strtolower($ext);
    
$img "";
    if (
$ext == "gif"){
        
$img imagecreatefromgif($target);
    } else if(
$ext =="png"){
        
$img imagecreatefrompng($target);
    }
    
$tci imagecreatetruecolor($w_orig$h_orig);
    
imagecopyresampled($tci$img0000$w_orig$h_orig$w_orig$h_orig);
    
imagejpeg($tci$newcopy84);
}
?>

Quick & Easy Form Validation Tutorial with JQuery

Quick & Easy Form Validation Tutorial with JQuery

Form validation has become never been easy like before. If you havent heard of jQuery, then its time to get know now. Jquery is an open source set of javascript library, that brings user interactivity in web applications so easy even for a beginner with just few lines of code.


In this tutorial, i am going to show how easy to validate a form with jquery. For this you will need to download the following:
JQuery Libraryhttp://jquery.com
JQuery form validation pluginhttp://bassistance.de/jquery-plugins/jquery-plugin-validation/
Lets say we are going to validate a registration form like shown below..
registerdemo2.PNG

Step 1:

Place the javascript files within the head section
?
CODE
1
2
3
4
5
6
7
8
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery.validate.min.js"></script>
<script>
$(document).ready(function(){
    $("#registerForm").validate();
  });
</script>
</head>
You should set the name and id of your html form same as $(“#registerForm”).validate();

Step 2:

For each required form element just place class=”required” and specify minlength tag inside it. For example
Name field -> class=”required”
Email field -> class = “required email”
?
CODE
1
2
3
<input name="name" type="text" id="name" class="required">
<input name="user_id" type="text" id="user_id" minlength="4">
<input name="user_email" type="text" id="user_email" class="required email">
Thats it! you will be able to validate form field textboxes without any advanced code.
For optional fields, you can specify class=”optional” or just leave it.

Step 3

In this last step you will add some styles to the error messages in the stylesheet.
?
CODE
1
2
3
4
5
6
7
.error {
    font: normal 10px arial;
    padding: 3px;
    margin: 3px;
    background-color: #ffc;
    border: 1px solid #c00;
}
Thats it! see how the validation works like a charm..
registererror.PNG

Advanced Validation

The following are some of bit advanced validation code that might help you.

To check password and password retype are same

?
CODE
1
2
3
4
5
6
7
8
<tr>
   <td>Password</td>
   <td><input name="pwd" type="text" id="pwd" class="required" minlength="5"></td>
 </tr>
 <tr>
   <td>Retype Password</td>
   <td><input name="pwdc" type="text" id="pwdc" class="required" equalTo="#pwd"></td>
 </tr>
To validate a website URL – optional field
It should check the URL and force the user to enter full url with http.
?
CODE
1
2
3
4
5
6
<tr>
           <td>Website </td>
           <td><input name="web" type="text" id="web2" class="optional defaultInvalid url">
             <span class="example">http://www.example.com</span></td>
         </tr>

To validate Phone Number

We dont want restrict phone numbers to be US only. Suppose if a foreign person enters a phone with + and dashes, we want that as well. To do this you will need to make slight change inside document.ready() in head section.
?
CODE
1
2
3
4
5
6
7
8
9
<script>
  $(document).ready(function(){
    $.validator.addMethod("NumbersOnly", function(value, element) {
        return this.optional(element) || /^[0-9\-\+]+$/i.test(value);
    }, "Phone must contain only numbers, + and -.");

  $.validator.addMethod("phoneValidate", function(value, element) {
        return this.optional(element) || /^[0-9\-\+\,\.\)\(\s]+$/i.test(value);
    }, "Only numbers,-,+ and , allowed");


 
    $("#regForm").validate();
  });
  </script>
and now you can validate specifying class=”required NumbersOnly”. This will allow only numbers 0-9, hyphen and + for country code.
?
CODE
1
2
3
4
<tr>
  <td>Phone</td>
  <td><input name="phone" type="text" id="phone" class="required NumbersOnly"></td>
</tr>

Validating Username with no special characters

We dont want username to contain any special characters like dot,slashes etc. We only want to allow alphabets, numbers and underscore.
We create a function similar way like above
?
CODE
1
2
3
4
5
6
7
8
9
<script>
  $(document).ready(function(){
    $.validator.addMethod("username", function(value, element) {
        return this.optional(element) || /^[a-z0-9\_]+$/i.test(value);
    }, "Username must contain only letters, numbers, or underscore.");
    $("#regForm").validate();
  });
  </script>
and now you can call using class=”required username”
?
CODE
1
2
3
4
5
6
<tr>
<td>User ID</td>
<td>
<input name="user_name" type="text" id="user_name" class="required username" minlength="4">
</td>
</tr>
Enjoy jQuery!