Not able store docx,pdf,csv files in GridFs - php

I'm have using Php, MongoDb and GridFs to store and retrieve files. It works fine for images, but I want to store files with docx, pdf, csv and etc. extensions. Here is my code:
$ext = $this->getFileExt($_FILES["news_attachment"]["name"]);
switch ($ext) {
case 'pdf':
$mimeType = 'application/pdf';
break;
case 'doc':
$mimeType = 'application/msword';
break;
case 'docx':
$mimeType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
break;
case 'xls':
$mimeType = 'application/vnd.ms-excel';
break;
case 'xlsx':
$mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
break;
case 'ppt':
$mimeType = 'application/x-mspowerpoint';
break;
case 'pptx':
$mimeType = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
break;
case 'csv':
$mimeType = 'text/csv';
break;
case 'txt':
$mimeType = 'text/plain';
break;
default:
$mimeType='application/pdf';
}
$gridFs = $this->getGridFs();
$fileData = array(
"filename" => microtime(true) . "." . $ext,
"contentType" => $mimeType);
$_id = $gridFs->storeUpload("news_attachment", $fileData);
But I get the same error message Message: error setting up file: . I've checked the file size is 78kb, $fileData is ok also. So, my question is - What else can caused this error?

Would you not be supplying the same argument when trying to upload:
$gridFs->storeUpload($_FILES["news_attachment"]["name"],
or possibly
$gridFs->storeUpload($_FILES["news_attachment"]["tmp_name"],

I just need to add check for error if(!empty($_FILES["news_attachment"]) && $_FILES["news_attachment"]["error"] == 0){ save file}

Related

image extension is not showing in PHP file-upload

I'm using this piece of code to handle an input for uploading multiple images, and resizing them as well. It works but there is one small thing that doesn't want to do its job. The extension that I'm trying to get is not showing up in the file's name.
Here is the piece of code where the problem should be:
if(isset($_POST["submit"])) {
if(is_array($_FILES)) {
foreach ($_FILES['fileToUpload']['tmp_name'] as $uploadedFile) {
//$uploadedFile = $_FILES['fileToUpload']['tmp_name'];
if($uploadedFile <> ''){
$sourceProperties = getimagesize($uploadedFile);
$newFileName = time();
$dirPath = "../images/";
$ext = pathinfo($_FILES['fileToUpload']['name'], PATHINFO_EXTENSION);
$imageType = $sourceProperties[2];
switch ($imageType) {
case IMAGETYPE_PNG:
$imageSrc = imagecreatefrompng($uploadedFile);
$tmp = imageResize($imageSrc,$sourceProperties[0],$sourceProperties[1]);
imagepng($tmp,$dirPath. $newFileName. "_thump.". $ext);
break;
case IMAGETYPE_JPEG:
$imageSrc = imagecreatefromjpeg($uploadedFile);
$tmp = imageResize($imageSrc,$sourceProperties[0],$sourceProperties[1]);
imagejpeg($tmp,$dirPath. $newFileName. "_thump.". $ext);
break;
case IMAGETYPE_GIF:
$imageSrc = imagecreatefromgif($uploadedFile);
$tmp = imageResize($imageSrc,$sourceProperties[0],$sourceProperties[1]);
imagegif($tmp,$dirPath. $newFileName. "_thump.". $ext);
break;
default:
echo "<div class='alert alert-danger'>File is not an image.</div>";
exit;
break;
}
}
}
}
}
For an example, something it is now saving is called 1547265041_thump. in my database.
What is going wrong?
Check $ext getting extension or not.
If it not getting check $_FILES['fileToUpload']['name'] reading or not.
You can debug by echo them.
Check you database character length.
Hope it helps.
The $_FILES['fileToUpload']['name'] seems to be an array, which is logical since you can upload multiple images at once. To loop through, I added a counter to the foreach to output the extension. Now it works well!

How can I make an image with this kind of data in PHP?

I'm using the getID3() function (available at
https://github.com/JamesHeinrich/getID3) for getting the image cover of
MP3 files.
I'm using this part of the code for that:
$path="mp3/3.mp3";
require_once('getid3/getid3.php');
$getID3 = new getID3;
$getID3->setOption(array('encoding'=>$TextEncoding));
$ThisFileInfo = $getID3->analyze($path);
getid3_lib::CopyTagsToComments($ThisFileInfo);
$info=$ThisFileInfo['comments'];
$TextEncoding = 'UTF-8';
$data=$info['picture'][0]['data'];
$mime_type=$info['picture'][0]['image_mime'];
$im_width=$info['picture'][0]['image_width'];
$im_height=$info['picture'][0]['image_height'];
For showing the image, I use this:
echo'<html><body>'."\n".'<tr><td><img src="data:'.$mime_type.';base64,'.base64_encode($data).'" width="'.$im_width.'" height="'.$im_height.'"></td></tr></body></html>'."\n";
But nothing is showing.
I want to save $data as an image file.
How can I do that?
To simply create an image file from a string, or from any format you need the gd extension for php.
FROM STRING
$toFilePath = '/path/to/save/data/filename';
//notice the missing file extension.It will be added according to the mime_type.
//Make sure you have the write rights to the folder/file above
$im = imagecreatefromstring($data); //create image data from the string
if ($im !== false) { //if the image creation is successful
switch($mime_type) {
case 'image/jpeg':
case 'image/jpg':
imagejpg($im, $toFilePath.'.jpg', 100);
break;
case 'image/png':
imagepng($im, $toFilePath . '.png');
break;
case 'image/gif':
imagegif($im, $toFilePath . '.gif');
break;
case 'image/bmp':
imagebmp($im, $toFilePath . '.bmp');
break;
}
imagedestroy($im);
}
FROM BLOB/BINARY DATA (The code snippets below are tailored specifically for this library.)
$toFilePath = '/path/to/save/data/filename';
//notice the missing file extension.It will be added according to the mime_type.
//Make sure you have the write rights to the folder/file above
switch($mime_type) {
case 'image/jpeg':
case 'image/jpg':
$toFilePath .= '.jpg';
break;
case 'image/png':
$toFilePath .= '.png';
break;
case 'image/gif':
$toFilePath .= '.gif';
break;
case 'image/bmp':
$toFilePath .= '.bmp';
break;
}
if ($handle = fopen($toFilePath, 'wb')) {
fwrite($handle, $data);
fclose($handle);
}
The code is taken from https://github.com/JamesHeinrich/getID3/blob/master/demos/demo.mp3header.php and stripped down to fit the needs of OP
EXTRACT ALL THE IMAGES FROM THE FILE
function extractImages($pictureInfo) {
$toFilePath = __DIR__ . DIRECTORY_SEPARATOR . 'output' . DIRECTORY_SEPARATOR . 'filename';
//notice the missing file extension.It will be added according to the mime_type.
//Make sure you have the write rights to the folder/file above
for ($i = 0, $count = count($pictureInfo);$i < $count;$i++) {
$data = $pictureInfo[$i]['data'];
$mime_type = $pictureInfo[$i]['image_mime'];
switch ($mime_type) {
case 'image/jpeg':
case 'image/jpg':
$toFilePath .= '_' . $i . '.jpg';
break;
case 'image/png':
$toFilePath .= '_' . $i . '.png';
break;
case 'image/gif':
$toFilePath .= '_' . $i . '.gif';
break;
case 'image/bmp':
$toFilePath .= '_' . $i . '.bmp';
break;
}
if ($handle = fopen($toFilePath, 'wb')) {
fwrite($handle, $data);
fclose($handle);
}
}
}
$path = __DIR__ . DIRECTORY_SEPARATOR . "mp3" . DIRECTORY_SEPARATOR . "3.mp3";
require_once(__DIR__ . DIRECTORY_SEPARATOR . 'getid3' . DIRECTORY_SEPARATOR . 'getid3.php');
$TextEncoding = 'UTF-8';
$getID3 = new getID3();
$getID3->setOption(array('encoding' => $TextEncoding));
$ThisFileInfo = $getID3->analyze($path);
getid3_lib::CopyTagsToComments($ThisFileInfo);
$info = $ThisFileInfo['comments'];
if (isset($info['picture'])) extractImages($info['picture']);
else {
echo 'no picture tag';
}

Pass font file through PHP

I have a website that is set up like this:
client request --> gate.php --> requested file
Every request the client sends goes to gate.php were it is parsed. Gate.php then includes the requested file from a restricted directory so that the client cannot access any file but gate.php.
Gate file:
<?php
$_uri = strtok($_SERVER["REQUEST_URI"],'?');
$_root = "<root>";
// Index //
switch($_uri) {
case "/": $_uri = "<path>"; break;
case "/css": $_uri = "<path>"; break;
case "/js": $_uri = "<path>"; break;
case "/font": $_uri = "<path>".strtok($_GET["p"],".")."/".$_GET["p"]; break;
case "/ajax": $_uri = "<path>"; break;
case "/signin": $_uri = "<path>"; break;
case "/signup": $_uri = "<path>"; break;
default:
if(substr($_uri,0,8) == "/profile") { // profile
$_uri = "<path>";
$_page = substr($_uri,9);
} else {
header("HTTP/1.1 404");
require_once($_root."<path>");
die();
}
}
!isset($_page) and isset($_GET["p"]) ? $_page = $_GET["p"] : 0;
// Mime //
$_path = explode(".",$_uri);
switch($_path[1]) {
case "php": $_path[2] = "text/html"; break;
case "css": $_path[2] = "text/css"; break;
case "js": $_path[2] = "application/javascript"; break;
case "xml": $_path[2] = "application/xml"; break;
case "svg": $_path[2] = "application/xml+svg"; break;
case "jpg": $_path[2] = "image/jpeg"; break;
case "png": $_path[2] = "image/png"; break;
case "otf": $_path[2] = "x-font/otf"; break;
case "eot": $_path[2] = "x-font/eot"; break;
case "ttf": $_path[2] = "x-font/ttf"; break;
case "woff": $_path[2] = "x-font/woff"; break;
default:
header("HTTP/1.1 500");
require_once($_root."<path>");
die();
}
$_path[2] == "text/html" ? require_once($_root."<path>") : 0;
// File //
header("Content-Type: ".$_path[2]);
require_once($_root."/sys".$_uri);
?>
The problem is, when I pass a font file through the gate, the font file contains the text <? which PHP parses and returns an error.
Is there any way to escape the font file so that PHP does not parse it?
You can only require files that can be interpreted by PHP. If you want to serve other kinds of files through your script, you have to output them by reading them.
Something like:
$file = 'myfontfile.ttf';
if (file_exists($file)) {
header('Content-Type: application/octet-stream');
header('Content-Disposition: inline; filename="'.basename($file).'"');
header('Content-Length: ' . filesize($file));
readfile($file);
exit;
}

PHP+Image type detection

I have a email script that sends file trough attachment from server. The email is sent using phpmailer and the attached file is attached in code like this:
$_img = (object) ($img);
if (!empty($_img->src)) {
$ext = substr($_img->src, -3);
$imginfo_array = getimagesize($_img->src);
$mime_type = $imginfo_array['mime'];
switch($mime_type) {
case "image/jpeg":
$type = "image/jpeg";
break;
case "image/png":
$type = "image/png";
break;
case "image/gif":
$type = "image/gif";
break;
}
$string = file_get_contents($_img->src);
$mail->AddStringAttachment($string, $i . '.' . $ext, 'base64', $type);
}
The problem occurs when a image is not properly saved before adding it to server. If one user decides that the file 'test.jpg' shoul be 'test.png' the attached file will not be visible via email.
The $_img->src is a file saved on server.
I am trying to check for mime type but still with no success.
I want to be able to tell the script that the correct file type is the one auto detected not determined by the extension.
Could someone give me a clue about how this could be done?
$_img = (object) ($img);
if (!empty($_img->src)) {
//$ext = substr($_img->src, -3);
// better solution for get file extension (with variable length: "jpeg" or "jpeg")
$ext = pathinfo($_img->src, PATHINFO_EXTENSION);
$imginfo_array = getimagesize($_img->src);
$mime_type = $imginfo_array['mime'];
switch($mime_type) {
case "image/jpeg":
$type = "image/jpeg";
$ext = 'jpg';
break;
case "image/png":
$type = "image/png";
$ext = 'png';
break;
case "image/gif":
$type = "image/gif";
$ext = 'gif';
break;
// fix for others mime type
default:
$type = "application/octet-stream";
}
// for binary file use AddAttachment()
//$string = file_get_contents($_img->src);
//$mail->AddStringAttachment($string, $i . '.' . $ext, 'base64', $type);
// I hope that the variable $i is set from previous code
$mail->AddAttachment($_img->src, $i . '.' . $ext, 'base64', $type)
}
You can detect the type of the image with the IMAGETYPE_XXX constants at index 2 of the returned imginfo_array. The returned mime field you are using is much less reliable.
See documentation:
http://php.net/manual/en/function.getimagesize.php
Type contants:
http://php.net/manual/en/image.constants.php

How to show file size when force the browser to download in PHP

I'm downloading mp4,mp3 etc.. files from my server with php. But browsers are not showing the size of file.
I searched everywhere but i couldn't find any working answer. Hope you can help me. Thanks in advance.
Here is the code :
function force_download($file)
{
$ext = explode(".", $file);
switch($ext[sizeof($ext)-1])
{
case 'jar': $mime = "application/java-archive"; break;
case 'zip': $mime = "application/zip"; break;
case 'jpeg': $mime = "image/jpeg"; break;
case 'jpg': $mime = "image/jpg"; break;
case 'jad': $mime = "text/vnd.sun.j2me.app-descriptor"; break;
case "gif": $mime = "image/gif"; break;
case "png": $mime = "image/png"; break;
case "pdf": $mime = "application/pdf"; break;
case "txt": $mime = "text/plain"; break;
case "doc": $mime = "application/msword"; break;
case "ppt": $mime = "application/vnd.ms-powerpoint"; break;
case "wbmp": $mime = "image/vnd.wap.wbmp"; break;
case "wmlc": $mime = "application/vnd.wap.wmlc"; break;
case "mp4s": $mime = "application/mp4"; break;
case "ogg": $mime = "application/ogg"; break;
case "pls": $mime = "application/pls+xml"; break;
case "asf": $mime = "application/vnd.ms-asf"; break;
case "swf": $mime = "application/x-shockwave-flash"; break;
case "mp4": $mime = "video/mp4"; break;
case "m4a": $mime = "audio/mp4"; break;
case "m4p": $mime = "audio/mp4"; break;
case "mp4a": $mime = "audio/mp4"; break;
case "mp3": $mime = "audio/mpeg"; break;
case "m3a": $mime = "audio/mpeg"; break;
case "m2a": $mime = "audio/mpeg"; break;
case "mp2a": $mime = "audio/mpeg"; break;
case "mp2": $mime = "audio/mpeg"; break;
case "mpga": $mime = "audio/mpeg"; break;
case "wav": $mime = "audio/wav"; break;
case "m3u": $mime = "audio/x-mpegurl"; break;
case "bmp": $mime = "image/bmp"; break;
case "ico": $mime = "image/x-icon"; break;
case "3gp": $mime = "video/3gpp"; break;
case "3g2": $mime = "video/3gpp2"; break;
case "mp4v": $mime = "video/mp4"; break;
case "mpg4": $mime = "video/mp4"; break;
case "m2v": $mime = "video/mpeg"; break;
case "m1v": $mime = "video/mpeg"; break;
case "mpe": $mime = "video/mpeg"; break;
case "mpeg": $mime = "video/mpeg"; break;
case "mpg": $mime = "video/mpeg"; break;
case "mov": $mime = "video/quicktime"; break;
case "qt": $mime = "video/quicktime"; break;
case "avi": $mime = "video/x-msvideo"; break;
case "midi": $mime = "audio/midi"; break;
case "mid": $mime = "audio/mid"; break;
case "amr": $mime = "audio/amr"; break;
default: $mime = "application/force-download";
}
header('Content-Description: File Transfer');
header('Content-Type: '.$mime);
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();
readfile($file);
}
if (isset($_POST['downl'])){
$file = "http://localhost/project1/downloads/gmf.mp4";
force_download($file);
}
<form method="POST" action=''>
<?php echo'<input type="submit" name="downl" value="Download Baby" >' ; ?>
</form>
If i try to show file size with echo filesize($file) it gives this error :
Warning: filesize(): stat failed for http://localhost/project1/downloads...
Since php 5.0.0 the file command supports http wrappers but the http wrapper does not support stat commands like size. So you cannot get the file size in your case with size.

Categories