been a lurker on Stack Overflow for a while, love the site.
Now its my turn. From the code below, i am making the background image random each time the page loads.
Would anyone be so kind as to help me make this more efficient so that i don't have to manually enter my filenames ? Im looking for some kind of wildcard function that can look through my given folder and load footer*.png or even *.png as this folder will only contain footer patterns.
var images = ['footer.png', 'footer2.png', 'footer3.png'];
$('#footer').css({'background-image': 'url(images/footers/' + images[Math.floor(Math.random() * images.length)] + ')'});
With PHP, you can do it:
<?php
$directory = "./images/";
$images = glob($directory . "*.png");
foreach($images as $image)
{
echo $image . "\n";
}
?>
Just don't make $directory an arbitrary argument, as the Russian hackers will jack your webapp.
To use it, make an AJAX request to the PHP file and parse the output, separating each file by the \n character.
So with jQuery,
var images = [];
jQuery.load('images.php', function(data)
{
images = data.split('\n');
});
Related
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';
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;
}
Information
For testing purposes I am building a system where a javascript file contains an array called "contains".
The javascript will then make the browser redirect to another page where the php-code is located, and that code should add the keyword as a new array-element
And before anyone of you try to say how simple this is, let me reiterate that I am injecting the JS code on another page using Tampermonkey, and I have no chance to modify their code
The code should then be converted to JS again and be written to a file which is called "copyright.js"
Code
At the moment the "copyright.js" file looks like this
var contains = ["original"]
The following code returns a positive result
$str = 'var contains = ["original"]';
$str = str_replace("var ", '$', $str);
eval($str.";");
But when I try to fetch the variable from the file i get an error
$file = fopen('copyright.js', 'r') or die('Unable to open File');
$str = fread($file, filesize('copyright.js'));
fclose($file);
$str = str_replace("var ", '$', $str);
eval($str.";");
If there is a better solution to this, please don't hesitate to tell me :)
I'm making a PHP script for a JavaScipt site I've made.
The goal is to save the contents of a string as an HTML file when I click a button.
I'm using jQuery to make a Post request.
I'm using an Ubuntu OS with an Apache 2 server. The folder I'm writing to has permissions 777 (for testing only, will repeal this).
A requirement is the PHP must live in another file.
The issue is whenever I make the request, the file saves blank.
A requirement is each filename must be a timestamp. The file has the correct file name, but not contents.
So far, here is my code:
<?php
$fileName = $_GET['fileNameData'];
$htmlImport = $_GET['htmlToSaveData'];
$htmlToSave = (string)$htmlImport;
$myFile = fopen($fileName, "w") or die('You do not have write permissions');
//fwrite($myFile, $htmlToSave);
file_put_contents($myFile, $htmlToSave);
fclose($myFile);
?>
I've tried the frwite function that I've commented out, same effect.
I have tested this in terminal by passing in arguments ($argv[1] and $argv[2]). That works fine.
The JS I've made to run my site looks like:
var newURL = 'saveHTML.php/?fileNameData=' + fileName + '&htmlToSaveData=' + htmlToSave
$.post(newURL)
.done(function(){
alert('Your file saved as ...' + htmlToSave)
})
I've also tried this code, with the same result:
$.post('saveHTML.php/', {
fileNameData : fileName,
htmlToSaveData : htmlToSave
})
Both the fileName and htmlToSave are strings, although htmlToSave is rather long and is actually html text that I've converted to a string.
Does anyone have ideas about what's going on here? I'm not a PHP developer at all.
I'm using a callback so I can be sure I've collected all my html before I pass the string to PHP.
I've read and tested the recommendations on this question here and this has been fruitless.
EDIT Don't be alarmed about the code, I realise it's a security issue but this is a learning project and this will not be in production.
I can see right off the bat that you have
$myFile = fopen($fileName, "w") or die('You do not have write permissions');
//fwrite($myFile, $htmlToSave);
file_put_contents($myFile, $htmlToSave);
fclose($myFile);
file_put_contents takes a file name, not a handle. So you would only need
file_put_contents($fileName, $htmlToSave);
Edit: I also feel like I should point out that you should not allow your users to name your files. They could potentially do some nasty stuff to your machine.
I wrote a jquery script to play short videoclips with random audio fragments + subtitles attached. See here for a 'working' example. Most of the code is triggered when the video ends, and that part works well. However I have an occasional problem with the on document.ready function. It works about 7 out of 8 times, but sometimes a 404 is given for the .vtt subtitle file and the first video plays without subtitle (I checked the link and the .vtt file is actually created). (you can recreate the bug by refreshing the page a few times) I was wondering if someone has a suggestion on how to fix or debug this... Thank you!
$(document).ready(function() {
createsubtitle(); //creates random subtitle string
timestamp0 = $.now();// two timestamps to make unique files (to be deleted afterwards)
timestamp1 = $.now();
window.timestamp0 = timestamp0
window.timestamp1 = timestamp1
$.ajax({type: "POST",url:"save1.php",data: {text:subtitle, time:timestamp1},success: function() {console.log("message sent!")}}); // first .vtt file is made using php (see code below)
createsubtitle(); // new random subtitle
$.ajax({type: "POST",url:"save0.php",data: {text:subtitle, time:timestamp0},success: function() {console.log("message sent!")}}); // second php (the script alternates between two .vtt files)
$("#subtitles").attr("src", "subtitle/sub1" + timestamp1 + ".vtt"); // one .vtt file is added as src to track element #subtitles
$('#rearrangements').get(0).play(); // video is played
});
php code:
#!/usr/bin/php
<?php
$subtitle = $_POST['text'];
$timestamp = $_POST['time'];
$filename = 'subtitle/sub1'.$timestamp.'.vtt';
$myfile = fopen($filename, "w") or die("Unable to open file!");
$txt = $subtitle;
fwrite($myfile, $txt);
fclose($myfile);
?>