Welcome on DoYourself.org

Have an tutorial and wanna public it ?

On this website you can add any type of tutorials , but first you must have an account . To create one just complete right inputs with your dates.

Members Login

Lost your password?

Not member yet? Sign-up!

Security Code

How do I expire a PHP session after 30 minutes?

Posted by CarcaBot on Tuesday, 11.10.09 @ 06:50am  •  Filled under Php  • (1) Comment  •   •  Views (171)  

You should implement a session timeout on your own. Both session.gc_maxlifetime and session.cookie_lifetime are not reliable. The reason for that is:

First:

session.gc_maxlifetime
session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and cleaned up. Garbage collection occurs during session start.

But the garbage collector is only started with a probability of session.gc_probability devided by session.gc_divisor. And using the default values for that options (1 and 100), the chance is only at 1%.

Furthermore the age of the session data is calculated on the file’s last modification date and not the last access date:

Note: If you are using the default file-based session handler, your filesystem must keep track of access times (atime). Windows FAT does not so you will have to come up with another way to handle garbage collecting your session if you are stuck with a FAT filesystem or any other filesystem where atime tracking is not available. Since PHP 4.2.3 it has used mtime (modified date) instead of atime. So, you won't have problems with filesystems where atime tracking is not available.

So it additionally might occur that a session data file is deleted while the session itself is still considered as valid.

And second:

session.cookie_lifetime
session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. […]

This does only affect the cookie lifetime. But the session itself may be still valid. It’s the server’s task to invalidate a session, not the client’s.

So the best solution would be to implement a session timeout on your own:

if (!isset($_SESSION['CREATED'])) {
    $_SESSION
['CREATED'] = time();
} else if (time() - $_SESSION['CREATED'] > 1800) {
   
// session started more than 30 minates ago
    session_destroy
();
    $_SESSION
= array();
}

You can scrap sessions after a certain lifespan by using the session.gc-maxlifetime ini setting:

ini_set('session.gc-maxlifetime', 60*30);

Manipulate Zip Files with PHP

Posted by CarcaBot on Sunday, 10.25.09 @ 08:48am  •  Filled under Php  • No comments  •   •  Views (175)  

Back in the olden days the easiest way to create zip files using php was to have the operating system (OS) do it. Sure, there were modules you could compile php with but really affected portability. So using the OS wasn’t too big of an issue but it still wasn’t optimal.

Zip Files

Zip Files

The Old Way

Assuming the OS was Linux, and if you were doing php web development it probably was, you’d execute a call like the below to create a gzipped archive:

<?php
exec(tar cfvz ".$WhereBackup."/".$Name.".tar.gz ".$whatBackup.");
?>

The above sucks for a couple reasons. For one, it requires a pretty large security hole to not be plugged; exec allows piping commands to the OS directly. For another, the above method will only work on Linux; Windows doesn’t have a “tar” command.

The biggest reason the above sucked, for me at least, was that the layman doesn’t understand the tar.gz file extension. I can’t count the number of times I’ve had to explain to a client or colleague that tar.gz is, as far as their needs go, that tar.gz is ok. “You can open it in WinZip or WinRar.”, I’d say. Sigh…

Enter PclZip

PclZip is a php class that creates and manage ZIP formatted archives. PclZip works on both Windows and Linux and is pretty easy to use. There’s a pretty extensive user manual too.

I first heard about it while writing the WordPress plugin iTunes-Data. I wanted to allow the upload of the iTunes XML files but mine was over 10MB so testing was becoming… inconvenient. I knew WordPress could manipulate zip archives so I took a look under the hood and the was PclZip.

Anyway, you can create zip files, remove files from existing zip files and extract zip files using the PclZip class. Below are a couple examples of how to do each.

The Basics

The most important thing to know about using PclZip is that the PclZip object must be instantiated with a “.zip” file being passed. It doesn’t matter if you’re creating, extracting or modifying, you have to pass the file you want to manipulate before you do anything else.

<?php
require_once('pclzip.lib.php');
$archive = new PclZip('tmp/archive.zip');
?>

Optional Arguments

PclZip allows for detailed control over archives through the use of optional arguments that get passed at the tail end of functions. According to the official site:

The optional arguments are identified by a name, which is in reality a static integer value. The value of the argument can be a single value or a list of values. In some cases they does not take a value, their name is enought to indicate a specific action to the method.

There’s far too many arguments you can use so I won’t bother listing them all here but there’s a complete list at the end of the article.

Create a Zip File

To create a zip file you have to pass the name of the archive you want to create to the object. The file passed will be where to the archive will be created.

You can include multiple files by either passing the directory, if you want the entire directory or by using a couple different methods to pass individual files and directories; arrays or a csv string.

<?php
require_once('pclzip.lib.php');
$archive = new PclZip('tmp/archive.zip');
 
//includes the file "debug.cl" and the directory "logs"
$files = './debug.cl,./logs/';
if ($archive->create($files) == 0) {
die('Error : '.$archive->errorInfo(true));
}
?>

or

<?php
require_once('pclzip.lib.php');
$archive = new PclZip('tmp/archive.zip');
 
//same as above
$files = array('./debug.cl','./logs/');
if ($archive->create($files) == 0) {
die('Error : '.$archive->errorInfo(true));
}
?>

Extracting Files from Archive

There are quite a few options for extracting files from a zip archive. PclZip contains a pretty extensive filtering mechanism that allows for some pretty selective extractions.

By default when extracting the files from an archive PclZip puts the files relative to where the script is executed.

$archive = new PclZip('tmp/archive.zip');
if ($archive->extract() == 0) {
die("Error : ".$archive->errorInfo(true));
}

You can explicitly state where the archive files are extracted by setting a value to the “PCLZIP_OPT_PATH” parameter. The below extracts all the files to the “./tmp” directory:

$archive = new PclZip('tmp/archive.zip');
if ($archive->extract(PCLZIP_OPT_PATH, "./tmp") == 0) {
die("Error : ".$archive->errorInfo(true));
}

Optional Argument List

PCLZIP_OPT_PATH
PCLZIP_OPT_ADD_PATH
PCLZIP_OPT_REMOVE_PATH
PCLZIP_OPT_REMOVE_ALL_PATH
PCLZIP_OPT_SET_CHMOD
PCLZIP_OPT_BY_NAME
PCLZIP_OPT_BY_EREG
PCLZIP_OPT_BY_PREG
PCLZIP_OPT_BY_INDEX
PCLZIP_OPT_EXTRACT_AS_STRING
PCLZIP_OPT_EXTRACT_IN_OUTPUT
PCLZIP_OPT_NO_COMPRESSION
PCLZIP_OPT_COMMENT
PCLZIP_OPT_ADD_COMMENT
PCLZIP_OPT_PREPEND_COMMENT
PCLZIP_OPT_REPLACE_NEWER
PCLZIP_OPT_EXTRACT_DIR_RESTRICTION
PCLZIP_OPT_ADD_TEMP_FILE_ON
PCLZIP_OPT_ADD_TEMP_FILE_THRESHOLD
PCLZIP_OPT_ADD_TEMP_FILE_OFF

How to unzip ZIP files with PHP

Posted by CarcaBot on Sunday, 10.25.09 @ 08:47am  •  Filled under Php  • No comments  •   •  Views (242)  

How to automatically unzip uploaded zip files with PHP

I wanted to upload a zip file with php script and unzip it within the server running PHP and linux. How to do it? i am documenting here about a solution to unpack uploaded zip files locally within the server with PHP.

well! it can be done in 3 ways. I

1. Using PHP exec command
2. suPHP (Alternative to PHPsuexec)
3. Get Pclzip class library. (create and extract ZIP files
4. Using Zziplib with PHP

I was successful with (3) option.

I tried the first option of using php exec command calling system level but it never worked for me and it just kept getting checkdir errors in my apache log.


  1. <?php  
  2. // uses  unzip command just like in commandline  
  3. //  
  4. //  
  5. echo system('unzip uploads/test.zip',$output);  
  6. print_r($output);  
  7.   
  8. ?> 
checkdir error: cannot create ithemex
unable to process xtheme/images/mini-archive.gif.
checkdir error: cannot create ithemex
unable to process itheme-x/images/mini-archive.png.

Using suPHP

suPHP is a good method just because instead of apache running as nobody/apache it runs under user account ownership. Basically what this means that it will have no problem with file permissions for zip files. Another great advantage of suphp is security (it restricts local users reading php files).

Unfortunately i couldnt use suphp because it needs PHP to be running as CGI, but mine was apache module. I couldnt use suPHP

Using Pclzip class for Zip files

This method worked best for me. I uploaded a zip and it cleanly unpacked within my server. Just download the pclzip class library. Set the folder permissions to 755 where you are unpacking the files. It need not be 777. If that 755 doesnt work set the ownership and usergroup to apache or nobody.

Now upload a sample zip file test.zip and put the following code in php file


  1. <?php  
  2.  require_once('pclzip.lib.php');  
  3.  $archive = new PclZip('test.zip');  
  4.  if (($v_result_list = $archive->extract(PCLZIP_OPT_PATH, 'uploads')) == 0) {  
  5.    die("Error : ".$archive->errorInfo(true));  
  6.  }  
  7.  echo "<pre>";  
  8.  var_dump($v_result_list);  
  9.  echo "</pre>";  
  10. >

PCLZIP_OPT_PATH, ‘uploads’ -> is the destination unzip folder (give it 777 or 755 permissions)

Just the php script and you will see error codes if any. In my case it worked perfectly fine unpacking the zip file. Refer to Pclzip documentation.

Note: You must have Zlib support installed for this script to work.
To install Zlib with PHP just do yum install zlib zip php-zip

zlibsupp.GIF

Dont forget to check apache logs to trace the exact error!

Perfect PHP Pagination

Posted by CarcaBot on Wednesday, 08.12.09 @ 10:12am  •  Filled under Php  • No comments  •   •  Views (33)  

Pagination is a topic that has been done to death -- dozens of articles and reference classes can be found for the management of result sets ... however (and you knew there was a "however" coming there, didn't you?) I've always been disgruntled with the current offerings to date. In this article I offer an improved solution.

Some pagination classes require parameters, such as a database resource and an SQL string or two, to be passed to the constructor. Classes that utilize this approach are lacking in flexibility - what if you require a different formatting of page numbers at the top and bottom of your pages, for example? Do you then have to modify some output function, or subclass the entire class, just to override that one method? These potential "solutions" are restrictive and don't encourage code reuse.

This tutorial is an attempt to further abstract a class for managing result pagination, thereby removing its dependencies on database connections and SQL queries. The approach I'll discuss provides a measure of flexibility, allowing the developer to create his or her very own page layouts, and simply register them with the class through the use of an object oriented design pattern known as the Strategy Design Pattern.

What Is the Strategy Design Pattern?

Consider the following: you have on your site a handful of web pages for which the results of a query are paged. Your site uses a function or class that handles the retrieval of your results and the publishing of your paged links.

This is all well and good until you decide to change the layout of the paged links on one (or all) of the pages. In doing so, you're most likely going to have to modify the method to which this responsibility was delegated.

1and1.com

A better solution would be to create as many layouts as you like, and dynamically choose the one you desire at runtime. The Strategy Design Pattern allows you to do this. In a nutshell, the Strategy Design Pattern is an object oriented design pattern used by a class that wants to swap behavior at run time.

Using the polymorphic capabilities of PHP, a container class (such as the Paginated class that we'll build in this article) uses an object that implements an interface, and defines concrete implementations for the methods defined in that interface.

While an interface cannot be instantiated, it can reference implementing classes. So when we create a new layout, we can let the strategy or interface within the container (the Paginated class) reference the layouts dynamically at runtime. Calls that produce the paged links will therefore produce a page that's rendered with the currently referenced layout.

Required Files

As I mentioned, this tutorial is not about the mechanics of how results are paged, but how to use an interface to implement this logic while retaining flexibility. I've provided as a starting point a class that contains functionality for registering primitive arrays or objects - the Paginated class -- as well as an interface that all of our page layouts must implement (PageLayout) and an implementation for a page layout (DoubleBarLayout). And all the code we'll use in the article is available for download.

A Basic Example

The following examples use an array of strings. Here's my data set:

  • Andrew
  • Bernard
  • Castello
  • Dennis
  • Ernie
  • Frank
  • Greg
  • Henry
  • Isac
  • Jax
  • Kester
  • Leonard
  • Matthew
  • Nigel
  • Oscar

However, this code could easily be extended to use an array of integers, characters, or other objects that have been fetched from a previous database call.

Here's how we'd use the Paginated class:

<?php
require_once "Paginated.php";

//create an array of names in alphabetic order
$names = array("Andrew", "Bernard", "Castello", "Dennis", "Ernie", Frank",   Greg", "Henry", "Isac", "Jax", "Kester", "Leonard", "Matthew", "Nigel", "Oscar");
 
$pagedResults = new Paginated($names, 10, 1);
 
echo "<ul>";
 
while($row = $pagedResults->fetchPagedRow()) {
 echo "<li>{$row}</li>";
}
 
echo "</ul>";
?>

First, we include the Paginated class and register an array with the constructor. The constructor takes three arguments, the final two of which are optional:

  1. The first parameter is the array of items to display -- as I mentioned, these can be primitive data types or more complex objects.

  2. The second parameter is the number of results we want to display on a page. By default, this figure is set to ten.

  3. The third parameter is the current page number.

In the above example, we've used the constant 1 to specify "page 1", however you're probably going to want to pass this as a parameter from the query string (more on this later). If an invalid page is supplied to the constructor, the page will default to 1.

By calling the fetchPagedRow method from within the while loop, our code iterates through the array, printing out the first ten names in the list (in this example, "Kester", "Leonard", "Matthew", "Nigel" and "Oscar" would be omitted). These items should be included on page two, but, as the image below illustrates, there are no links to page two yet! While Paginated will manage the access to any object registered by the programmer, the responsibility of publishing paged links is delegated to a class that implements the PageLayout interface.

The rendered list doesn't offer a link to page 2

Let's add some code to display the page numbers, then we'll dig a little deeper into the interior workings and flexibility of this class.

Create a new file with a PHP extension that contains the following code:

<?php
require_once "Paginated.php";
require_once "DoubleBarLayout.php";

//create an array of names in alphabetic order
$names = array("Andrew", "Bernard", "Castello", "Dennis", "Ernie", "Frank", "Greg", "Henry", "Isac", "Jax", "Kester", "Leonard", "Matthew", "Nigel", "Oscar");

$page = $_GET['page'];

$pagedResults = new Paginated($names, 10, 1);

echo "<ul>";

while($row = $pagedResults->fetchPagedRow()) {
 echo "<li>{$row}</li>";
}

echo "</ul>";

$pagedResults->setLayout(new DoubleBarLayout());
echo $pagedResults->fetchPagedNavigation();
?>

When we run the above script now, we'll see a list of the first ten names, as well as some additional orientation information shown in the image below. Our script now displays the text "Page 1", as well as a link to the second page that reads "next >".

The updated list includes page links

In the code snippet above, we've made use of a class called DoubleBarLayout, which implements the interface PageLayout and contains an implementation of the fetchPagedLinks method. This method takes two parameters: the Pagination object, and the query parameters that we want to attach to the hyperlinks (if any).

The great thing about this method is that it takes advantage of PHP's polymorphic capabilities, allowing the strategy that's currently registered to be called. It's therefore important for us to set the strategy first, before calling the method. Setting the strategy is done via a call to the setter method setLayout, which takes as a parameter an object that implements the PageLayout interface.

Hover over one of these links, and you'll notice that the parameter page and its value of 2 are included in the URL page number. However, in its current state, if you click this link to the second page, the names that we would expect to be rendered will not be displayed.

Let's see why this is the case by revisiting the constructor of Paginated.

The constructor takes three parameters:

  1. the array of primitive variables or objects to be processed

  2. the number of records to display

  3. the page number

Because the method fetchPagedNavigation writes a query parameter, we can replace our hardcoded value of 1 with the value held in $_GET['page']. This way, if the user manually modifies the value in the URL to something that's invalid, Paginated will default the page number to 1. How you choose to validate your GET parameters is up to you, though, so I won't dwell on this issue any further.

Flexibility in Page Layout Schemes

The flexibility of this class is accomplished via the PageLayout interface, which is part of the Paginated object. The PageLayout interface can reference any object that implements it, and calls to the Paginated method fetchPagedNavigation will cause the currently registered object to be referenced. If you haven't used interfaces before, this may seem a little confusing, but basically the end result is that the correct code will be called, and our results will be correctly spread over multiple pages.

To implement this technique, all you need to do is create a layout strategy that implements the PageLayout interface. Then, provide an implementation for the method fetchPagedLinks.

This method takes two parameters:

  1. $parent, which is the Paginated object

  2. $queryVars, which is the list of query parameters to append to the page numbers (and is optional)

There are three important points to note here:

  1. You'll never be making direct calls to fetchPagedLinks. All methods of Paginated can be accessed through the parent object.

  2. If you want to use your own page layouts, you must change the layout of the paginated result via calls to setLayout.

With those points in mind, let's create our own page layout! We'll call it TrailingLayout. Here's the code:

<?php
class TrailingLayout implements PageLayout {

 public function fetchPagedLinks($parent, $queryVars) {
 
   $currentPage = $parent->getPageNumber();
   $totalPages = $parent->fetchNumberPages();
   $str = "";

   if($totalPages >= 1) {
   
     for($i = 1; $i <= $totalPages; $i++) {
   
       $str .= " <a href=\"?page={$i}$queryVars\">Page $i</a>";
       $str .= $i != $totalPages ? " | " : "";
     }
   }

   return $str;
 }
}
?>

The above class, TrailingLayout, implements the PageLayout interface, and provides implementation for fetchPagedLinks. Remember the parameter $parent is an instance of the Paginated object, so we can determine the current page, and the total number of pages, by making calls to getPageNumber and fetchNumberPages, respectively.

In this simple layout, once there's more than a single page, the script will loop through the array of pages, and create a hyperlink and page number for each one. The $queryVars are also written to the href as part of this loop; the parameter $queryVars comes in handy when we're paging the results of a search that may have included a few parameters.

Note that the string "Page" is not a part of the queryVars, but is written by the loop that appends the page numbers to the string.

Now let's try implementing our new layout:

<?php
require_once "Paginated.php";
//include your customized layout
require_once "TrailingLayout.php";

//create an array of names in alphabetic order. A database call could have retrieved these items
$names = array("Andrew", "Bernard", "Castello", "Dennis", "Ernie", "Frank", "Greg", "Henry", "Isac", "Jax", "Kester", "Leonard", "Matthew", "Nigel", "Oscar");

$page = $_GET['page'];

$pagedResults = new Paginated($names, 10, $page);

echo "<ul>";

while($row = $pagedResults->fetchPagedRow()) {
 echo "<li>{$row}</li>";
}

echo "</ul>";

//$pagedResults->setLayout(new TrailingLayout());
echo $pagedResults->fetchPagedNavigation("&firstLetter=l");
?>

If we were to run the script above as is, we'd get the following error message:

"Fatal error: Call to a member function fetchPagedLinks() on a non-object".

This error occurs because we haven't yet registered the strategy that we wish to use before calling fetchPagedNavigation. To change the layout of the paged links, we pass to the setLayout method a parameter, which can be any object that implements the PageLayout interface. In the code from our TrailingLayout example above, uncomment the second-last line of PHP code, and refresh your page to see the final result, shown below.

The finished list

The last line in that code demonstrates how the fetchPagedNavigation method can take an optional parameter string to define the rest of the query (note the inclusion of the ampersand before the firstLetter parameter in the URL to distinguish it from the page parameter).

Summary

In this article, I introduced the Strategy Design Pattern, which can be used to provide flexibility when you're laying out paged links.

We saw this pattern in action through the Paginated class, which will hopefully prove useful to you when you're displaying data across multiple pages. The class can be used to display arrays containing primitive data types or more complex objects.

How to get a page's Google PageRank (PR) with PHP

Posted by CarcaBot on Friday, 07.24.09 @ 10:28am  •  Filled under Php  • No comments  •   •  Views (29)  

I was recently looking for an easy way to lookup the Page Rank for a given page, site or really any URL. I've seen lots of tools out that that can do it, and many of them allow you to integrate the tool into your site. But those require a lot of extra work, and they just really display the PR. I wanted to actually retrieve the value with PHP. Doing a quick search on google revealed a Google PageRank class from phpclasses.org. It seems to be pretty robust, and it looks like it will do the job!

Determine a visitor's location by their IP address!

Posted by CarcaBot on Friday, 07.24.09 @ 10:28am  •  Filled under Php  • No comments  •   •  Views (47)  

Tracking a visitor's geographical location (ie. country, region, city, latitude, longitude, ZIP code, ISP and domain name) used to be a cool trick. Now it is an integral part of many websites, enabling them to identify the locations from where they're getting the maximum traffic; and tune your webpages accordingly. It also enables you to modify the site according to location, or send users to specific sections (ie. show prices in CAD for Canadian visitors).

It is relatively easy to use this technology on your website with IP2Location's proprietary IP address lookup database. This database is free for the IP-Country version. Of you need more details like region, city, latitude, longitude, ZIP code, ISP and domain name for the IP address, you need to purchase the full database.

To determine the user's location by their IP address, you need to perform these three steps:

1. Retrieve the visitors' IP address
Here are the functions to get the IP address using ASP, PHP, an .Net (C# & VB.Net).

2. Convert the visitor's IP address to an IP Number
Here are the functions to convert an IP address to an IP number using ASP, PHP, an .Net (C# & VB.Net).

3. Locate the IP Number in the IP-Country database
Example: the IP Address 202.186.13.4 converts to IP Number 3401190660. It is between the beginning and the ending of the following IP numbers:
"3401056256","3401400319","MY","MALAYSIA"

From the IP-Country recordset, the Country_Name with this IP number range is Malaysia, the Country_Code is MY.

So once you have the IP Number, here's the SQL Query to locate the matching recordset:

SELECT country_name FROM ip_to_country WHERE
[your IP number] BETWEEN ip_start AND ip_end Of course, you need to download the IP2Country database.

How to retrieve a visitor's IP address

Posted by CarcaBot on Friday, 07.24.09 @ 10:28am  •  Filled under Php  • No comments  •   •  Views (27)  

Every visitor to your site or web application has an IP address. It is quite handy to be able to get that address. It can be used for security logging, or perhaps tracing. It can also be used to determine where they are in the world, or at least where their ISP is.

The difficulty is when they're behind a proxy of some sort, you only see the IP address of the proxy server. So, here are the code snippets in PHP, ASP and .Net that first check for an IP addresses that's forwarded from behind a proxy, and if there's none then just get the IP address.

Here it is in PHP

<?
    if (getenv(HTTP_X_FORWARDED_FOR)) {
        $ip_address = getenv(HTTP_X_FORWARDED_FOR);
    } else {
        $ip_address = getenv(REMOTE_ADDR);
    }
?> And here's how to get the IP address in ASP

<%
    ip_address = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
    if ip_address = "" then
        ip_address = Request.ServerVariables("REMOTE_ADDR")
    end if
%> And here's the IP retriever with proxy detection in .Net (C#)

public string IpAddress()
{
    string strIpAddress;
    strIpAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    if (strIpAddress == null)
    {
       strIpAddress = Request.ServerVariables["REMOTE_ADDR"];
    }
    return strIpAddress;
} And here's the same IP retriever with proxy detection in .Net, but in VB.Net

Public Function IpAddress()
    Dim strIpAddress As String
    strIpAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
    If strIpAddress = "" Then
       strIpAddress = Request.ServerVariables("REMOTE_ADDR")
    End If
    IpAddress = strIpAddress
End Function

PHPCart payment processor for Chase Paymentech (Orbital)

Posted by CarcaBot on Friday, 07.24.09 @ 10:28am  •  Filled under Php  • No comments  •   •  Views (37)  

I was working on a project recently, implementing the PHPCart ecommerce shopping cart solution. The merchant uses Chase Paymentech as their credit card processor, and the PHPCart website mentioned that there was a gateway already made. However, I quickly found out that there wasn't so I had to code one myself! So I'm offering it up for free as open source. Download the php chase payment gateway.

You need to place it in the 'processor/' directory of the PHPCart installation. It has the following features:

  • Configure your merchant #
  • Configure your Terminal ID
  • Configure your BIN #
  • Specify the credit cards you accept (I suggest "Visa,MasterCard,American Express,Discover,JCB")
  • Creates the proper expiry date with only the last two chars of the years from PHPcart
  • Chase processors dollar amount with implied decimal, so that's taken out
  • Converts the credit card name into the Chase approved format
  • You can uncomment line 39 and comment line 40 to switch to the testing server before you're certified.

Anyhow, enjoy! If there are any enhancements or modifications you make, feel free to tell me about them.

Build an image slideshow with PHP & JavaScript

Posted by CarcaBot on Friday, 07.24.09 @ 10:28am  •  Filled under Php  • No comments  •   •  Views (25)  

There are numerous scripts out there that use PHP to scan the contents of a particular directory, and create a "gallery" of sorts from all of the images in the folder. There are also JavaScripts out there that allow you to rotate between images in a gallery without refreshing the page – thus creating a slideshow on the page. Well, without having to know too much PHP or JavaScript, you can now have both of those capabilities in one easy to configure PHP class!

This open source PHP class is used to present images in a slide show without reloading the current page. It automatically generates the necessary HTML and Javascript to display the listing of images, on the page. Best of all, the images are scanned from a list of files in a server side directory, which means that you can just upload a new image and it will be there!

You can also easily configure the delay time between switching the images on the page.

How to parse a CSV file with PHP

Posted by CarcaBot on Friday, 07.24.09 @ 10:28am  •  Filled under Php  • No comments  •   •  Views (32)  

It's a very common feature request in any web application to be able to upload data in a CSV file rather than having to manually enter every single item. In that case, you need to build in some intelligence to be able to parse the data from the CSV file.

Well, I love the fact that no programming problem is unique, and many people have done this very thing before you. So, here's someone that's been kind enough to share freely the PHP class they built that can
parse and display data from a CSV file. (Here's the link)

Basically, it opens and parses the lines of a provided CSV file. The data is then stored in an array class variable. The class can also be used to display the CSV data in an HTML table. And you can customize the layout of the display by using a separate PHP template script. Not bad!