js: how to hide/crypt the src of the image? - javascript

I am looking for a way to hide/crypt the image src.
It is a quiz game and image name contains the solution
ex: <img src="solution.jpg">
Solution would be to encode64 the image, but this is quite heavy solution.
Suggestion does not have be to 100%secure, just avoid showing clearly the "solution.jpg" src

Best solution is to store the file path in database and serve it on request. An example using php would be
HTML
<img src="get-image.php?id=2653" />
PHP
// get image path from database
...
// output
header("Content-type: image/jpeg") // change format accordingly
header('Content-Length: ' . filesize($filepath));
ob_clean();
flush();
readfile($filepath);
die();

I know it's not php question but you can create php script that will read the file based on md5 hash. On the beginning of your main script you save hash in session:
session_start()
$time = array_sum(explode(' ', microtime()));
$_SESSION['hash'] = md5($time);
and in php script that you use for image
<img src="script.php?hash=<MD5 HASH>"/>
you check if $_GET['hash'] is equal to value from session:
session_start();
if (isset($_GET['hash']) && isset($_SESSION['hash']) &&
$_GET['hash'] == $_SESSION['hash']) {
header("Content-type: image/jpeg");
echo file_get_contents('your hidden image.jpg');
}

Related

How to show only image on the url not other content even html?

I wan't to know "How to show only image on the url not other content even html?". Like see this url link of Image. This url only shows image not any other content on webpage and also see the url of website it's dynamic url not a specific image url.
So, how to achieve that?
You simply make the request to the URL of the image.
For example, if your image is called test1.png and you have it in a directory called images, you would make the URL like this:
https://your.domain/images/test1.png
If you want to hide the full path to the images and serve them through a page (so you have some control over the request for some reason), you can do something more like the following. Let's call the PHP page img.php. And the request could be like
https://your.domain/img.php/test1
<?php
$request = './default.png';
if (isset($_SERVER['PATH_INFO'])){
$request = './images'.$_SERVER['PATH_INFO'].'.png';
if (! file_exists($request)){
$request = './default.png';
}
}
// we now know we have a valid request and the file was found
header('Content-type: image/png');
header('Content-Length: '.filesize($request));
echo file_get_contents($request);
exit;
?>
With this approach you could have any number of images in the /images/ directory and serve them if they match the request.
The website in your sample maybe using the same $_SERVER['PATH_INFO'] info approach but would be dynamically creating the image using the passed variables and explode('/',$_SERVER['PATH_INFO']) along with imagecreate()
A very quick hack version would be something like the following. The request would be like this:
https://your.domain/test.php/100x50/919/222
And the very quick code, with almost no error checking could be:
<?php
function hexToColor($hx){
$rgb = array(0,0,0);
if (strlen($hx) == 3){
$rgb[0] = hexdec($hx[0].$hx[0]);
$rgb[1] = hexdec($hx[1].$hx[1]);
$rgb[2] = hexdec($hx[2].$hx[2]);
} else {
$rgb[0] = hexdec($hx[0].$hx[1]);
$rgb[1] = hexdec($hx[2].$hx[3]);
$rgb[2] = hexdec($hx[4].$hx[5]);
}
return $rgb;
}
// default values
$sizeW = 100;
$sizeH = 100;
$bg = array(0,0,0);
$fg = array(255,255,255);
if (isset($_SERVER['PATH_INFO'])){
$opts = explode('/',substr($_SERVER['PATH_INFO'],1));
$bgSet = false;
foreach($opts as $k => $v){
// check for a width x height request
if (strpos($v,'x')){
$tmp = explode('x',$v);
$sizeW = $tmp[0];
$sizeH = $tmp[1];
} elseif ($bgSet){
// must be a foreground request
$fg = hexToColor($v);
} else {
$bg = hexToColor($v);
$bgSet = true;
}
}
}
header("Content-Type: image/png");
$im = #imagecreate($sizeW,$sizeH)
or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im,$bg[0],$bg[1],$bg[2]);
$text_color = imagecolorallocate($im,$fg[0],$fg[1],$fg[2]);
imagestring($im,1,5,5,$sizeW.' x '.$sizeH,$text_color);
imagepng($im);
imagedestroy($im);
exit;
?>
But I would strongly recommend a heap of error checking before using that code!
As I understand you want to dynamically update the picture.
You can see that on their main website they created a form for the entered values:
After that, on the picture URL there are all the values you need to display this image:
https://dummyimage.com/600x400/8a1a8a/232dba&text=xzcxzcnbngh
which is this image:
what you can't see is their server side, which takes the parameters 600x400/8a1a8a/232dba&text=xzcxzcnbngh, creates a picture using their server and returning it to you.
I'll suggest you to create a server side that will return a picture and text based on the given parameters.
based on your server you will need to find out how to create the picture and return it.
As you can see here, I just modified the "src" value of the and it changed the text on the photo.
which means that their server receives the request and send back the image.
If you want a simple solution you could just send back those parameters to your page scripts, and create this image element using JavaScript.
That way, your html code will be clean without even the img element tag.
create your img in JS and send put it on the html body.
Image placeholder that’s updated by scripting
HTML code:
<img id="abc" src="">
Javascript code:
var abcImage = document.getElementById('abc');
abcImage.src = 'https://dummyimage.com/600x400/000/fff';

Which one is the best way to download video/audio from URL with specific filename?

I would ike to find a solution for downloading a video/audio from a URL when I click on a HTML button.
One special point: The URL its external (so I do not have any chance to touch it) but I would like to specify the filename before the downloading starts.
I tried it over PHP, but im not sure if this method is the best/simpelst one. Because I have to define few headers, which are currently not working for a (mp4) file.
<?php
if (isset($_GET['title'], $_GET['link'])) {
$FileName = $_GET['title'];
$Link = $_GET['link'];
$ContentType = get_headers($Link, 1)["Content-Type"];
header('Content-disposition: attachment; filename="' . $FileName . '"');
header('Content-type: ' . $ContentType . '');
readfile($Link);
};
?>
Questions:
What do I wrong? I do always receive a 0kb file.
is there a more simple way to do it over JS or jquery?
What if its an Audio only URL that I want to download. Can I use same headers?
Looks like you've forgotten to include the protocol (ie https://) on those links. You'll also need to URL encode the parameter in your HTML so you don't lose any query parameters.
For example, to use https://example.com/example?test123, you'll want
href="download.php?link=https%3A%2F%2Fexample.com%2Fexample%3Ftest123"
Producing that encoded parameter can be done via...
urlencode() in PHP
<?php $link = 'https://example.com/example?test123&HERE-is-the-real-Content'; ?>
Download
encodeURIComponent() in JavaScript
let link = 'https://example.com/example?test123&HERE-is-the-real-Content'
let a = document.createElement('a')
a.href = `download.php?title=Whatever&link=${encodeURIComponent(link)}`
a.textContent = 'Download'
or, if you're building HTML strings (not recommended)...
const input_URL = 'https://...'
html += `Download`
Note, I'm using template literals in these JS examples.
You should also make sure the remote URL is valid. For example
$headers = get_headers($Link, 1);
if (strpos($headers[0], '200 OK') === false) {
http_response_code(404);
exit;
}

PHP is not writing to file

I'm trying to pass a variable ( n ) from a JS script to PHP thru the URL and get it to write said variable to a file. Unfortunately I can see the PHP script being called over the network, with the appropriate URL and with 200 status, but it doesn't seem to be executing. The file it should be writing to never changes. The disk is not full, the file is not in use by another process and the file it is writing to has completely open permissions as a testing measure. Hopefully this is a simple fix, thanks in advance.
<?php
$my_file='count.txt';
$count= $_GET['n'];
$handle = fopen($my_file, 'w');
fwrite($handle, $count);
fclose($handle);
?>
Examples of requests being sent
Your code is working fine and its writing whatever value for n is passed. however it keeps on overwriting previous value for every new request.
$handle = fopen($my_file, 'w');
In 'w' mode it create new file for read and write while placing pointer at the beginning.
Use 'w+' mode this places the pointer at the end of file.
$handle = fopen($my_file, 'w+');
For more details on files you can check below url for different modes and other functions
http://php.net/manual/en/function.fopen.php

filesize is changing during download

i have a pdf file that if downloaded through the viewer it downloads at the correct file size but when i use this code for say download selected the file size of the pdf changes and renders it useless when you open with adobe/nitro/etc.
<?php
#apache_setenv('no-gzip', 1);
#ini_set('zlib.output_compression', 'Off');
if (isset($_GET['url'])) {
$fullPath = $_GET['url'];
if($fullPath) {
#$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-Disposition: attachment;
filename=\"".$path_parts["basename"]."\""); // use 'attachment' to force a download
header("Content-type: application/pdf"); // add here more headers for diff. extensions
break;
default;
header("Location: ".$fullPath);
exit;
}
if($fsize) {//checking if file size exist
header("Content-length: $fsize");
}
fopen($fsize, "r");
exit;
}
}
?>
i noticed the file size is 24kb on the server. i go to url and view it then click the download from pdf viewer the file downloads just fine and verified the filesize in my download folder at 24kb. however when i use this code above as my download.php it downloads but comes back as 2kb.
can someone help me figure out why its changing the file size please?
I don't see any code where you are actually sending the file.Make sure you actually send the file. You have used fopen() but you are not using fread() that's why files is getting opened but not getting being read may be that's why it's showing some default output which amounts to 2kb . You can use the much simpler readfile() instead
For that replace this line
fopen($fsize, "r");
with this one
readfile('path/to/' . $path_parts["basename"]);
Just in case you are handling huge files like several MBs then fopen will suite you better as it would be more memory efficient.Also note the b flag in fopen() parameter it refers to binary mode so whenever you are sending a binary file like pdf,images etc you should always use this flag
set_time_limit(0);
$file = #fopen('path/to/' . $path_parts["basename"],"rb");
while(!feof('path/to/' . $path_parts["basename"]))
{
print(#fread('path/to/' . $path_parts["basename"], 1024*2));
ob_flush();
flush();
}
the problem was the / in the url it was starting with. once i added a trim to the url it worked. tbh now that i started looking into this i dont think it really ever work just appeared it did.
$trmfullPath = $_GET['url'];
$fullPath = trim($trmfullPath, "/");
this seemed to fix it. also dont get any errors in my php error log now.

Render .mht files dynamically without load/iframe/embed

I have .mht files that are stored on a folder on my server. This folder has a rule in .htaccess that only localhost is allowed inside.
I need to render files on my website depending on user actions.
<iframe> and <embed> and jquery .load() won't work as the request doesn't come from localhost.
I'm trying to get the data of the file via a phpscript and an ajax call :
PHP:
$file = htmlentities(filter_var($_GET['url'], FILTER_SANITIZE_STRING), ENT_QUOTES);
$content = file_get_contents(".".$file);
$return = array("content" => $content);
echo json_encode($return);
jQuery:
$.getJSON('queries.php',{q: 'getFile', url: file},
function(data){
$('#file_panel').html(data.content);
}
);
But it only displays the content of the file, it doesn't render it. Any suggestion to get it rendered?
It will not be possible unless you use an <iframe>. Browsers won't parse HTML & MHT within the same page.
Try this,
PHP File
$file = htmlentities(filter_var($_GET['url'], FILTER_SANITIZE_STRING), ENT_QUOTES);
echo file_get_contents(".".$file);
JS
$("#frame").attr("src", "queries.php?url="+file);

Categories