Developers Archive for April, 2007

Creating a Multi-File Upload Script in PHP

Creating a Multi-File Upload Script in PHP Wednesday, April 25th, 2007

From this article, we can learn how to upload more than one file at a time.

Step 1 : Basic form to get no.of Upload file required (uploadform1.php)<html>
<head>
<title>No.of Files to Upload</title>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″>
</head>

<html><head><title>No.of Files to Upload</title><meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″></head><body>
<form name=”form1″ method=”post” action=”uploadform2.php”>
<p>Enter the amount of boxes you will need below. Max = 9.</p>
<p>
<input name=”uploadNeed” type=”text” id=”uploadNeed” maxlength=”1″>
</p>
<p>
<input type=”submit” name=”Submit” value=”Submit”>
</p>
</form>
</body>
</html>

In above script, we can get maximum number of files need to be uploaded by user. We can set max upload boxes as 9. We can increase or decrease this to satisfy depending upon our project needs.

Step2 : Creating the Dynamic Form (uploadForm2.php)<html>
<head>
<title>Dynamic form</title>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″>
</head>

<html><head><title>Dynamic form</title><meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″></head><body>

<form name=”form1″ enctype=”multipart/form-data” method=”post” action=”processFiles.php”>
<p>
<?
// start of dynamic form
$uploadNeed = $_POST[’uploadNeed’];
for($x=0;$x<$uploadNeed;$x++){
?>
<input name=”uploadFile<? echo $x;?>” type=”file” id=”uploadFile<? echo $x;?>”>
</p>
<?
// end of for loop
}
?>
<p><input name=”uploadNeed” type=”hidden” value=”<? echo $uploadNeed;?>”>
<input type=”submit” name=”Submit” value=”Submit”>
</p>
</form>
</body>
</html>

In this page, We can create a simple HTML form with the value of the attribute “type” set to “file”. Within the form We cen put a block of code to start the for loop. We set $x to 0 and made it stop at the desired need by setting $x to be less than $uploadNeed – the value specified by the user. We also echo the $uploadNeed into a hidden input field to be carried over to the last page.

The key to making this all work however is the $x variable We are echoing right next to the uploadFile name. What this will do is append a number starting with 0 to the name. This in turn will make each upload field’s name unique.

Step3 : Creating a Multi-File Upload Script in PHP (processFiles.php)Here is the last page to complete our multiple upload tasks.

Here is the last page to complete our multiple upload tasks.<?
$uploadNeed = $_POST[’uploadNeed’];
// start for loop
for($x=0;$x<$uploadNeed;$x++){
$file_name = $_FILES[’uploadFile’. $x][’name’];
// strip file_name of slashes
$file_name = stripslashes($file_name);
$file_name = str_replace(”‘”,”",$file_name);
$copy = copy($_FILES[’uploadFile’. $x][’tmp_name’],$file_name);
// check if successfully copied
if($copy){
echo “$file_name | uploaded sucessfully!<br>”;
}else{
echo “$file_name | could not be uploaded!<br>”;
}
} // end of loop
?>

The first thing we do in this page is grab the uploadNeed from uploadForm2.php. We setup our for loop in the same fashion as the last page. The difference here though is we get the $_FILES name within the for loop. We assign this to the local variable name $file_name.

Next, we do a little parsing by adding the stripslashes and str_replace functions. The reason we add the stripslashes is due to file that may have apostrophes in their name; otherwise this will generate a parse error and prevent that file from being uploaded.

Notice once again how I add the $x variable, which in turn is a number, to the name of the $_FILES. By doing this the script now knows which file it is uploading.

We will use the copy function now to actually begin the upload process. The last thing We added was a simple if statement to check that the copy was successful and We echo that message out to the screen.

Clean URLs without mod_rewrite

Clean URLs without mod_rewrite Wednesday, April 25th, 2007

Introduction
As you may know, clean URLs can be made with Apache’s mod_rewrite, but you are able to make clean URLs with PHP only.

Contents
This tutorial is split up into the following parts:

  • Introduction
  • Method one
  • Implementing method one
  • Method two
  • Implementing method two
  • Conclusion

  • Method one

    The second method will take /users/2 and it’s purpose is to go to the users page on page 2.


    <?php
    $array = explode('/',$_SERVER['PATH_INFO']);
    array_shift($array);
    ?>

    PHP contains several predefined variables, one of them is $_SERVER[’PATH_INFO’]. To know what the first line does you must know the explode function. The explode function takes two arguments. The first is the seperator and the second is the string. The explode function takes the string and splits it up where the seperator is.

    array_shift removes the first key of an array.

    Implementing method one
    First you should put the above snippet in a file called something like clean_urls.php and include it on the top of your pages (or if you only have one page, just put it in the top).

    Here is how you could use it:


    <?php
    include 'clean_urls.php'; // Include the snippet
    $modules = array( // Define our array of valid modules
    ‘home’,
    ‘users’,
    ‘login’,
    ‘register’,
    ‘admin’,
    );

    $module = $array[0]; // The first key contains what we will use as our module
    $page = $array[1]; // The second key contains what we will use as the page number

    if(empty($module)) // We need a default module
    {
    $module = “home”;
    }

    if(in_array($module,$modules)) // Does the requested module exist?
    {
    include “./modules/{$module}.php”; // If yes: Include it
    }
    else {
    die(”Failed to load module ‘{$module}’”); // If no: Error message
    }
    ?>

    Then you would use the page variable for something useful in your module page.


    Method two

    The second method will convert /func/users/page/2 into what ?func=users&page=2 would have done.


    <?php
    $array = explode('/',$_SERVER['PATH_INFO']);
    for($i=1; $i

    Here the first line is the exact same line as in method one.

    Next we have a for loop. It starts by setting $i to 1, then it will run as longs as the second statement ($i<=count($array)-1) evaluates to true and by the end of each iteration it will add 2 to $i. Inside the loop we add to the $_GET variable.

    Implementing method two
    Method two is easy to implement. Just put the above snippet in a file called something like clean_urls.php and include it on each page.

    Conclusion
    As you see, clean URLs are very easy to make with PHP only. With only 2-4 lines, you can have clean URLs.

    Regular expression Basic tips

    Regular expression Basic tips Wednesday, April 25th, 2007

    PHP has two set of regular expression
    1. perl compatible
    2. Posix extended

    First we will take Perl-Compatible for our discussion
    The syntax for patten used for these functions resembles closely with the Perls regular expression syntax.

    First we will start with simple matches

    - ‘hai’ will directly match ‘hai’
    let us proceed with two special symbols ‘^’ & ‘$’

    ^ - do the match from the start
    ‘^hello’ will match the any string start with the word ‘hello’
    $- matches the end of the string
    ‘hello$’ - will match the any string ends with hello
    let us combine both ‘^hello$’ this will match a string that should start with ‘hello’
    and end with ‘hello’ ie it should only contain ‘hello’.

    Now we will take some more symbols *,+,?

    * - matches 0 or more quantifier
    + - matches 1 or more quantifier
    ? - matches 0 or 1 quantifier

    ‘as*’ - matches a string with ‘a’ followed by 0 or any number of ’s’
    ‘as+’ - matches a string with ‘a’ followed by at least one ’s’

    ‘as?’ - matches the string with ‘a’ followed by 0 or 1 ’s’.

    symbols {}- min/max quantifier

    ‘as{3}’ matches ‘asss’ ie ‘a’ and exactly 3 ’s’

    ‘as{2,3} matches ‘a’ followed by 2 to 3 ’s’

    ‘as{2,} matches ‘a’ followed by minimum 2 to n number of ’s’

    ‘as{,3}’ matches a followed by 0 to maximum 3 ’s’

    period ‘.’ quantifier

    ‘.’ - matches any character

    ‘a.*’ will match a followed by any character

    [] - class definition quantifier

    ‘[0-9]’ - matches digits from 0-9
    ‘[a-z]’ - matches characters from a-z
    ‘[A-Z]’ - matches characters from A-Z

    ex

    preg_match(’/[0-9]{2}-[0-9]{2}-[0-9]{4}/’,$string)

    will match formats like 12-12-2007

    preg_match(’/[0-9a-zA-Z]*/’,$string)

    will match digits and alphabets

    Splitting String to character Array

    <?php
    $str = ’string’;
    $chars = preg_split(’//’, $str, -1, PREG_SPLIT_NO_EMPTY);
    print_r($chars);
    ?>


    All material @ copyrighted by chrisranjana.com. If you want to link to this article you are welcome to do so. Unauthorized publication is strictly prohibited. This developer tutorial website contains articles by Php programmers , Software developers, Mysql programmers and asp c# programmers. This website also contains ajax tutorials and advanced mysql sql stored procedures and functions tutorials and sample codes.