Advance File Upload in PHP

I’ll show you a so called advance file upload implementation in PHP.
Advance because we’ll be changing the file name of the uploaded file for some good reason. I’m sure you’re thinking why should we change the file name of the uploaded file. The reason for that is that every time we’ll upload a file, we are going to store it in our server.

So what happens now if the file name already exist in the server? PHP will automatically replace the file without letting us now, so it’s kinda weird.

Think of it this way:
User1 uploads a file called “document.doc“. Then, User2 uploads a file called “document.doc”(same file name with User1). Of course those 2 files have different content in it, they just have the same file name. PHP replaces the file of User1 into the file that was uploaded by User2. So now, you got my point. :)

Here’s what we’re going to do.
HTML

<form action="upload.php" method="post" enctype="multipart/form-data">
if( $_SESSION['img_upload_error'] ) echo $_SESSION['img_upload_error'];
     <label for="uploadImage">Upload Profile Picture</label>
     <input id="file" type="file" name="file" />
     <input type="submit" />
unset( $_SESSION['img_upload_error'] );
</form>

upload.php

$file = $_FILES['file'];
#this is a function that will get the file extension of the uploaded file
 $file_extension = GetFileExtension( $file['name'] );

#we will change the name of the file name at the same time we'll append the file extension
$fileName = GenerateRandomStringAndInt().".".$file_extension;

if ( $file["error"] > 0 ) #If there's an error, return back to the previous page
{
   $_SESSION['img_upload_error'] = "There was an error while uploading your image. Please try again";
   header( "location: ".$_SERVER['HTTP_REFERER'] ); #this would redirect user to the previous page
   exit;
}
else
 {
     #1MB, We are limiting the file upload into 1MB you can always change this one depending on your  preference.
     if( $file['size'] > 1024000 ) 
     {
        $_SESSION['img_upload_error'] = "There was an error while uploading your image. Please try again";
        header( "location: ".$_SERVER['HTTP_REFERER'] );
        exit;
     }

     #while the file is exsting in the server, replace the filename
     while( file_exists( "/files/" . $fileName ) ) #/files/ is the directory where we will store the files
        $fileName = GenerateRandomStringAndInt().$file_extension;

       move_uploaded_file( $file["tmp_name"], "/files/" . $fileName );
 }

function GetFileExtension( $filename )
{
   return pathinfo( $filename, PATHINFO_EXTENSION );
}

function GenerateRandomStringAndInt( $length = 15 )
{
    $characters = '0123456789abcdefghijklmnopqrstuvwxyz';
    $string ="";
    for ( $p = 0; $p < $length; $p++ ) {
        $string .= $characters[ mt_rand( 0, strlen( $characters ) ) ];
    }
    return $string;
}

Now you are golden! Just create a directory named  “files” so that we’ll store the files in there.

This is how easy to implement an Advance File Upload in PHP.

Hope this helps someone.

Have a happy coding! :)

Coding a Navigation Menu Bar with drop down subpages

Over the past days, I was thinking how to design a navigation menu bar that when you hover it, the sub pages will be shown. I know it’s sounds so easy but the challenging part are these:

  • CSSing the Navigation Bar
  • Designing the Database since will be implementing a sub page that has a sub page and so on and so forth(unlimited SUBs)…
  • Coding the design in PHP and HTML

So then, after days of combat I made my own. Thanks also to my thorough research.

I created 3 files. A class for calling the categories, the HTML and the CSS.

Here’s my Code:

HTML

<?php
     require_once 'categories.php';
     $cat = new Categories();
     $menu = $cat->get_menu();
?>
 <div id="access">
    <div id="nav">
      <div class="menu-header"><?= $menu; ?></div>
     </div>
 </div>

Categories.php (Click here for more info about this class)

<?php
class Categories
{
	var $exclude;
	var $depth;

	function __construct() {
		$this->exclude = array();
		$this->depth = 1;
	}

	function get_menu()
	{
		$nav_query = mysql_query("SELECT * FROM `categories` ORDER BY 'category_id'") or die( mysql_error() );

		$tree = "<ul class='menu'>";					// Clear the directory tree
		$this->depth = 1;					// Child level depth.
		$top_level_on = 1;			// What top-level category are we on?
		array_push($this->exclude, 0);	// Put a starting value in it

		while ( $nav_row = mysql_fetch_array( $nav_query ) )
		{
			$goOn = 1; // Resets variable to allow us to continue building out the tree.
			for( $x = 0; $x < count( $this->exclude ); $x++ )// Check to see if the new item has been used
			{
				if ( $this->exclude[$x] == $nav_row['category_id'] )
				{
					$goOn = 0;
					break; // Stop looking b/c we already found that it's in the exclusion list and we can't continue to process this node
				}
			}
			if ( $goOn == 1 )
			{
				#top category or in other words category who's parent_id is 0
				$tree .= "<li class='menu-item'><a href='#'>".$nav_row['name']."</a>"; // Process the main tree node
				array_push( $this->exclude, $nav_row['category_id'] ); // Add to the exclusion list

				if ( $nav_row['category_id'] < 6 )
				{ $top_level_on = $nav_row['category_id']; }

				$tree .= $this->build_child( $nav_row['category_id'] ); // Start the recursive function of building the child tree
				$tree .= "</li>";
			}
		}

		return $tree."</ul>";
		// echo "</ul>";
	}

	function build_child( $oldID )// Recursive function to get all of the children...unlimited depth
	{
		$child_query = mysql_query( "SELECT * FROM `categories` WHERE parent_id=" . $oldID ) or die( mysql_error() );
		$tempTree .= "<ul class='sub-menu'>";
		while ( $child = mysql_fetch_array( $child_query ) )
		{
			if ( $child['category_id'] != $child['parent_id'] )
			{
				$tempTree .= "<li class='menu-item'><a href='#'>" . $child['name'] . "</a>";
				$this->depth++;		// Incriment depth b/c we're building this child's child tree  (complicated yet???)
				$tempTree .= $this->build_child( $child['category_id'] ); // Add to the temporary local tree
				$this->depth--;		// Decrement depth b/c we're done building the child's child tree.
				array_push( $this->exclude, $child['category_id'] );			// Add the item to the exclusion list
			}
		}
		$tempTree .= "</li></ul>";
		return $tempTree;		// Return the entire child tree
	}

}
?>

CSS

#access {
	display: block;
	float: left;
	height: 31px;
	margin: 0 auto;
	width: 1000px;
}
#access .menu-header, div.menu {
	font-size: 13px;
	margin-left: 12px;
	width: 1000px;
}
#access .menu-header ul, div.menu ul {
	list-style: none outside none;
	margin: 0;
}
#access ul ul {
	box-shadow: 0 3px 3px rgba(0, 0, 0, 0.2);
	display: none;
	float: left;
	left: 0;
	position: absolute;
	top: 38px;
	width: 180px;
	z-index: 99999;
}
#access ul ul ul {
	left: 100%;
	top: 0;
}
#access .menu-header li, div.menu li {
	float: left;
	position: relative;
}
#access ul ul li {
	min-width: 180px;
}
#access li:hover > a, #access ul ul *:hover > a {
	background: none repeat scroll 0 0 #333333;
	color: #FFFFFF;
}

#access ul li:hover > ul{
	display: block;
}
#access ul ul a {
	background: none repeat scroll 0 0 #333333;
	height: auto;
	line-height: 1em;
	padding: 10px;
	width: 160px;
}
#access a {
	display: block;
	line-height: 34px;
	padding: 0 10px;
	text-decoration: none;
}

Now everything is just a piece of cake! Since this code is designed to be dynamic, there’s no worrying how many sub pages you’ll create.
The finish product would look like this:

Just edit the CSS and you’ll be golden!
Hope this help someone! Have a Happy Coding! :)

Designing a Parent/Child Tree Category in PHP and MySQL

I found this very cool code that I was searching for a long time. It’s about designing and coding a Parent and Child Tree Category. A scenario is something like Parent Category has a child category at the same time the child category also has a child category, so it’s like a category has an unlimited subcategory.

  • Automobile
    • Fuel
      • Gasoline
      • Diesel
    • Maintenance
  • Food
    • Fish
    • Pork

Here’s how to implement that one.

First create a database table named “categories” that has fields.

- category_id (PK int)
- parent_id (int)
- title (varchar)

PHP CODE

<?php
    $connect = mysql_connect("localhost", "root", "") or die ( mysql_error() );
    mysql_select_db("test");
    $nav_query = mysql_query("SELECT * FROM `categories` ORDER BY `category_id`") or die( mysql_error() );
    $tree = ""; // Clear the directory tree
    $depth = 1; // Child level depth.
    $top_level_on = 1; // What top-level category are we on?
    $exclude = array(); // Define the exclusion array
    array_push($exclude, 0); // Put a starting value in it

   while ( $nav_row = mysql_fetch_array($nav_query) )
   {
      $goOn = 1; // Resets variable to allow us to continue building out the tree.
      for($x = 0; $x < count($exclude); $x++ ) // Check to see if the new item has been used
      {
          if ( $exclude[$x] == $nav_row['category_id'] )
          {
             $goOn = 0;
             break; // Stop looking b/c we already found that it's in the exclusion list and we can't continue to process this node
          }
      }
      if ( $goOn == 1 )
      {
          $tree .= $nav_row['title'] . "<br>"; // Process the main tree node
          array_push($exclude, $nav_row['category_id']); // Add to the exclusion list
          if ( $nav_row['category_id'] < 6 )
          { $top_level_on = $nav_row['category_id']; }

          $tree .= build_child($nav_row['category_id']); // Start the recursive function of building the child tree
       }
    }

   function build_child($oldID) // Recursive function to get all of the children...unlimited depth
   {
       global $exclude, $depth; // Refer to the global array defined at the top of this script
       $tempTree = "";
       $child_query = mysql_query("SELECT * FROM `categories` WHERE parent_id=" . $oldID);
       while ( $child = mysql_fetch_array($child_query) )
       {
          if ( $child['category_id'] != $child['parent_id'] )
          {
             for ( $c=0;$c<$depth;$c++ ) // Indent over so that there is distinction between levels
             { $tempTree .= " "; }
             $tempTree .= "- " . $child['title'] . "<br>";
             $depth++; // Incriment depth b/c we're building this child's child tree (complicated yet???)
             $tempTree .= build_child($child['category_id']); // Add to the temporary local tree
             $depth--; // Decrement depth b/c we're done building the child's child tree.
             array_push($exclude, $child['category_id']); // Add the item to the exclusion list
          }
       }
       return $tempTree; // Return the entire child tree
     }

     echo $tree;

?>

This code would produce something like this

Isn’t that cool!?! Yes!

All credit belongs to hawkee!

Hope this helps someone. Have a happy coding! :)

How to get the previous page in php

Imagine how this works, your in http://your-site.com/page-A and then you go to http://your-site.com/page-b, question is how would you get the url of http://your-site.com/page-A.

It’s easy, just use

$_SERVER['HTTP_REFERER']

In this way, you can get the url of the previous page.
The $_SERVER is a pre defined variable that has lots of useful information, you can just check it out when you do

print_r($_SERVER);

Hope this helps someone!
Have a happy coding! :)

Adding a Facebook Feed Content of a Page in WordPress

Adding a facebook feed of a or a page is very easy, the idea here is simply getting the RSS feed of the profile you wish to have.

I’ll show you the simple steps on how to do this.

  • Logged in on your facebook page.
  • Searched for the page you wish to get the feed.
  • On the lower left hand side of the page, you can see this one

 

  • Right Click “Get Updates via RSS” then copy that link.
  • Now login to your wordpress wp-admin
  • Go to Appearance->Widget
  • Make sure that you have the RSS Widget

  • Drag that to the sidebar then paste the link that you copied below the word “Enter the RSS feed URL here:”

  • Hit save! Then you are golden!

I was really looking for a plugin that can do this one, but unfortunately, I didn’t see anything. The result of this one is not as pretty as like the one in Twitter. If ever you find a plugin similar to this one, just leave a comment below and your help would be greatly appreciated! :)

Hope this helps someone, Have a Happy Coding! :)

How to add an image in a menu in wordpress

I was working on a project that needs an image in a menu. First, I was thinking to modify the theme but it felt like it’s kinda silly to do that. I had this feeling that wordpress can support that functionality without being so geekish.

Guess What! I’m right! So now, i’ll show you how to add an image in a menu in wordpress.

  • Go to Appearance->Menus
  • Add a Custom Link
  •  Enter the url of the image when it is clicked. I only put “#” since I only wanted to show the image no redirection happening or whatsoever.
  • Here’s the interesting part. Did you know that you can put HTML tags in the Label, Yes! you read it right! You can put HTML tags in the label.  That is where you can put something like this <div><img src=”myImageSrc” /></div>. You can even put the inline CSS in there. So it looks like this:
  • Then hit “Add to Menu” ! Now you are golden! Refresh your page and see the beauty of your menu!

 

So that’s how easy to add an image in a menu in wordpress!

Have a happy coding! Cheers! :)