Thursday, April 17, 2008

PHP/Oracle : Upload file to database

Today I try something related to PHP programmng to save/retrieve file from Oracle database.

Below is HTML code to create a form which allows user to specify file to be uploaded:


Below is PHP code fragment which upload PDF file to Oracle 10g database (using BLOB):

// create a new record (save content of file to column with BLOB type)
$cmd = "INSERT INTO MEETING_MINUTES (ID, MEETING_ID, REC_DATE, MINUTE_DESC, MINUTE_URL, DEL_STATE, MINUTE_CONTENT) VALUES ($new_recid, $ID, '$recday', '$desc', '$url_path', 'N', EMPTY_BLOB()) RETURNING MINUTE_CONTENT INTO :MINUTE_CONTENT";
$stmt = oci_parse($conn, $cmd);
$blob = oci_new_descriptor($conn, OCI_D_LOB);
oci_bind_by_name($stmt, ":MINUTE_CONTENT", $blob, -1, OCI_B_BLOB);
oci_execute($stmt, OCI_DEFAULT);
$blob->savefile($_FILES["file"]["tmp_name"]);
oci_commit($conn);

Below is PHP code fragment to retrieve file from Oracle Database (need to be a standalone PHP file)
$cmd = "SELECT * FROM MEETING_MINUTES where ID='$ID'";
$stmt = oci_parse($conn, $cmd);
oci_execute($stmt, OCI_DEFAULT);
while ($content = oci_fetch_assoc($stmt))
{ $result = $content['MINUTE_CONTENT']->load();
$file_url = oci_result($stmt, "MINUTE_URL");
$file_name = substr($file_url,strrpos($file_url,'/')+1);
$file_type = substr($file_url,strrpos($file_url,'.')+1);
header("Pragma: no-cache");

if (strcasecmp($file_type,"doc") == 0)
{ header('Content-type: application/doc'); }
else if (strcasecmp($file_type,"pdf") == 0) { header('Content-type: application/pdf'); }

$cmd = sprintf("Content-Disposition: attachment; filename=%s",$file_name);
header($cmd);
echo $result;
}

Below is PHP code to move content of a file from temporary storage to physical folder

// check content of file uploaded
if (($_FILES["file"]["type"] == "text/plain") ($_FILES["file"]["type"] == "application/msword")
($_FILES["file"]["type"] == "application/pdf"))
{ if ($_FILES["file"]["error"] > 0)
{ echo "Fail to upload file, error: " . $_FILES["file"]["error"] . "
";
}
else
{ $url_path = "repository/meeting/" . $ID . "/" . $_FILES["file"]["name"];

// move file from temporary directory
move_uploaded_file($_FILES["file"]["tmp_name"], $url_path);
}
}



Below is a library which allows to use PHP to save content to PDF file.
http://fpdf.org/