Showing posts with label file. Show all posts
Showing posts with label file. Show all posts

Monday, August 2, 2010

Dynamic Multiple File Uploads in PHP

I have a PHP script here which will let you specify the folder name and the number of files to be uploaded. Here is the preview.



This program has basic form validation and notifications on entering the data for the file uploads. You are free to copy the code and customize it the way you want it to be. I also provided comments in every lines of code for your guide in tracing or debugging.


<?php

// display open div wrapper
echo "<div class='wrapper'>";
// form for folder name and number of files
$num_form = "<form method=post>
    <table border='0' width='400' cellspacing='0' cellpadding='3' align=center>
    <tr><td>Folder Name</td><td>
    <input type=text name='fname' class='bginput'></td></tr>
    <tr><td>Number of Files</td><td>
    <input type=text name='num_imgs' class='bginput'></td></tr>
    <tr><td><input type=submit name='go' value='GO »' /></td></tr>
    </form>";


// check if the form for folder name and number of files was submitted
if(isset($_POST['go'])){
    //check if both fields were provided data
    if($_POST['fname']=='' || $_POST['num_imgs']==''){
       // notify the data error
       echo "<div class='notify'>Please provide data on both fields.</div>" . $num_form;
    }
    // check if the number of files is valid
    else if(number_format((int) $_POST['num_imgs']) == 0){
       // notify invalid number errors
       echo "<div class='notify'>Invalid number of images inputted.</div>" . $num_form;
    }
    else{
       // get the current directory path
       $thisdir = getcwd();
       // check if the directory already exists
       if(!is_dir($_POST['fname'])){
          // create the directory and change the file permissions
          mkdir(($thisdir.'/'.$_POST['fname']) , 0777);
}
       // form for file uploads
       $form = "<form method=post enctype='multipart/form-data'>";
       $form .= "<table border='0' width='400' cellspacing='0' cellpadding='0' align=center>";
       // input fields depending on the number of files entered
       for($i=1; $i<=$_POST['num_imgs']; $i++){
          $form .= "<tr><td>Image $i</td><td>
          <input type=file name='images[]' class='bginput'></td></tr>";
       }
       $form .= "<tr><td colspan=2 align=center><input type=submit name='add_image' value='Upload Files'></td></tr>";
       $form .= "<input type='hidden' name='fname' value=".$_POST['fname']." />";
       $form .= "</form> </table>";
       // display form file uploads
      echo $form;
    }
}
// check if form file uploads was submitted
else if(isset($_POST['add_image'])){
    // check file name was set
    if(isset($_FILES['images']['name'])){
       // counter for files uploaded
       $ctr = 0;
       // loop through all files to be uploaded
       while(list($key,$value) = each($_FILES['images']['name'])){
          // check if any blank field is entered
          if(!empty($value)){
             // increment counter
             $ctr++;
             // filename stores the value
             $filename = $value;
             // replace blank space with _
             $filename=str_replace(" ","_",$filename);
             //folder name
             $foldername = $_POST['fname'];
             // set upload directory path
             $add = "$foldername/$filename";
             // upload the file to the server
             copy($_FILES['images']['tmp_name'][$key], $add);
          }
       }
       // notify successful uploads
       echo "<div class='notify'>You have successfully uploaded $ctr file(s).</div>";
       echo "<br/><a href='multiple-uploads.php'><button>Upload more files »</button></a>";
    }
}
else{
    // display form for folder name and number of files
    echo $num_form;
}
// display close div wrapper
echo "</div";

?>


I have also here the CSS code for basic formatting of the program.


.wrapper {
    font-family:Verdana, Geneva, sans-serif;
    font-size:12px;
    width:420px;
    margin:0 auto;
    padding: 10px;
    background:#f4f4f4;
}

.notify{
    padding:2px 10px;
    background:#fff;
}

Tuesday, July 27, 2010

Force Download File Using PHP Header Function

Do you want to have a web page that has a script that can make a force download.


I have an example here using PHP to push the file to the browser. To trigger the download of the file, we will use HTML header statements. In PHP, this is possible using header function in passing raw HTML headers to the browser. In this example we will pass the filename in the url for instance - www.domainname.com/download.php?file=filename.zip. Of course, you can customize the codes according to the functionality of your website.


<?php

//path directory of the file
$dir="downloads/";
//cehck if there is a file passed
if (isset($_REQUEST["file"])) {
    //concatinate the directory and the filename
    $file=$dir.$_REQUEST["file"];
    //set HTML headers that must be sent to the browser.
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    //read the file
    readfile($file);
    exit;
}
else {
    //prompt if no file selected
    echo "No file selected";
}

?>


Click here for the php header manual

Friday, July 23, 2010

Create Zip Archive File using PHP ZipArchive

Do you want to place certain files on a zip archive file? In php this is possible using the ZipArchive class - a file archive, compressed with Zip. Below is the sample code program of this functionality.


<?php

//sample files in an array to be compressed
$files = array(
    'images/img1.png',
    'images/img2.png',
    'images/img3.png',
    'images/img4.png',
    'images/img5.png'
);

//returns true if creation succeed and false if zip creation failed
$result = create_zip($files,'my-archive.zip');

//function that creates a compressed zip file
function create_zip($files = array(),$destination = '',$overwrite = false) {
    //if the zip file already exists and overwrite is false, return false
    if(file_exists($destination) && !$overwrite) { return false; }
    //variable declaration
    $valid_files = array();
    //if files are valid
    if(is_array($files)) {
        //loops and check each file
        foreach($files as $file) {
            //check if file exists and store in array
            if(file_exists($file)) {
                $valid_files[] = $file;
            }
        }
    }
    //check if there are valid files
    if(count($valid_files)) {
       //create the zip archive object
       $zip = new ZipArchive();
       if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE :     ZIPARCHIVE::CREATE) !== true) {
           return false;
       }
        //add files to the object
        foreach($valid_files as $file) {
          $zip->addFile($file,$file);
        }

       //close the zip after adding the files
        $zip->close();

        //check if the destination file exists
        return file_exists($destination);
    }
    else {
        return false;
    }
}

?>