I am using wordpress for my website and there are some wallpapers in my folder which i provide for download . But i dont want users to know the exact file location of folder . As there is a subscription for the download.
suppose my file is stored in
http://www.example.com/wp-content/example.folder/awesome.png
Now how to hide the folder name example.folder and use any fake name, That dosent shows up while downloading . Really need a big help on this. can anyone suggest me a good method. I tried some wordpress plugins , but no help on this.
Example With PDF doc
$nameOld = "/public_html/wp-content/example.folder/oldnme.pdf";
$nameNew = "newName.pdf" ;
header("Content-Transfer-Encoding: binary");
header('Content-type: application/pdf');
header("Content-disposition: attachment; filename=$nameNew"); //
readfile($nameOld);
Edit
Prove of Concept for your image system using download.php?img=flower without the extension and flower show be the image name
$directory = "/public_html/wp-content/example.folder/";
$types = array("jpg","gif","png");
$ext = null;
if (! isset($_GET['img'])) {
die("Invalid URL");
}
$nameOld = filter_var($_GET['img'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_LOW);
$nameNew = uniqid(basename($nameOld));
// File the file
foreach ( $types as $type ) {
if (is_file($nameOld . "." . $type)) {
$ext = $type;
break;
}
}
if ($ext == null) {
die("Sorry Image Not Found");
}
$nameOld .= "." . $ext;
$type = image_type_to_mime_type(exif_imagetype($nameOld));
header("Content-Transfer-Encoding: binary");
header('Content-type: ' . $type);
header("Content-disposition: attachment; filename=$nameNew"); //
readfile($nameOld);
Related
I'm trying to get a couple files from wordpress /uploads folder using php and I get this error:
Warning: ZipArchive::close(): Can't remove file: No such file or directory in /www/public_html/wp-content/plugins/insert-php-code-snippet/shortcode-handler.php(65) : eval()'d code on line 32 (relative to $zip->close(); and bellow "if")
I use a plugin to inject PHP on the page.
I basically have a couple dozens checkboxes that when I press "Generate", it gets the name of the file like 07/2019/blabla (with code I get uploads folder + extension, checkbox only hold the media location + name file).
I checked and it's creating the Zip on /uploads, .pdf files exist but it crashes on the close part and when I download and try to extract I get the archive is either in unknown format or damaged
Any advise please?
if(isset($_POST['files'])) {
$error = ""; //error holder
$upload_dir = wp_upload_dir();
if(isset($_POST['createzip'])){
$post = $_POST;
if(isset($post['files']) and count($post['files']) > 0){
// open zip
$zip_file = $upload_dir['basedir'].'/'.time().".zip";
$zip_name = time().".zip";
$zip = new ZipArchive();
if ($zip->open($zip_file, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== TRUE) {
$error .= ("An error occurred creating your ZIP file.<br>");
}
foreach ($post['files'] as $file) {
// generate filename to add to zip
$filepath = $upload_dir['basedir'].'/' . $file . '.pdf';
if (file_exists($filepath)) {
$zip->addFile($filepath) or $error .= ("ERROR: Could not add the file $filename<br>");
} else {
$error .= ("File $filepath doesnt exit.<br>");
}
}
$zip->close();
if ($zip->close() !== true ) {
die($zip->getStatusString()."\n");
}
if(file_exists($zip_file)){
$error .= $zip_file;
ob_end_clean();
// push to download the zip
header('Content-type: application/zip');
header('Content-Disposition: attachment; filename="'.$zip_name.'"');
header("Content-Length: " . filesize($zip_file));
readfile($zip_file);
unlink($zip_file);
}
}
}
}
echo $error;
After $zip->close(); I replaced all code for this:
if(file_exists($zip_file)){
header($_SERVER['SERVER_PROTOCOL'].' 200 OK');
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: Binary");
header("Content-Length: ".filesize($zip_file));
header("Content-Disposition: attachment; filename=\"".basename($zip_file)."\"");
readfile($zip_file);
unlink($zip_file);
exit;
}
Part of what's being displayed:
PKd�wL��� ���/images/image_0.jpg��ex\K��1昙�3�133���;ffff����Ԇ�����w�̼߳�cw��딎�$��Z�������&QRTB�|>��E��M5���|�~b��)�o�3�� �>s���o�'���^B�O��V ����#���Q?S#(�� 6���v4���8����vvV�sy}#�_ �O��s�o���L�7Fv.F&�ol��WV.V��?�����g�W!�/w!�������K�oLL�1`���G�p�X���T�>C�#��L��)q���s��3�g�8�p�O�?
I'm trying to download images into zip file, this is what i've got so far:
if (count($headers->images) > 0) {
$counter = 0;
$zip = new ZipArchive();
$tmpFile = "tmpFolder/tmp" . strtotime("now") . ".zip";
$zip->open($tmpFile, ZipArchive::CREATE);
foreach($headers->images as $key => $images) $zip->addFromString("/images/image_" . $counter++ . ".jpg", file_get_contents($images));
$zip->close();
if (file_exists($tmpFile)) {
$fname = basename($_POST["titleZipFile"] . ".zip");
$size = filesize($tmpFile);
header("Content-Type: archive/zip");
header("Content-Disposition: attachment; filename=$fname");
header("Content-Length: " . $size);
ob_end_clean();
readfile($tmpFile);
//unlink($tmpFile);
echo "<div id='reportMessage'><p>You have successfully save images. Please go to your folder " . $_POST["titleZipFile"] . ".zip<p></div>";
}
}
if I remove the unlink($tmpFile); line then the tmp zip is actually generated and has the images inside the zip. However it's not actually showing the zip downloading in browser.
Does any one have any ideas why this could be happening?
Try to change the header for the content type to the following. I think the header is causing the browser problems with interpreting what it is supposed to do. Try the following type.
header('Content-type: application/zip');
I searched and tried a few previous questions/example codes, but couldn't get this to work.
I'm trying to deliver the results to end-users via PHP code. Here is my code.
$varZipFile = $varBaseNameParts[0] . '.' . $varDate . '.zip';
$varZipDir = $varBaseNameParts[0] . '_' . $varDate;
$zip = new ZipArchive();
$zip->open($varZipFile, ZipArchive::CREATE | ZipArchive::OVERWRITE);
$zip->addFile('008.csv');
$zip->addFile('002.csv');
$zip->close(); // mark line xxx
header("Content-Type: application/zip");
header("Content-disposition: attachment;filename=$varZipFile");
header('Content-Length: ' . filesize($varZipFile)); // with or without this line, got the same error
header("Content-Type: application/force-download"); // with or without this line, got the same error
readfile($varZipFile);
I got the .zip file in my browser. However WinZip cannot open it, neither can 7-Zip. WinZip complains that "Error: Central directory not found".
Interestingly, when I manually transfer the file via WinSCP from my server to my Windows machine, I can open the file with either WinZip or 7-Zip. This indicates it works all fine to 'mark line xxx', and problems occurs in the header lines.
TIA!
Your ouput buffer may not be cleared before you try to serve the download. Try to clean the output buffer before serving the download with the ob_clean() function like this:
$zip->close(); // mark line xxx
ob_clean();
Your code is working well on my side, debug this $varBaseNameParts[0] to see if the value is correct or try the below code.
// $name = name of the archive
// $archive_directory = directory to save the archive
// $file_array = list of files
function create_archive($name, $archive_directory, $file_array) {
$target_file = $archive_directory . '/' . $name . date('m-d-y').date('h-i-sa') . '.zip';
$zip = new ZipArchive();
if (count($file_array)) {
if ($zip->open($target_file, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE)) {
foreach ($file_array as $file) {
$zip->addFile($file);
}
$zip->close();
chmod($target_file, 0777);
return $target_file;
}
}
return null;
}
function create_download($archive) {
$file_name = basename($archive);
header("Content-Type: application/zip");
header("Content-Disposition: attachment; filename=$file_name");
header("Content-Length: " . filesize($archive));
readfile($archive);
}
// create the archive file
$archive = create_archive('test', 'archive', ['008.csv', '002.csv']);
if ($archive) {
create_download($archive);
}
So I'm fairly new to PHP and have been working on a web app that allows users to submit designs which are then saved as images (using html2canvas.js) to the server. I have the app working at the moment but it saves over any previous image with the same file name.
What I would like it to do is save with a consecutive number at the end of the file name so that previous designs are not overwritten. Working code below - the idea with the if else statement is that it checks for an existing file, if there isnt one, creates it (this code works) but if there is an existing file ... I dont know..
<?php
session_start();
$customerName = $_SESSION["design_name"];
//Get the base-64 string from data
$filteredData=substr($_POST['img_val_server'], strpos($_POST['img_val_server'], ",")+1);
//Decode the string
$unencodedData=base64_decode($filteredData);
//Check for previous user images
$fileName = '/customer-submits/design-' . $customerName . '.png';
if (file_exists($filename)) {
//THIS IS WHERE IS WANT THE FILE TO SAVE CONSECUTIVELY
} else {
//Save the image
file_put_contents('customer-submits/design-' . $customerName . '.png', $unencodedData);
$file = 'customer-submits/design-' . $customerName . '.png' ;
$fileName = basename($file);
$fileSize = filesize($file);
set_time_limit(0);
header("Pragma: public");
header("Expires: 0"); // Cache Options
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); // Cache Options
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\" " . $fileName ."\"");
header("Content-length: " . $fileSize);
readfile($file);
include 'sendMail.php';
echo send_mail();
}
?>
Would obviously very much appreciate any help with this, as Im struggling to get my head around php!
This should add a new number to the end of the customers name if a similar customers name appears.
$num = 0;
while (file_exists($filename)==TRUE) {
$num++;
$file = 'customer-submits/design-' . $customerName $num . '.png' ;
}
I added ==TRUE into my previous code which makes it a Boolean and should take away the parsing error you got earlier.
Try this after "//Check for previous user images", replacing the if...else:
$indx = 1;
$filename = '/customer-submits/design-' . $customerName . $indx . '.png';
while (file_exists ($filename) {
$indx++;
$filename = '/customer-submits/design-' . $customerName . $indx . '.png';
}
i start my downloads with a php script, it's very simple and looks like this:
$dir = 'downloads/';
$type = 'application/x-rar-compressed, application/octet-stream, application/zip';
function makeDownload($file, $dir, $type)
{
header("Content-Type: $type");
header("Content-Disposition: attachment; filename=\"$file\"");
readfile($dir.$file);
}
if(!empty($_GET['file']) && !preg_match('=/=', $_GET['file'])) {
if(file_exists ($dir.$_GET['file'])) {
makeDownload($_GET['file'], $dir, $type);
}
}
It works fine on win7 + ff/opera/chrome/safari, but on MAC it tries to download file.rar.html or file.zip.html instead of file.rar/file.zip.
Any ideas why?
Thanks in advance
"application/x-rar-compressed, application/octet-stream, application/zip" is not a valid file type. You need to add logic in your script to detect the type of file, then offer a specific file type. Example (untested):
<?php
$dir = 'downloads/';
function makeDownload($file, $dir)
{
switch(strtolower(end(explode(".", $file)))) {
case "zip": $type = "application/zip"; break;
case "rar": $type = "application/x-rar-compressed"; break;
default: $type = "application/octet-stream";
}
header("Content-Type: $type");
header("Content-Disposition: attachment; filename=\"$file\"");
readfile($dir.$file);
exit; // you should exit here to prevent the file from becoming corrupted if anything else gets echo'd after this function was called.
}
if(!empty($_GET['file']) && !preg_match('=/=', $_GET['file'])) {
if(file_exists ($dir.$_GET['file'])) {
makeDownload($_GET['file'], $dir);
}
}
?>