I have been working on a little PHP script that dynamically creates & saves images in a folder tmp (which already exists!) from a base64 string. This is my save.php file.
// get base-64 string from form
$filteredData = substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);
// decode string
$unencodedData = base64_decode($filteredData);
// create unique filename
$a = uniqid();
// name, location and file extension
$compfile = '/tmp/' . $a . '.png';
// save image
file_put_contents($compfile, $unencodedData);
// print image
echo '<img src="' . $compfile . '" />';
Strangely enough: It will neither create nor render the image on the page, because of the /tmp/ in my $compfile variable. When I remove it, everything works like a charm and the image is being created in the same folder.
Unfortunately, I really want the image to be created in the /tmp/ folder. Before $compfile was a randomly generated filename, and instead was called /tmp/img.png I was able to save to create an image by the name img.png and save it to the tmp.
What am I missing here?
(Thank you for your time.)
Since I guess this was the solution I'll post it as answer.
I think you want "tmp/" . $a . ".png" instead of "/tmp/" . $a . ".png". It's good practice to just always use absolute paths, so: __DIR__ . "/tmp/" . $a . ".png". This takes away any confusion.
Related
No matter which function I'm using:
copy("http:" . $imglink, "images/" . substr($imglink, 34));
//or
file_put_contents("images/" . substr($imglink, 34), file_get_contents("http:" . $imglink));
//or
file_put_contents("images/" . $productData['imagefile'], fopen($productData['imagelink'], 'r'));
the files are saved broken and almost 4 times bigger. No errors in the log,
already checked that I can manually download healthy images from the remote server through the browser. Any ideas?
Found the problem - the image filename contains space char which should be
rawurlencode($imglink)-ed before it is passed as argument
Alright so everything is being saved properly but how can I get the url of the file I am saving?
$songs = file_get_contents('https://example.com/tracks/'.$id.'/');
file_put_contents('./tmp/' . stripslashes(htmlspecialchars($songTitle)) . '.mp3', $songs);
Without manually having to get every url, please note I am a new developer still learning.. but is there not something I can just echo into an ??
Edit: ' . stripslashes(htmlspecialchars($songTitle)) . ' this is just the name of the file that we're downloading, nothing important about that string.
This depends on your setup, but if your script is in an externally accessible location and you trust $_SERVER client-defined fields, you can use __FILE__ and $_SERVER to accomplish what you want.
The code below assumes:
Your server is not on HTTPS;
Files in the subdirectory tmp can be accessed externally;
You can write to the subdirectory tmp.
$_SERVER['HTTP_HOST'] and $_SERVER['REQUEST_URI'] can be "trusted".
Try this:
// This is the only thing you need to set to your taste.
$dest_rel_path = 'tmp/' . stripslashes(htmlspecialchars($songTitle)) . '.mp3';
// This is the final file path in your filesystem.
// `dirname(__FILE__)` can be replaced with __DIR__ in PHP >= 5.3.0
// and the str_replace() part makes the code portable to Windows.
$filesystem_path = dirname(__FILE__) . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $dest_rel_path);
$songs = file_get_contents('https://example.com/tracks/'.$id.'/');
file_put_contents($filesystem_path, $songs);
// This takes the URL that the user requested and replaces the
// part after the last '/' with our new .mp3 location.
$req_uri = $_SERVER['REQUEST_URI'];
$url_path = substr($req_uri, 0, 1 + strrpos($req_uri, '/')) . $dest_rel_path;
$url = 'http://' . $_SERVER['HTTP_HOST'] . $url_path;
echo "This is my link to $songTitle!";
You can't, at least not directly, since it does not work that way: the filesystem does not necessarily translate to an URL.
For instance, in your case, you're saving the file into the tmp directory. I doubt that directory is accessible in any way to the outside world, ie, that it has a public URL than you can access in your browser.
I have been generating the PDFs and download it. Everything works fine. But whenever the file is output, it simply replaces the previous generated file.
Is there any way to output the file with the different name every time the NEW user downloads it by selecting data from the database?? What changes I can make in Output() method?
I have read output() doc.
$mpdf->Output("PDFs/something.pdf");
// change the path to fit your websites document structure
$fullPath = "PDFs/something.pdf";
You can do:
$filename = 'pdf' . time(). '.pdf';
$mpdf->Output("PDFs/$filename");
You can attach some timestamp/date with filename.
$filename = "PDFs/something-" . time() . ".pdf";
$mpdf->Output($filename);
// change the path to fit your websites document structure
$fullPath = $filename;
With the help of the answer given by Ramesh and some help from Immibis, I have found my way like this. Since the 'proposal_id' will always be unique in my case, so there will be no chance of downloading two pdfs of same id at the same time by different users.
$con = mysqli_connect("localhost","root","","my_db");
$name="Select name FROM table_name WHERE proposal_id= '$id'";
$name_result= mysqli_query($con,$name);
$row_name= mysqli_fetch_array($name_result);
$filename = $row_name['name']. time();
$mpdf->Output("PDFs/$filename.pdf");
$fullPath = "PDFs/$filename.pdf";
Hey my php/mysql/html people,
I have this variable that holds a path to an image and then insert it into a db (yes, I am using mysql_real_escape_string) which works perfectly.
$file_name = $_FILES["file"]["name"];
$path='images\ '. $file_name;
insert into...blah blah blah
The path is later pulled from the db and stored in said variable.
$path = $row['file_path'];
I am trying to display it with:
// the contents of $path in this case is: images\ cats.jpg
echo "<img src=" . $path . ">";
However the image breaks because the only thing that src pics up is: images\
and not the actualname+extension of the image. I know this probably has to do with the slashes, but I am a newbie and could use some help. Thanks in advance!
your
$path='images\ '. $file_name;
should be
$path='images\'. $file_name;
Print $path variable & see the values.
echo $path;exit;
You will get value on web browser.
Copy the value displayed on browser & paste it in the URL, if you see the image, your saved path is correct, if not, you have gone wrong in specifying the relative path too the resource.
1.Hi, I have a internal use only file upload script that uploads the files to a directory. When I upload something from my computer with a spcace in the name i.e example 1.zip it uploads with a space in the name thus killing the link in a email. Is it possible to make apache remove the space when its uploaded or make it a underscore?
The second problem I am having is how would I parse this to make the link an email link with the url of the file as the body of the email amd the email addy anything?
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir . $_FILES['file']['name'])) {
// uploaded file was moved and renamed succesfuly. Display a message.
echo "Link: " . "http://example.org/" . $_FILES["file"]["name"];
You just need to urlencode() your file name and everything is fine:
echo "Link: http://example.org/" . urlencode($_FILES["file"]["name"]);
But if you want to remove the spaces for another reason, you can use str_replace():
$replaced_name = str_replace(' ', '_', $_FILES["file"]["name"]);
rename($uploaddir . '/' . $_FILES['file']['name'], $uploaddir . '/' . $replaced_name);
# You should urlencode() it nonetheless:
echo "Link: http://example.org/" . urlencode($replaced_name);
Try:
$filename = $_FILES['file']['name'];
$filename = preg_replace("/[^a-zA-Z0-9]/", "", $filename);
//then
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploaddir . $filename)) {
// uploaded file was moved and renamed succesfuly. Display a message.
echo "Link: " . "http://example.org/" . $filename;
As a side note : with the code you are using, what is happening if two files with the same name are uploaded ? If you don't do a check (like "is there a file that already has that name in $uploaddir ?") the second file will replace the first one.
That might not be something you want... is it ?
If not, to solve that (potential) problem, one solution is to always rename uploaded files, with names you control. (A simple counter would probably to the trick)
Another thing is : $_FILES["file"]["name"] is sent by the client, and, as such, can probably be forged to contains whatever someone would want. If it contains something like "../../index.php" (or something like this - you get the idea), this could allow someone to put any file they want on your server.
To prevent this from happening, you shoud be sure the file name/path used as destination of move_uploaded_file does not contain anything "dangerous". A solution could be to use basename. (see, for instance, example #2 on POST method uploads)
You might also want to check the mimetype of the uploaded file, so you don't get executables, for instance -- and you should make sure files uploaded are not executable by the webserver.