Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Upload/download manager. 1

Status
Not open for further replies.

sd0t1

IS-IT--Management
Mar 14, 2007
131
US
thread434-1246898

I have created a upload/download script that stores .pdf's in as blobs.

The problem is they get corrupted when I try to open or save(then open) them.

I read what Jpadie said about storing these .pdf's in a file structure vs. a blob and am greatly considering changing to a file structure.

What I'm looking for now is a good upload/download script.

Jpadie, you referenced one that you created for another user. The link to it no longer works. Is it possible that you still have it handy somewhere that you can send it to me?


Here is the link you were talking about.


Thanks for your help.
 
sorry that site got taken down a long time ago.

to store a pdf in a blob you could use something very crude like this

Code:
<?php
//load database up
mysql_connect($server, $user, $pass) or die(mysql_error());
mysql_select_db($dbName) or die(mysql_error());

set_magic_quotes_runtime(false);
function cleanse($var){
  return  get_magic_quotes_gpc() ? stripslashes($var) : $var;
}

function showUploadForm(){
?>
<form method="post" enctype="multipart/form-data" action="upload.php">
<input type="file" name="upload" /><input type="submit" name="submit" value="Upload"/>
</form>
<?php	
	listFiles();
}

function processUpload(){
	if ($_FILES['upload']['error'] == UPLOAD_ERR_OK):
		$query = "Insert into storageTable (id, filename, file) values (NULL, '%s', '%s')";
		$query = sprintf(
							$query,
							mysql_real_escape_string(cleanse($_FILES['upload']['name'])),
							mysql_real_escape_string(file_get_contents($_FILES['upload']['tmp_name'])) );
     	$result = @mysql_query($query);
		if ($result == false):
			echo mysql_error();
		else:
			echo 'File uploaded ok<br/>';
		endif;
  	else:
		echo "Error uploading the file";
	endif;
	showUploadForm();
}

function serveDownload($id){
	$result = mysql_query(	sprintf("select * from storageTable where id=%d", intval($_GET['id']))) 
				or die (mysql_error());
	$row = mysql_fetch_assoc($result);
	if (empty($row)):
		echo 'No file available<br/>';
		listFiles();
	else:
		header("Content-type: application/pdf");
		header('Content-Disposition: attachment; filename="' .  $row['filename'] . '"');
		header("Content-Length: ".strlen($row['file']) );
		echo $row['file'];
		exit;
	endif;
}

function listFiles(){
	$result = mysql_query("select * from storageTable");
	echo "<ul>";
	while ($row = mysql_assoc($result)):
		echo <<<HTML
<li><a href="?action=serveFile&amp;id={$row['id']}">{$row['filename']}</a></li>
HTML;
	endwhile;
	echo "</ul>";
}
if ( isset($_POST['submit']) && $_POST['submit'] == 'Upload'):
	processUpload();
elseif(isset($_GET['action']) && $_GET['action'] == 'serveFile' && isset($_GET['id'])):
	serveDownload($_GET['id']);
else:
	showUploadForm();
endif;

?>
 
ok, I'm having a pretty strange problem. I have created a dashboard for a site. the dashboard gives the user a quick view and ability to interact with the six main areas of the site.

view/add assets
view/add payments
view/add notes
view/change case info
view/add case notes
view/upload files

The problem is the upload files manager. I've created it 2 ways. The first way, I stored the files documents (.pdf's) in the database as blob's. however I received an adobe error when I tried to view them. The error said "Adobe could not open 'file[1].pdf' because it is either not a supported file type or because the file has been damaged...".

So I thought it was related to storing files as blobs.

I read your post from a while back and decided to change the upload script to store in directories instead of the database.

Well that produced the same error when I try to view the files.

Ok, now for the strange part.

Both the blob and directories scripts worked during testing it was only when I implemented them into the dashboard page that they both stopped working.
Even now If I remove the code and put it in a stand alone page, both scripts still work, meaning the .pdf's don't get corrupted when I try to view them.

When I store them in a file system, if I browse the file structure on the server and open the pdf's directly, they are not corrupted and open right up.

It appears there's something on my dashboard page that is making the .pdf's not viewable.

I know the code is super long, but I think I may need to show it in order to get help.

Here is the file system code in stand alone mode and it works fine: There error starts at line 42 when "if(isset(download))" is ran.

Code:
<?php
include("upload_class.php"); //classes is the map where the class file is stored (one above the root)
$pq_id = 69;

if (!is_dir("files/$pq_id/")){
    mkdir("files/$pq_id/", 0700);
}
$folder = "files/$pq_id/";


error_reporting(E_ALL);
function select_files($dir) {
    // removed in ver 1.01 the globals 
    $teller = 0;
    if ($handle = opendir($dir)) {
        $mydir = "<p>These are the files in the directory:</p>\n";
        $mydir .= "<form name=\"form1\" method=\"post\" action=\"".$_SERVER['PHP_SELF']."\">\n";
        $mydir .= "  <select name=\"file_in_folder\">\n";
        $mydir .= "    <option value=\"\" selected>...\n";
        while (false !== ($file = readdir($handle))) {
            $files[] = $file;
        }
        closedir($handle); 
        sort($files);
        foreach ($files as $val) {
            if (is_file($dir.$val)) { // show only real files (ver. 1.01)
                $mydir .= "    <option value=\"".$val."\">";
                $mydir .= (strlen($val) > 30) ? substr($val, 0, 30)."...\n" : $val."\n";
                $teller++;    
            }
        }
        $mydir .= "  </select>";
        $mydir .= "<input type=\"submit\" name=\"download\" value=\"Download\">";
        $mydir .= "</form>\n";
    }
    if ($teller == 0) {
        echo "No files!";
    } else { 
        echo $mydir;
    }
}
if (isset($_POST['download'])) {
    $fullPath = $folder.$_POST['file_in_folder'];
    if ($fd = fopen ($fullPath, "rb")) {
        $fsize = filesize($fullPath);
        $path_parts = pathinfo($fullPath); 
        $ext = strtolower($path_parts["extension"]); 
        switch ($ext) {
            case "png":
            case "bmp":
            case "gif":
            header("Content-type: image/".$ext.""); 
            header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");
            break;
            case "pdf":
            header("Content-type: application/pdf");
            header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); 
            break;
            case "zip":
            header("Content-type: application/zip"); 
            header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
            break;
            default;
            header("Content-type: application/octet-stream");
            header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
        }
        header("Content-length: $fsize");
        header("Cache-control: private"); 
        while(!feof($fd)) {
            $buffer = fread($fd, 2048);
            echo $buffer;
        }
    }
    fclose ($fd);
    exit;
}
function del_file($file) {
    $delete = @unlink($file); 
    clearstatcache();
    if (@file_exists($file)) { 
        $filesys = eregi_replace("/","\\",$file); 
        $delete = @system("del $filesys");
        clearstatcache();
        if (@file_exists($file)) { 
            $delete = @chmod ($file, 0775); 
            $delete = @unlink($file); 
            $delete = @system("del $filesys");
        }
    }
}
function get_oldest_file($directory) {
    if ($handle = opendir($directory)) {
        while (false !== ($file = readdir($handle))) {
            if (is_file($directory.$file)) { // add only files to the array (ver. 1.01)
                $files[] = $file;
            }
        }
        if (count($files) <= 12) {
            return;
        } else {
            foreach ($files as $val) {
                if (is_file($directory.$val)) {
                    $file_date[$val] = filemtime($directory.$val);
                }
            }
        }
    }
    closedir($handle);
    asort($file_date, SORT_NUMERIC);
    reset($file_date);
    $oldest = key($file_date);
    return $oldest;
}



$max_size = 1024*250; // the max. size for uploading
    
$my_upload = new file_upload;

$my_upload->upload_dir = "files/$pq_id/"; // "files" is the folder for the uploaded files (you have to create this folder)
$my_upload->extensions = array(".png", ".zip", ".pdf"); // specify the allowed extensions here
// $my_upload->extensions = "de"; // use this to switch the messages into an other language (translate first!!!)
$my_upload->max_length_filename = 50; // change this value to fit your field length in your database (standard 100)
$my_upload->rename_file = true;
        
if(isset($_POST['docUpload'])) {
    $my_upload->the_temp_file = $_FILES['upload']['tmp_name'];
    $my_upload->the_file = $_FILES['upload']['name'];
    $my_upload->http_error = $_FILES['upload']['error'];
    $my_upload->replace = (isset($_POST['replace'])) ? $_POST['replace'] : "n"; // because only a checked checkboxes is true
    $my_upload->do_filename_check = (isset($_POST['check'])) ? $_POST['check'] : "n"; // use this boolean to check for a valid filename
    $new_name = (isset($_POST['name'])) ? $_POST['name'] : "";
    if ($my_upload->upload($new_name)) { // new name is an additional filename information, use this to rename the uploaded file
        $full_path = $my_upload->upload_dir.$my_upload->file_copy;
        $info = $my_upload->get_uploaded_file_info($full_path);
        // ... or do something like insert the filename to the database
    }
}
?> 
<SCRIPT language="JavaScript">

function submitForm()
{
  document.form1.submit();
}
</script>
<form name="form1" id="form1" enctype="multipart/form-data" method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
<table width="400" height="245" border="0">
  <tr>
    <td height="37" colspan="2">Document Information</td>
  </tr>
  <tr>
    <td width="103" height="30" valign="top"><label for="upload">Select a file...</label></td>
    <td width="281" valign="top"><input type="file" name="upload" size="30"></td>
    </tr>
  <tr>
    <td height="28" valign="top">New file name</td>
    <td valign="top"><input type="text" name="name" size="25">
      (no extension) </td>
    </tr>
  <tr>
    <td height="22" valign="top"> <label for="replace">Replace </label></td>
    <td valign="top"><input type="checkbox" name="replace" value="y"></td>
    </tr>
  <tr>
    <td height="22" valign="top"><label for="check">Validate</label></td>
    <td valign="top"><input name="check" type="checkbox" value="y" checked></td>
    </tr>
  <tr>
    <td height="23" valign="top"> <a href='javascript: submitForm()'>Upload</a></td>
    <td valign="top"><?php echo $my_upload->show_error_string(); ?></td>
  </tr>
  <tr>
    <td height="21" valign="top"><input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_size; ?>" />
      <input type="hidden" name="pq_id" id="pq_id" value="<?php echo $pq_id;?>" />
      <input type="hidden" name="docUpload" value="docUpload" /></td>
    <td valign="top"><p>
      <?php if (isset($info)) echo "<blockquote>".nl2br($info)."</blockquote>"; ?>
    </p></td>
  </tr>
  <tr>
    <td height="21" valign="top">&nbsp;</td>
    <td valign="top"><?php echo select_files($folder); ?></td>
  </tr>
  </table>
</form>
Now here is the entire dashboard script and the same code as above produces an error when ran within the rest of this code.
Again, sorry it's so long - i didn't know what else to do.
An easy way to navigate this code is that there are 6 divs at the bottom representing the 6 areas. the div in question is the "Document" div which is the upload/download manager.

Code:
<?php 
session_start();


$req_sec_level =  array("Administrator" , "IT");
security_check($_SESSION['loggedUser'],$_SESSION['role'], $req_sec_level);


//////////////////////////////////////////////////////////
//                                                        //
//            Set PQ_ID  Code                                  //                            
//                                                        //
//////////////////////////////////////////////////////////
if(isset($_GET['pq_id']))
{
$pq_id = mysql_real_escape_string($_GET['pq_id']);
}
elseif (isset($_POST['pq_id']))
{
$pq_id = mysql_real_escape_string($_POST['pq_id']);    
}

//////////////////////////////////////////////////////////
//                                                        //
//            Asset   Code                                  //                            
//                                                        //
//////////////////////////////////////////////////////////

$fi = 1;
$sql3 = "SELECT * FROM finance WHERE pq_id = '$pq_id' AND code = 'I'";
$result3 = mysql_query($sql3) or die(mysql_error());

while ($row_finance = mysql_fetch_array($result3))
{
    if($fi % 2){$fcolor = '#FFFF99';}else{$fcolor = '';}
    $income .= "<tr bgcolor='$fcolor'><td>$row_finance[name]</td><td>$row_finance[source]</td><td>$row_finance[amount]</td><td></td></tr>";
    $fi++;
    $total_income = $total_income + $row_finance['amount'];
}


$ei = 1;
$sql4 = "SELECT * FROM finance WHERE pq_id = '$pq_id' AND code = 'E'";
$result4 = mysql_query($sql4) or die(mysql_error());

while ($row_expense = mysql_fetch_array($result4))
{
    if($ei % 2){$ecolor = '#FFFF99';}else{$ecolor = '';}
    $expense .= "<tr bgcolor='$ecolor'><td>$row_expense[name]</td><td>$row_expense[source]</td><td>$row_expense[amount]</td><td></td></tr>";
    $ei++;
    $total_expense = $total_expense + $row_expense['amount'];
}

$total_net = $total_income - $total_expense;


//////////////////////////////////////////////////////////
//                                                        //
//             Info Packet Code                             //                            
//                                                        //
//////////////////////////////////////////////////////////

if ($_POST['trigger4'] == 'Packet')
{
$info_pack_rec = mysql_real_escape_string($_POST['info_pack_rec']);
$info_pack_sent = mysql_real_escape_string($_POST['info_pack_sent']);
$pq_id = mysql_real_escape_string($_POST['pq_id']);

if($info_pack_rec != '' && $info_pack_sent != '')
{
 $statement = "SET info_pack_sent = '$info_pack_sent', info_pack_rec = '$info_pack_rec'";    
}
elseif($info_pack_rec == '' && $info_pack_sent != '')
{
 $statement = "SET info_pack_sent = '$info_pack_sent'";    
}
elseif($info_pack_rec != '' && $info_pack_sent == '')
{
 $statement = "SET info_pack_rec = '$info_pack_rec'";    
}

$sql = "UPDATE prequal $statement WHERE pq_id = '$pq_id'";
mysql_query($sql) or die(mysql_error());

}

//////////////////////////////////////////////////////////
//                                                        //
//              NOTE  Code                                  //                            
//                                                        //
//////////////////////////////////////////////////////////

if ($_POST['trigger3'] == 'Note')
{
$note = mysql_real_escape_string($_POST['note']);
$pq_id = mysql_real_escape_string($_POST['pq_id']);

$sql = "INSERT INTO contact_notes (pq_id, contact_note) VALUES ('$pq_id', '$note')";
mysql_query($sql) or die(mysql_error());
}


$ni = 1;

$sql1 = "SELECT * FROM contact_notes WHERE pq_id = '$pq_id'";
$note_result = mysql_query($sql1) or die(mysql_error());
while ($nrow = mysql_fetch_array($note_result))
{
    if($ni % 2){$ncolor = '#FFFF99';}else{$ncolor = '';}
    $c_note .= "<tr bgcolor='$ncolor'><td>$nrow[date]</td><td>$nrow[user]</td><td>$nrow[contact_note]</td></tr>";
    $ni++;
    
}



//////////////////////////////////////////////////////////
//                                                        //
//         Populate Main Client Data                        //                            
//                                                        //
//////////////////////////////////////////////////////////

$sql = "SELECT prequal.client, prequal.vet_fname, prequal.vet_mname, prequal.vet_lname, prequal.vet_ssn, prequal.spo_fname, prequal.spo_mname, prequal.spo_lname, prequal.referral, prequal.lcp, prequal.lcp_fname, prequal.lcp_lname, prequal.lcp_phone, prequal.lcp_email, prequal.lcp_release, prequal.initial_contact, prequal.info_pack_sent, prequal.info_pack_rec, prequal.case_status, 
payment.amount, payment.check_num, payment.date_rec, payment.pq_id
FROM prequal LEFT JOIN 
payment ON prequal.pq_id = payment.pq_id
WHERE prequal.pq_id = '$pq_id'";

$mresult = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($mresult))
{
    if($row['client'] == 1 || $row['client'] == 0)
    {$client_name = $row['vet_lname'].",  ".$row['vet_fname']."  ".$row['vet_mname'];}
    else
    {$client_name = $row['spo_lname'].",  ".$row['spo_fname']."  ".$row['spo_mname'];}
    $ssn = substr($row['vet_ssn'],0,3)."-".substr($row['vet_ssn'],3,2)."-".substr($row['vet_ssn'],5);
    $facility = $row['lcp'];
    $facility_contact = $row['lcp_lname'].",  ".$row['lcp_fname'];
    $facility_phone = $row['lcp_phone'];
    $facility_email = $row['lcp_email'];
    $referral = $row['referral'];
    $status = $row['case_status'];
    $initial_contact = $row['initial_contact'];
    $info_pack_sent = $row['info_pack_sent'];
    $info_pack_rec = $row['info_pack_rec'];

}

//////////////////////////////////////////////////////////
//                                                        //
//         Insert Payment  Code                            //                            
//                                                        //
//////////////////////////////////////////////////////////
if ($_POST['trigger1'] == 'Pay')
{
    
    $pq_id = mysql_real_escape_string($_POST['pq_id']);
    $amount = mysql_real_escape_string($_POST['amount']);
    $receipt = mysql_real_escape_string($_POST['receipt']);
    $check_num = mysql_real_escape_string($_POST['check']);
    //$user = mysql_real_escape_string($_POST['user']);
    $date_rec = mysql_real_escape_string($_POST['pay_date']);
    
    
    $insert_pay = "INSERT INTO payment (id, pq_id, amount, receipt, check_num, date_rec, t_stamp) VALUES ('', '$pq_id', '$amount', '$receipt', '$check_num', '$date_rec', NOW())";    
    mysql_query($insert_pay) or die(mysql_error());
    
}

//////////////////////////////////////////////////////////
//                                                        //
//         Show  Payment  Code                            //                            
//                                                        //
//////////////////////////////////////////////////////////

$pi = 1;
$sql1 = "SELECT * FROM payment WHERE pq_id = '$pq_id'";
$result1 = mysql_query($sql1) or die(mysql_error());

while ($pay_row = mysql_fetch_array($result1))
{
    if($pi % 2){$pcolor = '#FFFF99';}else{$pcolor = '';}
    $payments .= "<tr bgcolor='$pcolor'><td>$pay_row[amount]</td><td>$pay_row[check_num]</td><td>$pay_row[receipt]</td><td>$pay_row[date_rec]</td></tr>";
    $pi++;
    $pay_total = $pay_total + $pay_row['amount'];
}



//////////////////////////////////////////////////////////
//                                                        //
//         Uploaded Document Code                            //                            
//                                                        //
//////////////////////////////////////////////////////////
include("upload_class.php"); //classes is the map where the class file is stored (one above the root)

if (!is_dir("files/$pq_id/")){
    mkdir("files/$pq_id/", 0700);
}
$folder = "files/$pq_id/";


//error_reporting(E_ALL);
function select_files($dir) {
    // removed in ver 1.01 the globals 
    $teller = 0;
    if ($handle = opendir($dir)) {
        $mydir = "<p>These are the files in the directory:</p>\n";
        $mydir .= "<form name=\"form1\" method=\"post\" action=\"".$_SERVER['PHP_SELF']."\">\n";
        $mydir .= "  <select name=\"file_in_folder\">\n";
        $mydir .= "    <option value=\"\" selected>...\n";
        while (false !== ($file = readdir($handle))) {
            $files[] = $file;
        }
        closedir($handle); 
        sort($files);
        foreach ($files as $val) {
            if (is_file($dir.$val)) { // show only real files (ver. 1.01)
                $mydir .= "    <option value=\"".$val."\">";
                $mydir .= (strlen($val) > 30) ? substr($val, 0, 30)."...\n" : $val."\n";
                $teller++;    
            }
        }
        $mydir .= "  </select>";
        $mydir .= "<input type=\"submit\" name=\"download\" value=\"Download\">";
        $mydir .= "</form>\n";
    }
    if ($teller == 0) {
        echo "No files!";
    } else { 
        echo $mydir;
    }
}
if (isset($_POST['download'])) {
    $fullPath = $folder.$_POST['file_in_folder'];
    if ($fd = fopen ($fullPath, "rb")) {
        $fsize = filesize($fullPath);
        $path_parts = pathinfo($fullPath); 
        $ext = strtolower($path_parts["extension"]); 
        switch ($ext) {
            case "png":
            case "bmp":
            case "gif":
            header("Content-type: image/".$ext.""); 
            header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");
            break;
            case "pdf":
            header("Content-type: application/pdf");
            header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\""); 
            break;
            case "zip":
            header("Content-type: application/zip"); 
            header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
            break;
            default;
            header("Content-type: application/octet-stream");
            header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
        }
        header("Content-length: $fsize");
        header("Cache-control: private"); 
        header("Content-Transfer-Encoding: binary");
        while(!feof($fd)) {
            $buffer = fread($fd, 2048);
            echo $buffer;
        }
    }
    fclose ($fd);
    exit;
}
function del_file($file) {
    $delete = @unlink($file); 
    clearstatcache();
    if (@file_exists($file)) { 
        $filesys = eregi_replace("/","\\",$file); 
        $delete = @system("del $filesys");
        clearstatcache();
        if (@file_exists($file)) { 
            $delete = @chmod ($file, 0775); 
            $delete = @unlink($file); 
            $delete = @system("del $filesys");
        }
    }
}
function get_oldest_file($directory) {
    if ($handle = opendir($directory)) {
        while (false !== ($file = readdir($handle))) {
            if (is_file($directory.$file)) { // add only files to the array (ver. 1.01)
                $files[] = $file;
            }
        }
        if (count($files) <= 12) {
            return;
        } else {
            foreach ($files as $val) {
                if (is_file($directory.$val)) {
                    $file_date[$val] = filemtime($directory.$val);
                }
            }
        }
    }
    closedir($handle);
    asort($file_date, SORT_NUMERIC);
    reset($file_date);
    $oldest = key($file_date);
    return $oldest;
}



$max_size = 10024*250; // the max. size for uploading
    
$my_upload = new file_upload;

$my_upload->upload_dir = "files/$pq_id/"; // "files" is the folder for the uploaded files (you have to create this folder)
$my_upload->extensions = array(".png", ".zip", ".pdf"); // specify the allowed extensions here
// $my_upload->extensions = "de"; // use this to switch the messages into an other language (translate first!!!)
$my_upload->max_length_filename = 50; // change this value to fit your field length in your database (standard 100)
$my_upload->rename_file = true;
        
if(isset($_POST['docUpload']))
{
    $my_upload->the_temp_file = $_FILES['upload']['tmp_name'];
    $my_upload->the_file = $_FILES['upload']['name'];
    $my_upload->http_error = $_FILES['upload']['error'];
    $my_upload->replace = (isset($_POST['replace'])) ? $_POST['replace'] : "n"; // because only a checked checkboxes is true
    $my_upload->do_filename_check = (isset($_POST['check'])) ? $_POST['check'] : "n"; // use this boolean to check for a valid filename
    $new_name = (isset($_POST['name'])) ? $_POST['name'] : "";
    if ($my_upload->upload($new_name)) { // new name is an additional filename information, use this to rename the uploaded file
        $full_path = $my_upload->upload_dir.$my_upload->file_copy;
        $info = $my_upload->get_uploaded_file_info($full_path);
        // ... or do something like insert the filename to the database
    }
}
 
?>
<script type="text/javascript">
function setStatus()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
            
            document.getElementById('statusUpdate').innerHTML = xmlhttp.responseText;
           
    }
  }

var status = document.getElementById('status').value;
var pq_id = document.getElementById('pq_id').value;
xmlhttp.open("GET","ajax/setStatus.php?status="+status+"&pq_id="+pq_id,true);
xmlhttp.send();
}
</script>
<div id='top'>
<div id="client">
  <table width="400" height="221" border="0">
    <tr>
      <td><a href="prequal_form.php?stack=e1&pq_id=<?php echo $pq_id; ?>">Client Information</a></td>
      <td width="179">&nbsp;</td>
      <td width="88"><a href="dashboard.php?stack=s1">New Search</a></td>
      </tr>
    <tr>
      <td width="119" height="21">Client:</td>
      <td colspan="2"><?php echo $client_name; ?></td>
      </tr>
    <tr>
      <td height="21">SSN</td>
      <td colspan="2"><?php echo $ssn; ?></td>
      </tr>
    <tr>
      <td height="21">Facility:</td>
      <td colspan="2"><?php echo $facility; ?></td>
      </tr>
    <tr>
      <td>Facility Contact:</td>
      <td colspan="2"><?php echo $facility_contact; ?></td>
      </tr>
    <tr>
      <td height="21">Facility Phone:</td>
      <td colspan="2"><?php echo $facility_phone; ?></td>
    </tr>
    <tr>
      <td height="22">Facility Email:</td>
      <td colspan="2"><?php echo $facility_email; ?></td>
    </tr>
    <tr>
      <td height="21">Referred By:</td>
      <td colspan="2"><?php echo $referral; ?></td>
      </tr>
    <tr>
      <td height="24">Status:</td>
      <td colspan="2">
        <select id="status" name="status" onchange="javascript: setStatus()">
          <option value="<?php echo $status; ?>"><?php echo $status; ?></option>
          <option value="none"></option>
          <option value="Pending - Customer">Pending - Customer</option>
          <option value="Pending - Company">Pending - Company</option>
          <option value="Processing">Processing</option>
          <option value="Closed">Closed</option>
          </select><div id="statusUpdate"></div>
        </td>
    </tr>
    </table>
</div>
<div id="contact">
<form id="form4" name="form4" method="post" action="<?php $_SERVER['PHP_SELF'];?>">
  <table width="400" border="0" height="160">
    <tr>
      <td colspan="4">Contact Information</td>
    </tr>
    <tr>
      <td width="117">Initial Contact:</td>
      <td colspan="2"><input type="text" name="initial_contact" id="initial_contact" value="<?php echo $initial_contact;?>"></td>
      <td width="124">&nbsp;</td>
      </tr>
    <tr>
      <td> Packet Sent:</td>
      <td colspan="2"><input type="text" name="info_pack_sent" id="info_pack_sent" value="<?php echo $info_pack_sent;?>"></td>
      <td><div id="sentUpdate"></div></td>
      </tr>
    <tr>
      <td> Packet Received:</td>
      <td colspan="2"><input type="text" name="info_pack_rec" id="info_pack_rec" value="<?php echo $info_pack_rec;?>"></td>
      <td>&nbsp;</td>
      </tr>
    <tr>
      <td>&nbsp;</td>
      <td colspan="2"> <input type="hidden" name="trigger4" id="trigger4" value="Packet" />
        <input type="hidden" name="pq_id" id="pq_id" value="<?php echo $pq_id;?>" /></td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td> <a href='javascript: submitForm4()'>Update</a></td>
      <td colspan="2">&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
     </table>
  </form>
</div>
<div id="document">
<form name="form1" id="form1" enctype="multipart/form-data" method="post" action="<?php $_SERVER['PHP_SELF']; ?>">
<table width="400" border="0">
  <tr>
    <td height="30" colspan="2">Document Information</td>
  </tr>
  <tr>
    <td width="103" height="26" valign="top"><label for="upload">Select a file...</label></td>
    <td width="281" valign="top"><input type="file" name="upload" size="30"></td>
    </tr>
  <tr>
    <td height="24" valign="top">New file name</td>
    <td valign="top"><input type="text" name="name" size="25">
      (no extension) </td>
    </tr>
  <tr>
    <td height="22" valign="top"> <label for="replace">Replace </label></td>
    <td valign="top"><input type="checkbox" name="replace" value="y"></td>
    </tr>
  <tr>
    <td height="22" valign="top"><label for="check">Validate</label></td>
    <td valign="top"><input name="check" type="checkbox" value="y" checked></td>
    </tr>
  <tr>
    <td valign="top"> <a href='javascript: submitForm()'>Upload</a></td>
    <td valign="top"><?php echo $my_upload->show_error_string(); ?>
      <?php if (isset($info)) echo "<blockquote>".nl2br($info)."</blockquote>"; ?></td>
  </tr>
  <tr>
    <td valign="top"><input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_size; ?>" />
      <input type="hidden" name="pq_id" id="pq_id" value="<?php echo $pq_id;?>" />
      <input type="hidden" name="docUpload" value="docUpload" /></td>
    <td valign="top"><p><?php echo select_files($folder); ?></p></td>
  </tr>
  </table>
</form>
</div>
<div id="payment">
<table width="400" height="116" border="0">
<tr>
  <td height="28" colspan="3">Payment Information<br />    <a href='javascript: submitForm2()'>ADD</a></td>
  <td height="28" valign="top"><div id="paytotal" align="right"><?php echo "$".$pay_total;?></div></td>
</tr>
<tr>
  <td height="26" colspan="4"><form id="form2" name="form2" method="post" action="<?php $_SERVER['PHP_SELF'];?>">
  <table width="396" border="0">
    <tr>
      <td width="87"><input type="hidden" name="pq_id" id="pq_id" value="<?php echo $pq_id;?>" />
        <label>
          Amount
          <input name="amount" type="text" id="amount" size="10" />
        </label>
      </td>
      <td width="99"><label>
        Check No
        <input name="check" type="text" id="check" size="10" />
      </label></td>
      <td width="96"><label>
        Receipt
        <input name="receipt" type="text" id="receipt" size="10" />
      </label></td>
      <td width="96" align="right" valign="bottom"><label>
        Date Received
        <input name="pay_date" type="text" id="pay_date" size="10" />
        <input type="hidden" name="trigger1" id="trigger1" value="Pay" />
      </label></td>
    </tr>
  </table></form></td>
  </tr>
<tr>
  <td height="26">&nbsp;</td>
  <td>&nbsp;</td>
  <td>&nbsp;</td>
  <td>&nbsp;</td>
</tr>
<tr>
  <td width="82" height="26">Amount</td>
  <td width="104">Check No.</td>
  <td width="95">Receipt</td>
  <td width="101">Date</td>
</tr>
  <?php echo $payments;?>
</table>
</div>
<div id="showNotes">
<p> Contact Notes:</p>
<form id="form3" name="form3" method="post" action="<?php $_SERVER['PHP_SELF'];?>">
<table width='400'>
<tr>
      <td height="56" colspan="3"><a href='javascript: submitForm3()'>Click to Add Note:</a>
        <input type="hidden" name="trigger3" id="trigger3" value="Note" />
        <input type="hidden" name="pq_id" id="pq_id" value="<?php echo $pq_id;?>" />
        <br />
        <br />
        <label>
        <textarea name="note" id="note" cols="45" rows="5"></textarea>
          </label><br /><br />
        </td>
      </tr>
<?php echo $c_note;?>
</table>
</form>
</div>
<div id="assets">
<p>Asset Information:</p>
<form id="form5" name="form5" method="post" action="<?php $_SERVER['PHP_SELF'];?>">
<table width='400'>
<tr>
      <td colspan="4">
        </td>
      </tr>
<?php echo "<tr height='50'><td colspan='4'><a href='dashboard.php?stack=8&pi=$pq_id'>Edit Income</a></td></tr>";?>      
<?php echo $income; ?>
<?php echo "<tr height='50'><td colspan='4'><a href='dashboard.php?stack=9&pi=$pq_id'>Edit Expense</a></td></tr>";?>  
<?php echo $expense;?>
<?php echo "<tr height='50'><td colspan='4'></td></tr>";?>  
<?php echo "<tr height='25'><td colspan='2'>Total Net Income</td><td>$$total_net</td><td></td></tr>"; ?>
</table>
</form>
</div>
</div>
<div id='bottom'>


</div>
 
without ploughing through everything this line looks incorrect

Code:
$fullPath = $folder.$_POST['file_in_folder'];

you are prepending the folder whereas in the option values within the posted select control you are including the whole path.

personally this approach seems flawed. you are exposing the full path to the user and, unless you are controlling access via .htaccess, you are therefore exposing the download. it is better to store the protected files outside of the docroot and just expose uniqueIDs that the download script can use.
 
i should add that the line quoted above is actually a huge security hole. with the correct insertion of ../../ etc the user can get to the whole file system.
 
OK, so are you saying I should upload the files to my file system. Store the name and id in my database, then display the names of the files to the user and use the id to search the file system and download the file?

Is this how I would go about setting up my downloads the way your talking about?
 
Ok, I have written a script that stores the file in a directory that I will secure with .htaccess. The users only see the ID, and the file name and path are stored in the database..
However, I'm still getting the same .pdf corrupted error.

If I just just browse out to the directory on the server and double click the .pdf it opens up just fine. If I try and use my script to open it, it's corrupt.
I'm not sure what I'm doing wrong.

Please check this out and let me know what you think.

Code:
<?
ob_start();
$pq_id = 69;

$db_user = "";
$db_pass = "";
$db_host = "localhost";
$db_name = "";


$conn = mysql_connect($db_host, $db_user, $db_pass);


//List files
$query = "SELECT * FROM file WHERE pq_id = '$pq_id'";
if($result = mysql_db_query($db_name, $query, $conn)) 
	{
		while($row = mysql_fetch_array($result)) 
		{			
			echo "<a href=\"fileopen.php?id=".$row["id"]."\">".$row["name"]."</a>\n";			
		}
	}

//open files
$query = "SELECT pq_id, name, path FROM file WHERE id = $id";
if($result = mysql_db_query($db_name, $query, $conn)) 
	{
	
	
	if($row = mysql_fetch_array($result)) 
		{
			$file_name = $row["name"];
			$file_path = $row["path"]."/".$row['pq_id']."/";
		
			header("Content-Type: application/pdf");
			header("Content-Disposition: attachment; filename=$file_name");
			header("Content-length: filesize($file_name)");
							
				if($fp = fopen($file_path.$file_name, "r")) 
					{
					while(!feof($fp)) 
						{
							echo  fgets($fp, 4096);
						}
							fclose($fp);
					}		
		}			
	}	
// close db connection
mysql_close($conn);	
	
?>
 
did you try my code?

this line
Code:
header("Content-length: filesize($file_name)");
appears incorrect as you are not referencing the path

in the alternative please post the whole of your code
 
I did try your code, it gave me an error on this line (if (isset($_POST['submit']) && $_POST['submit'] == 'Upload'):) that I couldn't figure out. I didn't spend to much time because based on some other reading, I had decided to not store docs in the database.

Here is the error:
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in C:\AppServ\ on line 74

However it is fixed now and it was the line of code you pointed out.

I really appreciate your help. I would have never figured this out.
 
I think you cut and pasted my code incorrectly. there was no trailing bracket after the if statement.

anyway, am glad things are working for you.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top