Creating SEO friendly URL using htaccess

Creating SEO friendly URL requires a knowledge on how htaccess works. Not just that, you should also be familiar with Regular Expressions but I won’t cover that one in this post though since we’ll be focusing on putting those in htaccess. Now, let’s get our hands dirty.

For example:
http://mysite.com/profile.php?username=JuanDelaCruz

If you wanted that one to become
http://mysite.com/user/JuanDelaCruz/

This is what you’re going to do:

#RewriteEngine On
#RewriteCond %{REQUEST_FILENAME} !-d 
#RewriteCond %{REQUEST_FILENAME}\.php -f 
#RewriteRule ^(.*)$ $1.php

# Use the following rule if you want to make the page like a directory
RewriteCond %{REQUEST_URI} !^/user/profile.php
RewriteRule ^user/(.*[^/])$ user/$1/ [R=301,L]

# The following rewrite the other way round:
RewriteCond %{REQUEST_URI} ^/profile.php
RewriteCond %{THE_REQUEST} ^(GET|POST|HEAD|TRACE)\ /profile.php
RewriteCond %{QUERY_STRING} id=([^&]+)
RewriteRule ^profile.php$ user/%1?

There are comments, so hope you can understand it from there.
Hope this helps someone! Have a Happy Coding! :)

How to create a zip file in PHP

Howdy!

I will show you how to create a zip file in PHP. All the directory in your server will also be zipped in the code. I will use the ZipArchive class in php. It’s easy as 1 2 3 :)

function ListFiles($dir) {
	if($dh = opendir($dir)) {
		$files = Array();
		$inner_files = Array();
		while($file = readdir($dh)) {
			if($file != "." && $file != ".." && $file[0] != '.') {
				if( $dir == getcwd() )	continue;
				if(is_dir($dir . "/" . $file)) {
					$inner_files = ListFiles($dir . "/" . $file);
					if(is_array($inner_files)) $files = array_merge($files, $inner_files); 
				} else {
					array_push($files, $dir . "/" . $file);
				}
			}
		}

		closedir($dh);
		return $files;
	}
}

$zip = new ZipArchive();
$backupName = date("Y-M-d-h:i:a",time());
$filename = $backupName.".zip";
#Store the backup file in a Folder called 'Files'
if( $zip->open("Files/".$filename,ZIPARCHIVE::CREATE) !== TRUE ) {
	exit("Cannot open the archive file");
}
#Replace this one with your root directory
$directory = '/home/mysite/public_html';
foreach (ListFiles($directory) as $key=>$file){
        #do not include the backup files to be backed-up 
	if( strstr($file,getcwd()) != "" ) continue; 
	$zip->addFile($file);
}  
$zip->close();

To download the zip file, just access it through your browser, so mine is I put the zip file in a File Directory, so it should be something like this: http://mysite.com/File/ . It really depends.

Hope this helps someone! Have a happy coding!

Implementing Paypal Subscription API in PHP

I’m working on implementing Paypal Subscription API in PHP for the past weeks, I thought this was kinda complicated just like the DirectPayment method API. Guess what, it was just a piece of cake, i’ll show you my code:


<form name="_xclick" id="_xclick" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="image" src="http://www.paypal.com/en_US/i/btn/btn_subscribe_LG.gif" border="0" name="submit" alt="Make payments with PayPal - it's fast, free and secure!">
		<input type="hidden" name="cmd" value="_xclick-subscriptions">
		<input type="hidden" name="business" value="yourpaypalaccount@samplemail.com">
		<input type="hidden" name="currency_code" value="USD">
		<input type="hidden" name="no_shipping" value="1">
		<input type="hidden" name="a3" value="20">
		<input type="hidden" name="p3" value="1">
		<input type="hidden" name="t3" value="M">
		<input type="hidden" name="src" value="1">
		<input type="hidden" name="sra" value="1">
		<input type="hidden" name="return" value="http://mysite.com/return.php">
		<input type="hidden" name="cancel_return" value="http://mysite.com/cancel.php">
		<input type="hidden" name="item_name" value="Subscription Fee">
		<input type="image" src="http://www.paypal.com/en_US/i/btn/btn_subscribe_LG.gif" border="0" name="submit" alt="Make payments with PayPal">
</form>';

Here’s an explanation about that code, it’s pretty straightforward though.
a3 – amount to billed each recurrence
p3 – number of time periods between each recurrence
t3 – time period (D=days, W=weeks, M=months, Y=years)
return – Return URL after the user has paid
Cancel – the URL when the user clicks on Cancel on the Paypal Page

On this example, there will be a Subscription Button being displayed, and the user will have to click on the button so that they will be redirected to paypal’s website.

Subscribe Button

 

 

If you want something like there’s no user interaction, like there would be no user clicking, just use javascript in sending the form. Just like this:

<script>document.forms['_xclick'].submit();</script>

And don’t forget to wrap the form code with an echo. So it should look like this:

echo '<form name="_xclick" id="_xclick" action="https://www.paypal.com/cgi-bin/webscr" method="post" style="display:none;">
		<input type="hidden" name="cmd" value="_xclick-subscriptions">
		<input type="hidden" name="business" value="yourpaypalaccount@samplemail.com">
		<input type="hidden" name="currency_code" value="USD">
		<input type="hidden" name="no_shipping" value="1">
		<input type="hidden" name="a3" value="20">
		<input type="hidden" name="p3" value="1">
		<input type="hidden" name="t3" value="M">
		<input type="hidden" name="src" value="1">
		<input type="hidden" name="sra" value="1">
		<input type="hidden" name="return" value="http://mysite.com/return.php">
		<input type="hidden" name="cancel_return" value="http://mysite.com/cancel.php">
		<input type="hidden" name="item_name" value="Subscription Fee">
		<input type="image" src="http://www.paypal.com/en_US/i/btn/btn_subscribe_LG.gif" border="0" name="submit" alt="Make payments with PayPal">
		</form>';
echo "<script>document.forms['_xclick'].submit();</script>";

Just a piece of cake, right? I hope this helps someone.

Have a happy coding :)

jQuery break out of each loop statement

While I was coding in jQuery, I bumped in a very unusual error, it’s about using a break statement inside an each loop statement.
Here’s my code:

jQuery("input:checkbox").each(function(index) {
   if( jQuery(this).attr("checked") == "checked" )
   {
     checked = "ischecked";
     break;
   }
});

I just thought this would be the same in PHP.

But after trying so hard :D , I got the solution.
Just replace the break; with return( false );

Here’s the code:

jQuery("input:checkbox").each(function(index) {
   if( jQuery(this).attr("checked") == "checked" )
   {
     checked = "ischecked";
     return( false );
   }
});

So this is how to break out of jQuery each statement
Hope this helps someone!

Have a happy coding! :)

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! :)