I have a one-time link like in this:
<?php
session_start();
$file1 = "img/img1.jpeg";
$key1 = md5($file1 . microtime());
$_SESSION[$key1] = $file1;
$link1 = "download.php?key=" . $key1;
echo "<a href='" . $link1 . "'id='button1'>download</a><br>";
?>
download.php
<?php
session_start();
// Get the key from the query string
$key = $_GET['key'];
// Check if the key exists in the session
if(isset($_SESSION[$key])) {
$file = $_SESSION[$key];
// Remove the key from the session to prevent reuse
unset($_SESSION[$key]);
// Set the content type and headers for the file
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=" . basename($file));
header("Content-Length: " . filesize($file));
readfile($file);
}
else{
echo("Invalid link");
}
?>
Every time the page is refreshed, it creates a new one-time link that can only be used once.
And if I follow this link, the file will be downloaded. But when I follow it a second time, the link is no longer valid. How can I make the link update when clicking on it (without refreshing the page), so that the link is always valid?
I do not know how to do it? How can this be done? Via ajax? Or how?
Here you go:
<?php
session_start();
$file1 = "img/img1.jpeg";
$key1 = md5($file1 . microtime());
$_SESSION[$key1] = $file1;
$link1 = "download.php?key=" . $key1;
echo "<a href='" . $link1 . "'id='button1'>download</a><br>";
?>
download.php
<?php
session_start();
// Get the key from the query string
$key = $_GET['key'];
// Check if the key exists in the session
if(isset($_SESSION[$key])) {
$file = $_SESSION[$key];
// DO NOT remove the key from the session, to allow reuse
//unset($_SESSION[$key]);
// Set the content type and headers for the file
header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment; filename=" . basename($file));
header("Content-Length: " . filesize($file));
readfile($file);
}
else{
echo("Invalid link");
}
?>
It works now. :-)
(This answers your question, but if it's not what you wanted, you might need to be clearer about your objective and reasons.)
Related
Im trying to hide the src url for a pdf file in an iframe / embed. Im not sure how.
I tried with all the previously exiting answers, but none of them are working.
<?php
$url = $_GET['url'];
?>
<embed id="renderedPrint" style="height:calc(100% - 4px);width:calc(100% - 4px);padding:0;margin:0;border:0;"></embed>
<script>
$(document).ready(function() {
var encryptedString = "assets/labels/" + "<?php echo $url; ?>" + ".pdf";
$("#renderedPrint").attr("src", encodeURIComponent(encryptedString));
});
</script>
But no matter which method i use (Obfuscator, php openssl_encrypt/decrypt), the output url is always visible.
I dont want users to find the iframe/embed url. I want to make it difficult to or even hide the url from the front-end.
The purpose is that i dont want users to have direct access to the generated pdf file. They may copy the iframe src url and send it to someone else. We cant stop them from downloading the pdf, but i dont want them to copy the source url from the server.
check this code
you should be add file address to DB
<?php
// get id to search on DB and get detail
$id = $_REQUEST['id'];
try {
$conn = new PDO("pgsql:host=$host;port=5432;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$stmt = $conn->prepare("SELECT url FROM mytable WHERE id=? LIMIT 1");
$stmt->execute([$id]);
$row = $stmt->fetch();
// the address of file in server
$path = $row['url'];
$filename = basename($path);
if (file_exists($path) && is_readable($path)) {
// get the file size and send the http headers
$size = filesize($path);
header('Content-Type: application/octet-stream');
header('Content-Length: '.$size);
header('Content-Disposition: attachment; filename='.$filename);
header('Content-Transfer-Encoding: binary');
// open the file in binary read-only mode
// display the error messages if the file canĀ“t be opened
$file = # fopen($path, 'rb');
if ($file) {
// stream the file and exit the script when complete
fpassthru($file);
exit;
} else {
echo $err;
}
} else {
echo 'check that file exists and is readable';;
}
?>
i have a php file that is called from a javascript with the purpose of uploading files to my server.
Clarification that what im doing is calling this php file with ajax, so as i understand it it's not run in the traditional sence, which is why i am not using $_FILE and $_POST as the whole point of this project is to handle fileupload / collection of user data is done without a page reload.
obviously we want some sort of serverside file validation, which i have set up in an if statement.
however the code succeeds and proceeds with the upload no matter what file type i select.
can someone tell me what is wrong / or guide me in the right direction ?
<?php
session_start();
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$phone = $_SESSION['phone'];
$date = date('Y-m-d');
$mypath = $name . '-' . $phone . '-' . $date;
$ext = $_SERVER['HTTP_X_FILE_TYPE'];
$allow = array('psd', 'ai', 'eps', 'svg', 'jpg', 'png', 'docx', 'doc', 'pptx', 'ppt');
if(!in_array($ext,$allow)){
if(!file_exists($mypath)) {
mkdir($mypath,0777,TRUE);
}
$str = file_get_contents('php://input');
$title = $_SERVER['HTTP_X_FILE_NAME'];
$path = "$mypath/".$title;
file_put_contents($path,$str);
}else{
return false;
}
?>
much apreciated - Mr B
The problem with the code is (Like #Cashbee mentioned in the comments), is with if(!in_array($ext,$allow)) portion of the code. This part allows the file to be uploaded if the file extension is not in $allow array. The correct code should be as below.
<?php
session_start();
$name = $_SESSION['name'];
$email = $_SESSION['email'];
$phone = $_SESSION['phone'];
$date = date('Y-m-d');
$mypath = $name . '-' . $phone . '-' . $date;
$ext = $_SERVER['HTTP_X_FILE_TYPE'];
$allow = array('psd', 'ai', 'eps', 'svg', 'jpg', 'png', 'docx', 'doc', 'pptx', 'ppt');
if(in_array($ext,$allow)){
if(!file_exists($mypath)) {
mkdir($mypath,0777,TRUE);
}
$str = file_get_contents('php://input');
$title = $_SERVER['HTTP_X_FILE_NAME'];
$path = "$mypath/".$title;
file_put_contents($path,$str);
}else{
exit;
}
?>
Important Note : Please keep in mind that, trusting an extension based on a header set by a javascript command from browser has a high risk and shouldn't be trusted. If this is required, you must store those files in a folder either inaccessible/restricted from the web and serve them raw with the correct mime header upon request or check more than file extension on upload.
I'm trying to get all link URL of news on some div from this web
To get all link, after I view source but there is nothing.
But there are any data display
Could any that understand PHP, Array() and JS help me, please?
This is my code to get the content:
$html = file_get_contents("https://qc.yahoo.com/");
if ($result === FALSE) {
die("?");
}
echo $html;
$html = new DOMDocument();
#$html->loadHtmlFile('https://qc.yahoo.com/');
$xpath = new DOMXPath( $html );
$nodelist = $xpath->query( "//div[#id='news_moreTopStories']//a/#href" );
foreach ($nodelist as $n){
echo $n->nodeValue."\n";
}
you can get all links from the divs you specify. make sure you put the div ids in id='news_moreTopStories']. you're using xpath to query the divs. you don't need a ton of code, just this portion.
http://php.net/manual/en/class.domxpath.php
Assuming, you want to extract all Anchor Tags with their hyperlinks from the given page.
Now there are certain problems with doing file_get_contents on that URL :
Character encoding for Compression, i.e gzip
SSL Verification of the URL.
So, to overcome first problem of gzip character encoding, we'll use CURL as #gregn3 suggested in his answer. But he missed to use CURL's ability to automatically decompress gziped content.
For second problem, you can either follow this guide or disable SSL verification from CURL's curl_setopt methods.
Now the code which will extract all the links from the given page is :
<?php
$url = "https://qc.yahoo.com/";
# download resource
$c = curl_init ($url);
curl_setopt($c, CURLOPT_HTTPHEADER, ["Accept-Encoding:gzip"]);
curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($c, CURLOPT_ENCODING , "gzip");
curl_setopt($c, CURLOPT_VERBOSE, 1);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 0);
$content = curl_exec ($c);
curl_close ($c);
$links = preg_match_all ("/href=\"([^\"]+)\"/i", $content, $matches);
# output results
echo "url = " . htmlspecialchars ($url) . "<br>";
echo "links found (" . count ($matches[1]) . "):" . "<br>";
$n = 0;
foreach ($matches[1] as $link)
{
$n++;
echo "$n: " . htmlspecialchars ($link) . "<br>";
}
But if you want to do advance html parsing, then you'll need to use PHP Simple HTML Dom Parser. In PHP Simple HTML Dom you can select the div by using jQuery selectors and fetch the anchor tags. Here are it's documentation & api manual.
To find all links in HTML you could use preg_match_all().
$links = preg_match_all ("/href=\"([^\"]+)\"/i", $content, $matches);
That url https://qc.yahoo.com/ uses gzip compression , so you have to detect that and decompress it using the function gzdecode(). (It must be installed in your PHP version)
The gzip compression is indicated by the Content-Encoding: gzip HTTP header. You have to check that header, so you must use curl or a similar method to retrieve the headers.
(file_get_contents() will not give you the HTTP headers... it only downloads the gzip compressed content. You need to detect that it is compressed but for that you need to read the headers.)
Here is a complete example:
<?php
$url = "https://qc.yahoo.com/";
# download resource
$c = curl_init ($url);
curl_setopt ($c, CURLOPT_HEADER, true);
curl_setopt ($c, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec ($c);
$hsize = curl_getinfo ($c, CURLINFO_HEADER_SIZE);
curl_close ($c);
# separate headers from content
$headers = substr ($content, 0, $hsize);
$content = substr ($content, $hsize);
# check if content is compressed with gzip
$gzip = 0;
$headers = preg_split ('/\r?\n/', $headers);
foreach ($headers as $h)
{
$pieces = preg_split ("/:/", $h, 2);
$pieces2 = (count ($pieces) > 1);
$enc = $pieces2 && (preg_match ("/content-encoding/i", $pieces[0]) );
$gz = $pieces2 && (preg_match ("/gzip/i", $pieces[1]) );
if ($enc && $gz)
{
$gzip = 1;
break;
}
}
# unzip content if gzipped
if ($gzip)
{
$content = gzdecode ($content);
}
# find links
$links = preg_match_all ("/href=\"([^\"]+)\"/i", $content, $matches);
# output results
echo "url = " . htmlspecialchars ($url) . "<br>";
echo "links found (" . count ($matches[1]) . "):" . "<br>";
$n = 0;
foreach ($matches[1] as $link)
{
$n++;
echo "$n: " . htmlspecialchars ($link) . "<br>";
}
I have a following function that downloads the file whose name is passed as a parameter in the url. Here is the code:
public function actionDownloadFile($filename)
{
$file = Yii::app()->request->getBaseUrl(true) . '/upload/digitaluploads/' . $filename;
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($file) . '"');
readfile($file);
}
This function is called from view file when the user clicks on download button from the view:
<a class="digital-download" href="<?php echo Yii::app()->request->getBaseUrl('true'); ?>/site/downloadfile/filename/<?php echo urlencode($digital_download['filename']); ?>">Click here to download</a>
This works for filename that don't have spaces like it will work for file with the name like somefile.mp3 but it does not work for the files that have spaces in that. i.e it fails for the files whose name contains spaces like 'maid with the flaxen hair.mp3'.
As you can see I have even encoded the parameter in the url using urlencode. I tried using decode in action as well but all I get is the broken page.
Anyone?
use this function to avoid space and other possible problems:
function fullescape($in)
{
$out = '';
for ($i=0;$i<strlen($in);$i++)
{
$hex = dechex(ord($in[$i]));
if ($hex=='')
$out = $out.urlencode($in[$i]);
else
$out = $out .'%'.((strlen($hex)==1) ? ('0'.strtoupper($hex)):(strtoupper($hex)));
}
$out = str_replace('+','%20',$out);
$out = str_replace('_','%5F',$out);
$out = str_replace('.','%2E',$out);
$out = str_replace('-','%2D',$out);
return $out;
}
found here: http://php.net/manual/en/function.urlencode.php
try this :
str_replace(' ', '%20', 'your url here');
How to make live preview a PDF file in my local website ( no internet ) which is the PDF saved in Longblob? I use this script to download the PDF :
<?php
if(isset($_GET['id']))
{
include "../conn.php";
$query = "select * from file where id = '".$_GET['id']."'";
$result = mysql_query($query) or die (mysql_error);
$download = mysql_fetch_array($result);
$name = str_replace('%20', ' ',$download['file_name']);
$type = $download['file_type'];
$size = $download['file_size'];
$content = $download['file'];
header("Content-disposition: attachment; filename=\"".$name."\"");
header("Content-length: ".$size."");
header("Content-type: $type");
echo $content;
exit;
}
?>
I have use almost all open source PDF Viewer plugins like from http://viewerjs.org , but failed to display the wanted PDF file. Need your help guys..
you shoud have a pdf plugin and you should use code looks like :
header('Content-type: application/pdf');
header("Cache-Control: no-cache");
header("Pragma: no-cache");
header("Content-Disposition: inline;filename='document.pdf'");
header("Content-length: ".strlen($binary_contents_from_database));