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';
}
Related
Let's say I want to create a unique one-time link to encrypt via md5.Script at the bottom
$file1 = "/img/img1.jpeg";
$hash1 = md5($file1 . time());
$notepad = "notepad.txt";
file_put_contents($notepad, $hash1 . "\n", FILE_APPEND);
echo "Link for : <a href='download.php?file=".$file1.".&hash=" . $hash1 . "'>Download</a><br>";
and I have download.php
$file = $_GET['file'];
$hash = $_GET['hash'];
$notepad = "notepad.txt";
$hashes = file($notepad);
if (in_array($hash . "\n", $hashes)) {
header("Content-Type: application/octet_stream");
header("Content-Disposition: attachment; filename=" . basename($file));
header("Content-Length: " . filesize($file));
readfile($file);
$hashes = array_diff($hashes, array($hash . "\n"));
file_put_contents($notepad, implode($hashes));
} else {
echo "The link you are trying to use is invalid or has already been used.";
}
Yes, everything works fine, but the problem is that when I follow the link, the path where $file1 is located is visible, for example, one-time link:
http://localhost:8080/project/download.php?file=img/img1.jpeg.&hash=e4b105d20845e7ee82f782c01f833786
And I want a one-time link for each file to look like this:
http://localhost:8080/project/download.php?hash=e4b105d20845e7ee82f782c01f833786
So that the path of the file is not visible.
How can this be implemented?
I'm trying to make 2 option names to download a file: Dictionary and Random.
When the user selects the dictionary option it downloads the file constantly with the name 'download' instead of some random word from the dictionary and the random option works fine.
I tried using the load function and printing what it returns and it does print the actual randomly picked word from the dictionary but it doesn't in the download part. I'm guessing its something with the headers but it might not.
That's the load function which loads the dictionary from a file on the server:
function load($file) {
$file_arr = file($file);
$num_lines = count($file_arr);
$last_arr_index = $num_lines - 1;
$rand_index = rand(0, $last_arr_index);
$rand_text = $file_arr[$rand_index];
return $rand_text;
}
That's the download function which downloads the file:
function download($file, $filename) {
header("Content-Type: application/jpeg");
header("Content-Length: " . filesize($file));
header('Content-Disposition: attachment; filename="' . $filename . '"');
readfile($file);
exit();
}
That's how I call the functions:
$filename = load("includes/dictionary_words.txt");
download($file, $filename);
Lastly the $file variable:
$file = "main/app.exe";
Instead of downloading the file with a random dictionary name it downloads it with a 'download' name. I didn't get any errors or notices.
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'm currently making a controller to download files from the server.
It all happens in the index action:
public function indexAction() {
$schuurName = $this->_getParam('storageID');
$fileName = $this->_getParam('fileName');
$name = explode('.', $fileName)[0];
$path = '..' . DIRECTORY_SEPARATOR . 'schuren' . DIRECTORY_SEPARATOR . $schuurName . DIRECTORY_SEPARATOR . $fileName;
if (file_exists($path)) {
$mimeType = mime_content_type($fileName);
header('Content-Type: ' . $mimeType);
header('Content-Length: ' . filesize($path));
header('Content-Disposition: attachment; filename=' . $name . ';');
$resource = fopen($path, 'r');
while (!feof($resource)) {
$chunk = fread($resource, 4096);
echo $chunk;
}
$this->view->layout()->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
}
else {
echo 'file doesn\'t exist';
}
}
So the downloading works right now, I'm testing it with an image of 725 bytes. The problem is.. The image is corrupted so it couldn't be seen/edited. What am I doing wrong in my code?
Thanks!
You should use binary mode. Use the 'rb' flag.
From the php Manual : If you do not specify the 'b' flag when working with binary files, you may experience strange problems with your data, including broken image files and strange problems with \r\n characters.
http://www.php.net/manual/en/function.fopen.php
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);