Read .eml file using php - php

I have the php script as shown below. I want to ask that using this script how can i read normal .eml file as we read in gmail or yahoo? how can i get attachments from it ?
<?php
/**
*
* This code has been written by Alexis Ulrich (http://alx2002.free.fr)
* This code is in the public domain.
*
*/
define(EML_FILE_PATH,'');
define(PICTURE_DIRECTORY_PATH,'img/');
// gets parameters
$images = substr($_GET['images'],0,5);
$filename = substr($_GET['filename'],0,50);
if ($filename == '') $filename = 'toto.eml';
$eml_file = EML_FILE_PATH.$filename;
// opens file
if (!($content = fread(fopen(EML_FILE_PATH.$filename, 'r'), filesize(EML_FILE_PATH.$filename))))
die('File not found ('.EML_FILE_PATH.$filename.')');
// two kinds of separators
if (strpos($content,'------_') !== false) $separator = '------_';
else $separator = '------=_';
$aContent = explode($separator,$content);
$aImages = array();
foreach($aContent as $thisContent) {
if (strpos($thisContent,'Content-Type: text/html') !== false) {
// email HTML body
$thisContent = substr($thisContent,strpos($thisContent,'<!DOCTYPE'));
$thisHTMLContent = quoted_printable_decode($thisContent);
//echo "<hr>$thisHTMLContent<hr>\n\n";
}
if (strpos($thisContent,'Content-Type: image/gif;') !== false) {
// base64 gif picture
$begin = strpos($thisContent,'Content-ID: <') + 13;
$long = strpos(substr($thisContent,strpos($thisContent,'Content-ID: <') + 13),'>');
$img_id = substr($thisContent,$begin,$long);
$img_name = substr($thisContent,strpos($thisContent,'name="')+6,strpos($thisContent,'.gif"')-strpos($thisContent,'name="')-6);
if (strpos($thisContent,'Content-Location: ') !== false) {
$img_location = substr($thisContent,strpos($thisContent,'Content-Location: ')+18);
$img_location = substr($img_location,0,strpos($img_location,'.gif'));
$searched = 'Content-Location: ' . $img_location . '.gif';
$img_base64 = substr($thisContent,strpos($thisContent,$searched)+strlen($searched));
}
else {
$img_location = $img_name;
$searched = 'Content-ID: <' . $img_id . '>';
$Content_ID_pos = strpos($thisContent,'Content-ID: <');
$end_content = substr($thisContent,$Content_ID_pos);
$end_Content_ID_pos = strpos($end_content,'>');
$img_base64 = substr($end_content,$end_Content_ID_pos + 1);
}
$aThisImage = array('id'=>$img_id, 'name'=>$img_name, 'location'=>$img_location, 'type'=>'gif', 'base64'=>$img_base64);
//print_r($aThisImage);
$aImages[] = $aThisImage;
}
if (strpos($thisContent,'Content-Type: image/jpeg;') !== false) {
// base64 jpg picture
$begin = strpos($thisContent,'Content-ID: <') + 13;
$long = strpos(substr($thisContent,strpos($thisContent,'Content-ID: <') + 13),'>');
$img_id = substr($thisContent,$begin,$long);
$img_name = substr($thisContent,strpos($thisContent,'name="')+6,strpos($thisContent,'.jpg"')-strpos($thisContent,'name="')-6);
if (strpos($thisContent,'Content-Location: ') !== false) {
$img_location = substr($thisContent,strpos($thisContent,'Content-Location: ')+18);
$img_location = substr($img_location,0,strpos($img_location,'.jpg'));
$searched = 'Content-Location: ' . $img_location . '.jpg';
$img_base64 = substr($thisContent,strpos($thisContent,$searched)+strlen($searched));
}
else {
$img_location = $img_name;
$searched = 'Content-ID: <' . $img_id . '>';
$Content_ID_pos = strpos($thisContent,'Content-ID: <');
$end_content = substr($thisContent,$Content_ID_pos);
$end_Content_ID_pos = strpos($end_content,'>');
$img_base64 = substr($end_content,$end_Content_ID_pos + 1);
}
$aThisImage = array('id'=>$img_id, 'name'=>$img_name, 'location'=>$img_location, 'type'=>'jpg', 'base64'=>$img_base64);
$aImages[] = $aThisImage;
}
}
//print_r($aImages);
foreach($aImages as $image) {
if ($images == 'filed') {
// image file creation
if (!file_exists(PICTURE_DIRECTORY_PATH."$image[location].$image[type]")) {
if (!$handle = fopen (PICTURE_DIRECTORY_PATH."$image[location].$image[type]", "wb"))
die("Cannot open file (".PICTURE_DIRECTORY_PATH."$image[location].$image[type])");
if (!fwrite($handle, base64_decode($image[base64])))
die("Cannot write into file (".PICTURE_DIRECTORY_PATH."$image[location].$image[type])");
fclose($handle);
}
$thisHTMLContent = str_replace('cid:'.$image['id'],PICTURE_DIRECTORY_PATH."$image[location].$image[type]",$thisHTMLContent);
}
else {
// images to be created on the fly
$imageLocation = urlencode($image[location]);
$file = urlencode($eml_file);
$thisHTMLContent = str_replace('cid:'.$image['id'],"viewImage.php?imageLocation=$imageLocation&file=$file",$thisHTMLContent);
}
$thisHTMLContent = preg_replace("/<IMG HEIGHT=(\d*)/i","<img ",$thisHTMLContent);
// no base href referring to local file
$thisHTMLContent = preg_replace("/href=\"file(.*)\"/i","",$thisHTMLContent);
}
echo $thisHTMLContent;
?>
Thanks in advance and would hope to receive reply soon.

Related

An uncaught Exception was encountered Type: ImagickException Message: Failed to read the file in Codeigniter

The following php pdf to image code with imagick in codeigniter framework has a problem in the controller, imagick cannot read my file pdf.
error:
[codeigniter] An uncaught Exception was encountered Type: ImagickException Message: Failed to read the file in Codeigniter.
controller:
<?php defined('BASEPATH') OR exit('No direct script access allowed');
class Files_upload extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('files');
}
function index(){
$data['gallery'] = $this->db->query("select * from gallery order by id desc limit 10")->result();
$data = array();
if($this->input->post('submitForm') && !empty($_FILES['upload_Files']['name'])){
$filesCount = count($_FILES['upload_Files']['name']);
for($i = 0; $i < $filesCount; $i++){
$_FILES['upload_File']['name'] = $_FILES['upload_Files']['name'][$i];
$_FILES['upload_File']['type'] = $_FILES['upload_Files']['type'][$i];
$_FILES['upload_File']['tmp_name'] = $_FILES['upload_Files']['tmp_name'][$i];
$_FILES['upload_File']['error'] = $_FILES['upload_Files']['error'][$i];
$_FILES['upload_File']['size'] = $_FILES['upload_Files']['size'][$i];
$uploadPath = 'uploads/files/';
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|png|pdf|mp4|avi';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if($this->upload->do_upload('upload_File')){
$fileData = $this->upload->data();
$uploadData[$i]['file_name'] = $fileData['file_name'];
$uploadData[$i]['created'] = date("Y-m-d H:i:s");
$uploadData[$i]['modified'] = date("Y-m-d H:i:s");
}
}
if(!empty($uploadData)){
//Insert file information into the database
$insert = $this->files->insert($uploadData);
$statusMsg = $insert?'Files uploaded successfully.':'Some problem occurred, please try again.';
$this->session->set_flashdata('statusMsg',$statusMsg);
}
$this->load->helper('url');
$ImageName = $_FILES['upload_File']['name'];
$loc = base_url().$uploadPath.$ImageName;
echo $ImageName;
echo $loc;
$im = new imagick($loc);
$noOfPagesInPDF = $im->getNumberImages();
if ($noOfPagesInPDF) {
for ($i = 0; $i < 1; $i++) {
$url = $loc.'['.$i.']';
$image = new Imagick($url);
$image->setImageFormat("jpg");
$image->setImageCompressionQuality(80);
$image->writeImage("uploads/files/img/".($i+1).'-'.$ImageName.'.jpg');
}
}
for($i = 0; $i<1;$i++) {
$img = "uploads/files/img/".($i+1).'-'.$ImageName.'.jpg';
$display .= "<img src='$img' title='Page-$i' /><br>";
}
$message = "PDF converted to JPEG sucessfully!!";
}
//Get files data from database
$data['gallery'] = $this->files->getRows();
//Pass the files data to view
$this->load->view('files_upload/index', $data);
}
}
Solved
Is Correct Code
$ImageName= $fileData['file_name'];
$loc = realpath(APPPATH.'../uploads/files/').'/'.$ImageName;
Or you can just do
$loc = $fileData['full_path'];
This will work (tested):
//$data['gallery'] = $this->db->query("select * from gallery order by id desc limit 10")->result(); // same at bottom??
$message = '';
$display = '';
if ($this->input->post('submitForm') && !empty($_FILES['userfile']['name'])) {
$uploadPath = FCPATH . 'uploads/files/';
if (!is_dir($uploadPath) && mkdir($uploadPath, DIR_WRITE_MODE, true) == false) {
show_error('Folder cannot be made!');
}
$config['upload_path'] = $uploadPath;
$config['allowed_types'] = 'gif|jpg|png|pdf|mp4|avi';
$this->load->library('upload', $config);
// change input field to <input type="file" name="userfile">
if (!$this->upload->do_upload()) {
$this->session->set_flashdata('statusMsg', $this->upload->display_errors());
} else {
$fileData = $this->upload->data();
$uploadData['file_name'] = $fileData['file_name'];
$uploadData['created'] = date("Y-m-d H:i:s");
$uploadData['modified'] = date("Y-m-d H:i:s");
$insert = $this->files->insert($uploadData);
$insert = true;
if (!$insert) {
#unlink($fileData['full_path']); // remove orphan
$this->session->set_flashdata('statusMsg', 'Database error. Please try again');
} else {
$this->session->set_flashdata('statusMsg', 'Files uploaded successfully.');
if ($fileData['file_ext'] == '.pdf') {
try {
$newPath = $uploadPath . 'img/';
if (!is_dir($newPath) && mkdir($newPath, DIR_WRITE_MODE, true) == false) {
throw new Exception('Folder cannot be made!');
}
$ImageName = $fileData['raw_name'];
$loc = $fileData['full_path'];
$im = new Imagick($loc);
$pdfPageCount = $im->getNumberImages();
if ($pdfPageCount > 0) {
for ($i = 0; $i < $pdfPageCount; $i++) {
$url = $loc . '[' . $i . ']';
$image = new Imagick($url);
$image->setImageFormat("jpg");
$image->setImageCompressionQuality(80);
$image->writeImage($newPath . ($i + 1) . '-' . $ImageName . '.jpg');
$img = base_url("uploads/files/img/" . ($i + 1) . '-' . $ImageName . '.jpg');
$display .= "<img src='$img' title='Page-$i' /><br>";
}
echo $display; // debugging
$this->session->set_flashdata('statusMsg', "PDF converted to JPEG(s) sucessfully!");
}
} catch (Exception $e) {
#unlink($fileData['full_path']); // remove orphan
$this->session->set_flashdata('statusMsg', $e->getMessage());
}
} else {
echo 'not a pdf'; // debugging only
}
}
}
}
//Get files data from database
$data['gallery'] = $this->files->getRows();
//Pass the files data to view
$this->load->view('files_upload/index', $data);
Please note the input file field should now look like this:
<input type="file" name="userfile" />
You will also have to revise:
$this->files->insert($uploadData) function

PHP - Loop through folders, open each docx file and replace string

I have a script that:
goes through each folder and subfolder of my "./sample/" directory
opens each .docx file
replaces a string such as "##PROPERTY##" with my $_POST['property'] variable
zips the folder content
launches a download
Now, running portions of the code individually, it does what is needed. However, when putting it all together, it dies while scanning the subfolders for docx files.
My folder structure is like this:
./sample/
/IT/it1.docx
/F&B/fb1.docx
/FO/fo1.docx
sample1.docx
The problem seems to occur during the is_dir($dir) part for the level 1 folders.
Any ideas what could cause this?
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// form variables
$holidex = strtoupper($_POST['holidex']);
$property = $_POST['property'];
$brand = $_POST['brand'];
$division = $_POST['division'];
$language = $_POST['language'];
$date_issued = $_POST['date_issued'];
$approved_by = $_POST['approved_by'];
// script variables
//$dir = './Sample_SOP_-_'.$brand.'_('.$language.')'; //dir to scan like ./sample/
$dir = './sample/'; //dir to scan like ./sample/
$archive = date("Y-m-d H-i-s"); //UNIQUE name of zip file to create and download
$zipfile = "./".$holidex." - ".$archive.".zip"; //path to zip file download
$temp = "./temp/"; //directory to temp folder
// string replacements
$find = "##PROPERTY##"; // find and replace property information
$replace = $_POST['property'];
$find2 = "##BRAND##"; // find and replace brand information
$replace2 = $_POST['brand'];
$find3 = "##DATE##"; // find and replace effective date
$replace3 = $_POST['date_issued'];
$find4 = "##APPROVED_BY##"; // find and replace approved by
$replace4 = $_POST['approved_by'];
//read dir
$files = scandir($dir, 1);
//create new archive name
$zip_download = new ZipArchive();
$zip_download->open("$zipfile", ZipArchive::CREATE);
foreach($files as $file) {
//docx
$ext1 = ".docx";
$checkextension = explode($ext1, $file);
if (count($checkextension) > 1) {
$zip = new ZipArchive;
$zip->open("$file");
$word = $zip->getFromName('word/document.xml');
$word2 = str_replace($find, $replace, $word);
$word2 = str_replace($find2, $replace2, $word);
$word2 = str_replace($find3, $replace3, $word);
$word2 = str_replace($find4, $replace4, $word);
$zip->addFromString("word/document.xml", $word2);
$zip->close();
} else {
die("Error - There are no files the directory..");
}
//folders level 1
if (is_dir($file)) {
$sub = $file . '/';
$subfiles = scandir($sub, 1);
if ($subfiles > 1) {
if ($sub == "../" || $sub == "./") {
}
else {
foreach($subfiles as $subfile) {
//docx
$ext1 = ".docx";
$checkextensionsub = explode($ext1, $subfile);
$subsubfile = $sub . $subfile;
if (count($checkextensionsub) > 1) {
$zipsub = new ZipArchive;
$zipsub->open("$subsubfile");
$wordsub = $zipsub->getFromName('word/document.xml');
$word2sub = str_replace($find, $replace, $wordsub);
$word2sub = str_replace($find2, $replace2, $wordsub);
$word2sub = str_replace($find3, $replace3, $wordsub);
$word2sub = str_replace($find4, $replace4, $wordsub);
$zipsub->addFromString("word/document.xml", $word2sub);
$zipsub->close();
}
//folders level 2
$sub2 = $sub . $subfile;
if (is_dir($sub2)) {
$subfiles2 = scandir($sub2, 1);
if ($subfiles2 > 1) {
if ($sub2 == $sub.".." || $sub2 == $sub.".") {
}
else {
foreach($subfiles2 as $subfile2) {
//docx
$ext1 = ".docx";
$checkextensionsub2 = explode($ext1, $subfile2);
$subsubfile2 = $sub2 . '/' . $subfile2;
if (count($checkextensionsub2) > 1) {
$zipsub2 = new ZipArchive;
$zipsub2->open("$subsubfile2");
$wordsub2 = $zipsub2->getFromName('word/document.xml');
$word2sub2 = str_replace($find, $replace, $wordsub2);
$word2sub2 = str_replace($find2, $replace2, $wordsub2);
$word2sub2 = str_replace($find3, $replace3, $wordsub2);
$word2sub2 = str_replace($find4, $replace4, $wordsub2);
$zipsub2->addFromString("word/document.xml", $word2sub2);
$zipsub2->close();
}
//more directories when needed
//****replicate code here****
//add files to archive
$zip_download->addFile($subsubfile2, $subsubfile2);
}
}
}
}
//add files to archive
$zip_download->addFile($subsubfile, $subsubfile);
}
}
}
} else {
die ("Error - No files in the directory");
}
}
//add files to archive
$zip_download->addFile($file, $file);
}
$zip_download->close();
//download zip
if (file_exists($zipfile) && is_readable($zipfile)) {
header('Content-Type: application/octet-stream');
header('Content-Length: '.filesize($zipfile));
header('Content-Disposition: attachment; filename="'.basename($zipfile).'";');
header('Content-Transfer-Encoding: binary');
$file_download = # fopen($zipfile, 'rb');
if ($file_download) {
fpassthru($file_download);
exit;
}
echo ("ZIP generated successfully, download is starting...");
} else {
echo ("Error creating the ZIP archive!");
}
}
?>
I think it's because Scandir() will produce something like
`Array
(
...
[9] => .
[10] => ..`
at the end of the arrayand when you check those if they are folders maybe an error occurs and dies.

Downloading website screenshot not downloading right size

Hello this is a 2 part question....
I have been trying to solve my problem for a while and gave up tonight and seeking answers :/
i have the following code and trying to download the image to the width of 1207px,
the download of the script works fine so i haven't included it below.
the second part is i like to screenshot to the ratio of 1207px wide but cant find way round it.
i have edited the following lines..
$w = 500;
$h = 768;
but this don't work, what ever the values are it downloads at 500px or very close width which is not ideal.
$url = trim(urldecode($url));
if ($url == '') {
exit();
}
if (!stristr($url, 'http://') and !stristr($url, 'https://')) {
$url = 'http://' . $url;
}
$url_segs = parse_url($url);
if (!isset($url_segs['host'])) {
exit();
}
$here = dirname(__FILE__) . DIRECTORY_SEPARATOR;
$bin_files = $here . 'bin' . DIRECTORY_SEPARATOR;
$jobs = $here . 'jobs' . DIRECTORY_SEPARATOR;
$cache = $here . 'cache' . DIRECTORY_SEPARATOR;
if (!is_dir($jobs)) {
mkdir($jobs);
file_put_contents($jobs . 'index.php', '<?php exit(); ?>');
}
if (!is_dir($cache)) {
mkdir($cache);
file_put_contents($cache . 'index.php', '<?php exit(); ?>');
}
$w = 500;
$h = 768;
if (isset($_REQUEST['w'])) {
$w = intval($_REQUEST['w']);
}
if (isset($_REQUEST['h'])) {
$h = intval($_REQUEST['h']);
}
if (isset($_REQUEST['clipw'])) {
$clipw = intval($_REQUEST['clipw']);
}
if (isset($_REQUEST['cliph'])) {
$cliph = intval($_REQUEST['cliph']);
}
if (isset($_REQUEST['download'])) {
$download = $_REQUEST['download'];
}
$url = strip_tags($url);
$url = str_replace(';', '', $url);
$url = str_replace('"', '', $url);
$url = str_replace('\'', '/', $url);
$url = str_replace('<?', '', $url);
$url = str_replace('<?', '', $url);
$url = str_replace('\077', ' ', $url);
$screen_file = $url_segs['host'] . crc32($url) . '_' . $w . '_' . $h . '.jpg';
$cache_job = $cache . $screen_file;
$refresh = false;
if (is_file($cache_job)) {
$filemtime = #filemtime($cache_job); // returns FALSE if file does not exist
if (!$filemtime or (time() - $filemtime >= $cache_life)) {
$refresh = true;
}
}
$url = escapeshellcmd($url);
if (!is_file($cache_job) or $refresh == true) {
$src = "
var page = require('webpage').create();
page.viewportSize = { width: {$w}, height: {$h} };
";
if (isset($clipw) && isset($cliph)) {
$src .= "page.clipRect = { top: 0, left: 0, width: {$clipw}, height: {$cliph} };";
}
$src .= "
page.open('{$url}', function () {
page.render('{$screen_file}');
phantom.exit();
});
";
$job_file = $jobs . $url_segs['host'] . crc32($src) . '.js';
file_put_contents($job_file, $src);
$exec = $bin_files . 'phantomjs ' . $job_file;
$escaped_command = escapeshellcmd($exec);
exec($escaped_command);
if (is_file($here . $screen_file)) {
rename($here . $screen_file, $cache_job);
}
}
if (is_file($cache_job)) {
if ($download != false) {
$file = $cache_job;
$file_name=basename($file);
$type = 'image/jpeg';
header("Content-disposition: attachment; filename={$file_name}");
header("Content-type: {$type}");
readfile($file);
;
} else {
$file = $cache_job;
$type = 'image/jpeg';
header('Content-Type:' . $type);
header('Content-Length: ' . filesize($file));
readfile($file);
}
}
?>

Download file is getting corrupted

I have a code function in php
What it does:
it absorbs data from a table and converts the images(saved as blob) into files and put under a subfolder named "image" under a folder created dynamically based on version and date
ex: v3-20-12-2012
Then it creates a csv file and save it in the v3-20-12-2012 folder.
Then it creates a zip file for the folder v3-20-12-2012.
The problem is , the zip file getting saved in the project folder. I want it to be downloadable.
How can i achieve this.
Here's my code:
function create_csv($version,$ctg,$cnt,$nt,$api)
{
$folder = $version."-".date('d-m-Y')."-".time();
if(!file_exists('./'.$folder))
{
mkdir('./'.$folder);
mkdir('./'.$folder.'/image/');
}
$cnt_table = "aw_countries_".$version;
$ctg_table = "aw_categories_".$version;
$off_table = "aw_offers_".$version;
$sizeof_ctg = count($ctg);
$cond_ctg = " ( ";
for($c = 0; $c < $sizeof_ctg ; $c++)
{
$cond_ctg = $cond_ctg." $ctg_table.category = '".$ctg[$c]."' ";
if($c < intval($sizeof_ctg-1))
$cond_ctg = $cond_ctg." OR ";
else if($c == intval($sizeof_ctg-1))
$cond_ctg = $cond_ctg." ) ";
}
$sizeof_cnt = count($cnt);
$cond_cnt = " ( ";
for($cn = 0; $cn < $sizeof_cnt ; $cn++)
{
$cond_cnt = $cond_cnt." $cnt_table.country = '".$cnt[$cn]."' ";
if($cn < intval($sizeof_cnt-1))
$cond_cnt = $cond_cnt." OR ";
else if($cn == intval($sizeof_cnt-1))
$cond_cnt = $cond_cnt." ) ";
}
$sizeof_nt = count($nt);
$cond_nt = " ( ";
for($n = 0; $n < $sizeof_nt ; $n++)
{
$cond_nt = $cond_nt." $off_table.network_id = '".$nt[$n]."' ";
if($n < intval($sizeof_nt-1))
$cond_nt = $cond_nt." OR ";
else if($n == intval($sizeof_nt-1))
$cond_nt = $cond_nt." ) ";
}
$sizeof_api = count($api);
$cond_api = " ( ";
for($a = 0; $a < $sizeof_api ; $a++)
{
$cond_api = $cond_api." $off_table.api_key = '".$api[$a]."' ";
if($a < intval($sizeof_api-1))
$cond_api = $cond_api." OR ";
else if($a == intval($sizeof_api-1))
$cond_api = $cond_api." ) ";
}
$output = "";
$sql = "SELECT DISTINCT $off_table.id,$off_table.name
FROM $off_table,$cnt_table,$ctg_table
WHERE $off_table.id = $cnt_table.id
AND $off_table.id = $ctg_table.id
AND ".$cond_api."
AND ".$cond_nt."
AND ".$cond_cnt."
AND ".$cond_ctg;
$result = mysql_query($sql);
$columns_total = mysql_num_fields($result);
for ($i = 0; $i < $columns_total; $i++)
{
$heading = mysql_field_name($result, $i);
$output .= '"'.$heading.'",';
}
$output .= '"icon"';
$output .="\n";
while ($row = mysql_fetch_array($result))
{
for ($i = 0; $i < $columns_total; $i++)
{
$output .='"'.$row["$i"].'",';
}
$sql_icon = "SELECT $off_table.icon FROM $off_table WHERE id = '".$row['id']."'";
$result_icon = mysql_query($sql_icon);
while($row_icon = mysql_fetch_array($result_icon))
{
$image = $row_icon["icon"];
$id = $row["id"];
$icon = "./$folder/image/{$id}.jpg";
$icon_link = "$folder/image/{$id}.jpg";
file_put_contents($icon, $image);
}
$output .= '"'.$icon_link.'"';
$output .="\n";
}
$filename = "myFile.csv";
$fd = fopen ( "./$folder/$filename", "w");
fputs($fd, $output);
fclose($fd);
$source = $folder;
$destination = $folder.'.zip';
$flag = '';
if (!extension_loaded('zip') || !file_exists($source)) {
return false;
}
$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
return false;
}
$source = str_replace('\\', '/', realpath($source));
if($flag)
{
$flag = basename($source) . '/';
}
if (is_dir($source) === true)
{
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($files as $file)
{
$file = str_replace('\\', '/', realpath($file));
if (is_dir($file) === true)
{
}
else if (is_file($file) === true)
{
$zip->addFromString(str_replace($source . '/', '', $flag.$file), file_get_contents($file));
}
}
}
else if (is_file($source) === true)
{
$zip->addFromString($flag.basename($source), file_get_contents($source));
}
$zip->close();
if (is_dir($folder))
{
$objects = scandir($folder);
foreach ($objects as $object)
{
if ($object != "." && $object != "..")
{
if (filetype($folder."/".$object) == "dir")
{
$object_inner = scandir($folder."/".$object);
foreach ($object_inner as $object_inner)
{
if ($object_inner != "." && $object_inner != "..")
{
unlink($folder."/".$object."/".$object_inner);
}
}
rmdir($folder."/".$object);
}
else
unlink($folder."/".$object);
}
}
reset($objects);
}
rmdir("./".$folder);
/*$zipfile = $folder.'.zip';
$file_name = basename($zipfile);
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=$file_name");
header("Content-Length: " . filesize($zipfile));
readfile($zipfile);
exit;*/
}
EDIT:
I have two instance of the file. One file gettng saved automaticaly at the project folder. The next one is getting forced to download. The one that is automatically saved has no prolem whle unzipping. But the one that is forcefully download, that having issue while unzipping.
You forgot to send the actual data at the end and it would be nice to also send the Content-Length header.
Example:
$filename = 'something.zip';
$filepath = './path/to/files/directory/';
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename='.$filename);
header("Content-Length: ".filesize($filepath.$filename));
ob_end_flush();
readfile($filepath.$filename);
And as a side note, you may want to split that function because it does more than it should. As name states, it should just create_csv, but is also working with DB, creating a zip, sending the response, etc.
Update:
After your update I looked closely to your code and you have a few issues which might result in a corrupted download:
$source = str_replace('\\', '\\', realpath($source));
// more code ...
$file = realpath($file);
Those lines will result in full paths being used in archive, which you might not want. I recommend commenting those two lines so you store relative paths inside the archive.
After you add all your files to your archive, you don't close it and because the archive will have a temporary name which is different than its final one, your code used when sending headers will result in sending garbage data.
To fix that, you should close the .zip before sending the headers:
// more code ...
$zip->close();
header('Content-type: application/zip');

PHP Uploader wont rename uploads

I have a PHP uploader on my Dedi server, the uploader works as it should, only after it uploads the files it dose not rename them from their temp names..
it comes out something like
2b4134a1f559b6da866c9febbc92d709.mp3
The uploader file.php
<?php
class file {
public $id;
public $fileName;
public $systemFilename;
public $fileType;
public $fileExtension;
public $systemUrl;
public $originalUrl;
public $thumbPath;
public $thumbUrl;
public $canHaveThumb;
public $ts;
public $size;
public $authorized;
public $knownExtensions;
public $mimeType;
public $filePath;
public function __construct() {
$this->setKnownExtensions();
}
// Check and save a new file on the disk and the database
public function uploadNewFile($files) {
$result = array(); // The variable we will send back when we have finished to check and save the file
$this->setFileName($files['Filedata']['name']);
if ($this->authorized) {
// Build the target path
$siteUrl = F3::get('siteUrl'); // Set in config.php
$uploadFolder = F3::get('uploadFolder'); // Set in config.php
$uploadUrl = $_SERVER['DOCUMENT_ROOT'] . '/' . $uploadFolder . '/';
// Get the temporary file
$tempFile = $_FILES['Filedata']['tmp_name'];
// Get a unique system name
$rand = rand(1, 414342);
$ts = time();
$systemName = md5($rand . $ts);
$this->systemFilename = $systemName . '.' . $this->fileExtension;
$this->ts = $ts;
// Clean the path
$targetFile = str_replace('//', '/', $uploadUrl) . $this->systemFilename;
// Save the file on the disk
move_uploaded_file($tempFile, $targetFile);
// Save the file in the database
DB::sql('INSERT INTO hm_files (fileName, systemFilename, fileType, time) VALUES ("' . $this->fileName . '", "' . $this->systemFilename . '", "' . $this->fileType . '", ' . $this->ts . ')');
$this->id = F3::get('DB->pdo')->lastInsertId();
// Retrieve the template for the file list
$result['tableRow'] = $this->getTableRow();
// We create a thumbnail if it is a simple image
$this->createThumb();
}
$result['file'] = $this;
return $result;
}
public function canHaveThumb() {
if ($this->fileType == 'image') {
$this->canHaveThumb = true;
} else {
$this->canHaveThumb = false;
}
return $this->canHaveThumb;
}
public function createThumb() {
if ($this->canHaveThumb()) {
$filePath = $this->getFilePath();
if (file_exists($filePath)) {
$thumbPath = site::getThumbsPath();
$thumb = new image($filePath);
$thumb->dir($thumbPath);
$thumb->width(250);
$thumb->save();
}
}
}
public function getThumbPath() {
$thumbFolderPath = site::getThumbsPath();
$this->thumbPath = $thumbFolderPath . $this->systemFilename;
if (!file_exists($this->thumbPath)) {
$this->createThumb();
}
return $this->thumbPath;
}
public function getThumbUrl() {
$base = F3::get('BASE');
$thumbsFolder = F3::get('thumbsFolder');
$this->thumbUrl = $base . '/' . $thumbsFolder . '/' . $this->systemFilename;
return $this->thumbUrl;
}
// Delete a file
public function delete() {
$filePath = $this->getFilePath();
if (file_exists($filePath)) {
unlink($filePath); // Remove the file from the hard drive
}
if ($this->canHaveThumb()) {
$thumbPath = $this->getThumbPath();
if (file_exists($thumbPath)) {
unlink($thumbPath); // Remove the thumb from the hard drive
}
}
DB::sql('DELETE FROM hm_files WHERE id = ' . $this->id); // Remove from database
}
// Set the filename and the file extension
public function setFileName($fileName) {
$this->fileName = $fileName;
$this->fileExtension = strtolower(substr(strrchr($this->fileName, '.'), 1));
$this->checkExtension();
$this->getFileType();
}
// Check if a file has an authorized extension
public function checkExtension() {
$okExtensions = F3::get('okExtensions'); // defined in config.php
if (in_array($this->fileExtension, $okExtensions)) {
$this->authorized = true;
} else {
$this->authorized = false;
}
return $this->authorized;
}
// Define the file type (eg: image, video, ...)
// Not used in this version
public function getFileType() {
$ext = $this->fileExtension;
if (isset($this->knownExtensions[$ext])) {
$this->fileType = $this->knownExtensions[$ext];
} else {
$this->fileType = 'file';
}
return $this->fileType;
}
public function getFileSize() {
$this->size = filesize($this->getFilePath());
return $this->size;
}
// Transform the filesize in kilobytes, megabytes, ... and append the unit.
public function getReadableSize() {
$bytes = $this->getFileSize();
$decimals = 2;
$sz = 'BKMGTP';
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . #$sz[$factor];
}
// Get the HTML for the file list
public function getTableRow() {
F3::set('file', $this);
// We check if the file exist before displaying the table row
if (file_exists($this->getFilePath())) {
$tableRow = F3::render('views/table_row.php');
return $tableRow;
} else {
return '';
}
}
// Get a file path on the server harddrive
public function getFilePath() {
$path = F3::get('rootPath');
$uploadsFolder = F3::get('uploadFolder');
$this->filePath = $path . '/' . $uploadsFolder . '/' . $this->systemFilename;
return $this->filePath;
}
public function getSystemUrl() {
$base = F3::get('BASE');
$this->systemUrl = $base . '/file/' . $this->systemFilename;
return $this->systemUrl;
}
public function getOriginalUrl() {
$siteUrl = F3::get('siteUrl');
$uploadsFolder = F3::get('uploadFolder');
$this->originalUrl = $siteUrl . '/' . $uploadsFolder . '/' . $this->systemFilename;
return $this->originalUrl;
}
public function getMime() {
$filePath = $this->getFilePath();
$finfo = new finfo(FILEINFO_MIME);
$info = $finfo->file($filePath);
return $info;
}
public function gearUp($queryResult) {
$this->id = $queryResult['id'];
$this->fileName = $queryResult['fileName'];
$this->systemFilename = $queryResult['systemFilename'];
$this->fileType = $queryResult['fileType'];
$this->ts = $queryResult['time'];
$this->getSystemUrl();
$this->getOriginalUrl();
return $this;
}
// Display a single file
public static function display($systemFilename) {
$fileQuery = DB::sql('SELECT * FROM hm_files WHERE systemFilename LIKE "' . $systemFilename . '"');
if (count($fileQuery) > 0) {
$file = new file();
$file->gearUp($fileQuery[0]);
$mime = $file->getMime();
header('Content-Disposition: inline; filename="' . $file->fileName . '"');
header('Content-type: ' . $mime);
readfile($file->getOriginalUrl());
} else {
return false;
}
}
// Build a zip of files
// You can create direct download by setting $directDownload on true.
// Important : we don't use the classic ZipArchive class of PHP. When we zip large files it produces errors.
// We use the pclzip class. Doc: http://www.phpconcept.net/pclzip/
public static function serveZip($idsArray, $token, $directDownload = true) {
if (count($idsArray) > 0) {
$rootPath = F3::get('rootPath');
$zipPath = $rootPath . '/zips/archive-' . $token . '.zip';
$zipper = new pclzip($zipPath);
foreach ($idsArray as $id) {
$file = file::fetch($id);
$filePath = $file->getFilePath();
$filesArray = array(
array(PCLZIP_ATT_FILE_NAME => $filePath,
PCLZIP_ATT_FILE_NEW_FULL_NAME => $file->fileName)
);
$zipper->add($filesArray, PCLZIP_OPT_NO_COMPRESSION, PCLZIP_OPT_REMOVE_ALL_PATH);
}
// We set the cookie to track the end of zipping
setcookie('multiUp', $token);
// If this is a direct download we serve the zip in the browser and then destroy the zipfile on the server
if ($directDownload) {
$zipContent = file_get_contents($zipPath);
header('Content-Disposition: attachment; filename="archive.zip"');
header('Content-type: application/zip');
echo $zipContent;
unlink($zipPath);
}
}
}
// Get info for a single file
public static function fetch($id) {
$fileQuery = DB::sql('SELECT * FROM hm_files WHERE id = ' . $id);
if (count($fileQuery) > 0) {
$file = new file();
$file->gearUp($fileQuery[0]);
return $file;
} else {
return false;
}
}
// Fetch all files in the database
public static function fetchAll() {
$files = array();
$filesId = DB::sql('SELECT id FROM hm_files ORDER BY time DESC');
foreach ($filesId as $fileId) {
$file = file::fetch($fileId['id']);
if ($file) {
$files[] = $file;
}
}
return $files;
}
// Creates families for file extensions
// Not used in this version. Might be usefull to create icons
private function setKnownExtensions() {
$fileTypes = array();
// DOCUMENTS
$fileTypes['pdf'] = 'pdf';
// PLAIN TEXT
$fileTypes['txt'] = 'text';
$fileTypes['rtf'] = 'text';
$fileTypes['as'] = 'text';
$fileTypes['xml'] = 'text';
$fileTypes['html'] = 'text';
$fileTypes['htm'] = 'text';
$fileTypes['js'] = 'text';
$fileTypes['php'] = 'text';
$fileTypes['asp'] = 'text';
$fileTypes['py'] = 'text';
$fileTypes['sql'] = 'text';
$fileTypes['css'] = 'text';
// ARCHIVES
$fileTypes['zip'] = 'archive';
$fileTypes['rar'] = 'archive';
$fileTypes['7zip'] = 'archive';
$fileTypes['gzip'] = 'archive';
$fileTypes['gz'] = 'archive';
$fileTypes['tgz'] = 'archive';
$fileTypes['ace'] = 'archive';
$fileTypes['arc'] = 'archive';
// EXCEL
$fileTypes['xls'] = 'excel';
$fileTypes['xlsx'] = 'excel';
$fileTypes['xlsm'] = 'excel';
$fileTypes['ods'] = 'excel';
$fileTypes['ots'] = 'excel';
$fileTypes['csv'] = 'excel';
$fileTypes['numbers'] = 'excel';
// WORD
$fileTypes['doc'] = 'word';
$fileTypes['docx'] = 'word';
$fileTypes['odt'] = 'word';
$fileTypes['ott'] = 'word';
$fileTypes['pages'] = 'word';
// POWERPOINT
$fileTypes['ppt'] = 'powerpoint';
$fileTypes['pptx'] = 'powerpoint';
$fileTypes['odp'] = 'powerpoint';
$fileTypes['otp'] = 'powerpoint';
$fileTypes['key'] = 'powerpoint';
// IMAGES
$fileTypes['png'] = 'image';
$fileTypes['gif'] = 'image';
$fileTypes['jpg'] = 'image';
$fileTypes['jpeg'] = 'image';
// UNCOMMON IMAGEs
$fileTypes['svg'] = 'rareimage';
$fileTypes['svgz'] = 'rareimage';
$fileTypes['jpf'] = 'rareimage';
$fileTypes['bmp'] = 'rareimage';
$fileTypes['eps'] = 'rareimage';
$fileTypes['tif'] = 'rareimage';
$fileTypes['tiff'] = 'rareimage';
$fileTypes['raw'] = 'rareimage';
$fileTypes['pbm'] = 'rareimage';
$fileTypes['tga'] = 'rareimage';
$fileTypes['cdr'] = 'rareimage';
// "WORKING" IMAGES
$fileTypes['psd'] = 'photoshop';
$fileTypes['psb'] = 'photoshop';
$fileTypes['ai'] = 'illustrator';
$fileTypes['ait'] = 'illustrator';
$fileTypes['fxg'] = 'illustrator';
$fileTypes['cgm'] = 'illustrator';
$fileTypes['indd'] = 'indesign';
$fileTypes['idml'] = 'indesign';
$fileTypes['fla'] = 'flash';
$fileTypes['swf'] = 'flash';
$fileTypes['xfl'] = 'flash';
$fileTypes['prproj'] = 'premiere';
$fileTypes['aep'] = 'aftereffect';
// 3D
$fileTypes['3ds'] = '3d';
$fileTypes['dwg'] = '3d';
$fileTypes['dxf'] = '3d';
$fileTypes['max'] = '3d';
// SOUND / MUSIC
$fileTypes['mp3'] = 'music';
$fileTypes['wav'] = 'music';
$fileTypes['flac'] = 'music';
$fileTypes['aac'] = 'music';
$fileTypes['aiff'] = 'music';
$fileTypes['aif'] = 'music';
$fileTypes['aifc'] = 'music';
$fileTypes['wma'] = 'music';
$fileTypes['au'] = 'music';
$fileTypes['snd'] = 'music';
$fileTypes['aa3'] = 'music';
$fileTypes['oma'] = 'music';
$fileTypes['at3'] = 'music';
$fileTypes['m3u'] = 'music';
$fileTypes['amr'] = 'music';
$fileTypes['cda'] = 'music';
//VIDEO
$fileTypes['avi'] = 'video';
$fileTypes['flv'] = 'video';
$fileTypes['m4v'] = 'video';
$fileTypes['mkv'] = 'video';
$fileTypes['mov'] = 'video';
$fileTypes['mpeg'] = 'video';
$fileTypes['mpg'] = 'video';
$fileTypes['mpe'] = 'video';
$fileTypes['mp4'] = 'video';
$fileTypes['3gp'] = 'video';
$fileTypes['aep'] = 'video';
$this->knownExtensions = $fileTypes;
}
}
?>
It worked fine on managed servers that have CPanel thats why i suspect my PHP.ini file? (i installed the server myself)
If it is the .ini file, what should i look for?
The script changes the file names on purpose, to guarantee they are always unique. This prevents a file from getting overwritten if someone uploads a file with the same file name. If you really want to retain the original name, you can change this line:
$targetFile = str_replace('//', '/', $uploadUrl) . $this->systemFilename;
to this:
$targetFile = str_replace('//', '/', $uploadUrl) . $this->fileName;
Note that although the script assigns a unique name to each uploaded file, it still retains the original name in the database table as shown here:
DB::sql('INSERT INTO hm_files (fileName, systemFilename, fileType, time) VALUES ("' . $this->fileName . '", "' . $this->systemFilename . '", "' . $this->fileType . '", ' . $this->ts . ')');

Categories