I have a music player that links to a song using the following syntax:
<li>title</li>
Is there any way that I could have that executed server side and then be displayed like (see below) for the user?
While searching, I ran across this...I like the idea behind having an external file that has the data...like:
<?php
// get-file.php
// call with: http://yoururl.com/path/get-file.php?id=1
$id = (isset($_GET["id"])) ? strval($_GET["id"]) : "1";
// lookup
$url[1] = 'link.mp3';
$url[2] = 'link2.mp3';
header("Location: $url[$id]");
exit;
?>
then using: http://yoururl.com/path/get-file.php?id=1 as the link...the only problem is that when you type http://yoururl.com/path/get-file.php?id=1 the user goes straight to the file...is there any way to disable that ability...maybe some code on get-file.php itself?
Ok, so I did a combination of things that I am satisfied with...although not completely secure, it definitely helped me obscure it quite a bit.
First of all, I am using the AudioJS player to play music - which can be found: http://kolber.github.com/audiojs/
Basically what I did was:
Instead of using "data-src" as the path to my songs I called it "key", that way people wouldn't necessarily think it was a path.
Instead of using "my-song-title" as the name of the songs, I changed it to a number like 7364920, that way people couldn't look for that in the source and find the url that way.
I added + "mp3" to the javascript code after all of the "key" variables, that way I would not have to declare it in obfusticated link.
I used a relative path like "./8273019283/" instead of "your-domain.com/8273019283/", that way it would be harder to tell that I was displaying a url.
Added an iTunes link to the href, that way people might get confused as to how I was pulling the file.
So, now my inline javascript looks like:
<script type="text/javascript">
$(function() {
// Play entire album
var a = audiojs.createAll({
trackEnded: function() {
var next = $("ul li.playing").next();
if (!next.length) next = $("ul li").first();
next.addClass("playing").siblings().removeClass("playing");
audio.load($("a", next).attr("key") + "mp3");
audio.play();
}
});
// Load the first song
var audio = a[0];
first = $("ul a").attr("key") + "mp3";
$("ul li").first().addClass("playing");
audio.load(first);
// Load when clicked
$("ul li").click(function(e) {
e.preventDefault();
$(this).addClass("playing").siblings().removeClass("playing");
audio.load($('a', this).attr('key') + "mp3");
audio.play();
});
});
</script>
My link looks like:
Falling
When you load it up in the browser and you view the source you'll see:
Falling
Then when you use Web Inspector or Firebug you'll see:
Falling - *which doesn't completely give the url away
Basically what I did was make the link look like it's an api-key of some-kind. The cool thing is that you can't just copy the link straight from view source or straight from Web Inspector/Firebug. It's not fool-proof, and can definitely be broken, but the user would have to know what they're doing. It keeps most people away, yet still allows the player to get the url it needs to play the song :)
*also, I got the php obfusticate script from somewhere on Stack Exchange, just not sure where.
Instead of doing a header redirect, add proper headers and include the audio file in your PHP code. Then, in your .htaccess file, you can disallow access to the directory where your audio files live.
If you are using amazon s3 service you can use signed url for your files. It will be more safe as you have to be signed user and also url can be expired. Read this.
No. This is not possible since it is the browser that interprets the HTML to make the page work properly. So if the client (browser) does not know where the mp3 is coming from then it will not be there to use.
On the other hand if you want to have the music switch songs by clicking a link then i suggest you look into some tools like http://jplayer.org/
EDIT: The only way to probably prevent direct access to the file itself would be to read the file in instead of linking to it from the script. For instance on my image hosting site http://www.tinyuploads.com/images/CVN5Qm.jpg and if you were to look at the actual file path on my server, the file CVN5Qm.jpg is out of view from the public_html folder. There is no way to directly access the file. I use databases to take the image id, look up where it is stored, and then readfile() it into the script and display the proper headers to output the image.
Hope this helps
I use http_referer and I can controll the procedence of the link
<?php
// key.php
// call with: http://yoururl.com/path/key.php?id=1
$page_refer=$_SERVER['HTTP_REFERER'];
if ($page_refer=="http://www.yourdomine.com/path/page.html")
{
$id = (isset($_GET["id"])) ? strval($_GET["id"]) : "1";
// lookup
$url[1] = 'link1.mp3';
$url[2] = 'link2.mp3';
header("Location: $url[$id]");
exit;
}
else
{
exit;
}
?>
Related
I have a webpage that needs to check to see if an app exists using a deep link, but it doesn't seem to work like it should. I have tried the following things.
Using a redirect in PHP (Doesn't work)
header('Location: exampleapp://param=test');
Using a redirect using JavaScript (Doesn't work)
var appurl = 'exampleapp://param=test';
var appstore = 'https://itunes.apple.com/us/app/...';
var timeout;
function preventPopup() {
clearTimeout(timeout);
timeout = null;
window.removeEventListener('pagehide', preventPopup);
}
function startApp() {
window.location = appurl;
timeout = setTimeout(function(){
if(confirm('You do not seem to have the App installed, do you want to go download it now?')){
document.location = appstore;
}
}, 100);
window.addEventListener('pagehide', preventPopup);
}
// app start is then called in the onload
Same as above but replace the the line window.location = appurl; with document.getElementById('deeplink').click(); and adding a link in the html's webpage. (Works) <a id="deeplink" href="exampleapp://param=test">Deep Link</a>
Is there a reason why you can't redirect using a header in PHP?
The PHP version doesn't work, because of the way HTTP works. The HTTP protocol doesn't specify that it should work to redirect to a different protocol from within the "Location:" header. There is nothing specific to PHP here, it's a HTTP issue.
The Javascript version doesn't work because you wanted to set the windows location. And the window cannot show the contents of "exampleapp://..." . You want the link to open like when the user clicks on it. Instead of using window.location you may use document.location.href. That should work.
Another problem:
in your code you write exampleapp:// in 1) and 2). And in 3) you write testapp:// - make sure you use the same URL in all three cases, so that you can be sure that the URL can work eventually..
The answer is to use Apples implementation called 'Smart Banners'
<meta name="apple-itunes-app" content="app-id=myAppStoreID, affiliate-data=myAffiliateData, app-argument=myURL">
You can include three comma-separated parameters in the content
attribute:
app-id: (Required.) Your app's unique identifier. To find your app ID
from the iTunes Link Maker, type the name of your app in the Search
field, and select the appropriate country and media type. In the
results, find your app and select iPhone App Link in the column on the
right. Your app ID is the nine-digit number in between id and ?mt.
affiliate-data: (Optional.) Your iTunes affiliate string, if you are
an iTunes affiliate. If you are not, find out more about becoming an
iTunes affiliate at http://www.apple.com/itunes/affiliates/.
app-argument: (Optional.) A URL that provides context to your native
app. If you include this, and the user has your app installed, she can
jump from your website to the corresponding position in your iOS app.
Typically, it is beneficial to retain navigational context because: If
the user is deep within the navigational hierarchy of your website,
you can pass the document’s entire URL, and then parse it in your app
to reroute her to the correct location in your app. If the user
performs a search on your website, you can pass the query string so
that she can seamlessly continue the search in your app without having
to retype her query. If the user is in the midst of creating content,
you can pass the session ID to download the web session state in your
app so she can nondestructively resume her work. You can generate the
app-argument of each page dynamically with a server-side script. You
can format it however you'd like, as long as it is a valid URL.
https://developer.apple.com/library/ios/documentation/AppleApplications/Reference/SafariWebContent/PromotingAppswithAppBanners/PromotingAppswithAppBanners.html
as I already mentioned in the title, I'm looking for a JS-function for getting the same result like I get with this PHP code:
dirname(dirname(__FILE__))
Thanks in advance!
I don't think it is possible because php dirname operates on apache server on local machine. It has access to the filesystem. But javascript operates on browser layer which can't operate with filesystem. I think so you should use ajax and proccess result how you need it. I think so its best solution for you.
I needed a solution to write code like this:
$("#div").load(ROOT_URL + "my/path/to/script.php");
Solution: a PHP script generates one JS-file of all needed JS-files and adds the ROOT_URL to the top of the generated file:
$js = 'ROOT_URL = "' . ROOT_URL . '"; ' . $js;
file_put_contents("file.js", $js);
Now I'm able to use the ROOT_URL (set in a PHP config-file) in JS-code as well. I hope I could help.
You can have PHP output the script. Yes, that's right, you probably can't make php process js files (unless you are in full control of the server). But it doesn't matter. Just make sure that the MIME type is correct, both in the headers PHP returns and the script tag. That way, you can have PHP insert the any values you want in the script, including it's own path.
In script.php:
header("Content-type: text/javascript");
echo 'var myvar = '.$something;
//where $something can be $_SERVER['REQUEST_URI'], __FILE__ or whatever you need.
//You could even use information from session variables, or query the database.
//In fact, this way you can have GET parameters in your javascript.
//Make sure you are not creating a vulnerability with the exposed information.
//Then put the rest of the script as usual. You could even include it*.
*: include
In HTML:
<script type="text/javascript" src="script.php"></script>
Yes, I know I'm repeating the MIME type, do it this way to maximize browser compatibility.
There's no analogue of __FILE__ in browser Javascript; the code does not have direct access to the URL from which it was loaded. But with certain assumptions you can figure it out, as in the answer here.
Once you have the URL of the script (I assume in a variable called scriptURL below) you can set about finding the grandparent URL. This can get tricky with URLs, so it's probably safest to let the URL-savvy bits of Javascript parse the URL for you and get just the pathname component before you start with the string-munging:
var a = document.createElement('a')
a.href = scriptURL
var scriptPath = a.pathname
Then it's unfortunately down to string manipulation; here's one somewhat clunky solution:
var components = scriptPath.split(/\//)
while (components.length > 0 && !components[components.length-1])
components.length -= 1;
var twoDirsUp = components.slice(0,components.length-2).join('/')
And then you can convert the result back into a full URL using the anchor element trick in reverse:
a.pathname = twoDirsUp;
var grandParentUrl = a.href
Why not load what you want from absolute URL?
If you have inse your block of codes: /my/script/to/load.js browser will load the correct file if you are in yoursite.com or whatever like yoursite.com/a/b/c/d/e/f
A little off topic, but if you just want to get the similar of dirname($_SERVER['REQUEST_URI']) for javascript, you can do
window.location.href.substr(0, window.location.href.length - window.location.href.split('/').pop().length)
I use something like that to free from the paths in javascript
var __DIR__ = window.location.pathname.match('(.*\/).*')[1] + 'NameOfThisFolder';
first
window.location.pathname.match('(.*\/).*')[1]
return the current path without the file name or other stuff.
rootFolder/folder1/folder2/
then I add the name of this folder ('NameOfThisFolder').
In this way, I can make for instance ajax request in current page from a page that was called in turn from an ajax request without worry about the path
I have Apache set up through xampp to test a webpage to load some .php file to read a .csv file as data source to output a bar graph chart. And I encounter this error on Chrome.
Unsafe JavaScript attempt to access frame with URL file:///C:/xampp/htdocs/search/php/loader/csvFileUploader.php from frame with URL file:///C:/xampp/htdocs/search/stackedBarChart.html. Domains, protocols and ports must match.
upclick-min.js:99
i.onload_callback.i.onload_callback upclick-min.js:99
onload
I don't think this is an iframe problem like many other posts have suggested. I tested this also through firefox, it went beyond reading the php but doesn't load the .csv file from local directory.
Any suggestions?
<script>
var uploaderCSV = document.getElementById('uploaderCSV');
upclick({
element : uploaderCSV,
action : 'php/loader/csvFileUploader.php',
onstart : function(filename) {
console.log(" -- Start upload: <" + filename + "> Here");
},
oncomplete : function(response_data) {
alert(response_data);
console.log(" -- CSV file to load: ", response_data);
var n = response_data.split("|");
if (n.length > 1) {
console.log(" >> csv file loaded at[ ", n[1], " ]");
loadDayLightFactor("php/loadCSV.php", "../" + n[1]);
}
}
});
</script>
and here's the php file
<?php
// using upload at click from http://code.google.com/p/upload-at-click/
// FileData is the name for the input file
$file_result = "";
$file = $_FILES['Filedata'];
$allowedExtensions = array("csv", "txt");
$extension = end(explode(".", $file["name"]));
echo "123".$file;
?>
Your problem seems to be the URL you are trying to reach:
file:///C:/xampp/htdocs/search
This is not the way to develop on local environment.
try to access it through
http://localhost/search
I'm sure it will work better. detailed explanation below..
This is happening because of a security standard called Cross-Domain-Policy
You can not make a call (via JavaScript) to files with a URL that is different from your current URL Address.
For example:
My website's URL is foobar.com, I'm trying to send an AJAX request to barbaz.com.
I can't!
because it's not my domain. I can try sending requests to barbaz.foobar.com (using some JavaScript code).
Another scenario that will show you why this is a "must have" security standard:
Lets say that I'm logged into my bank's website using a cookie. the cookie is persistent.
I'm entering a random website X that send AJAX request to all known bank websites. If I'm still logged into my bank's website, X website can "talk" to the bank's website using my user, and do things that I'm not aware of.
This is a small example why this is very important.
I hope this was helpful.
I would like to load an external file using javascript. I'm planning to add ad codes in the external file and include it using javascript wherever necessary. This will help me to change ad codes easily when the need arises.
Also I believe various third party solutions such as Google Admanager are complex and unnecessary. So I need your suggestion for the same.
Note : The external file may contain PHP / Javascript source.
What I thought was to add something like this ...
document.write("<script type='text/javascript' src='ad1.js'></script>");
What's your opinion ?
Correct me if I'm wrong, but it sounds like you want to display ad codes separate from the content of the page (such as in iframes). Most ad providers don't like this, since the ads displayed won't be relevant to site content.
Another way to do it however (that makes everyone happy) is to use php's include statement and include the external file. This will dump the contents of the page into the current page, so make sure you don't have multiple <html> elements or inaccurate paths.
I wouldn't use document.write, is that would overwrite the content already on the page, thus making your solution quite static. Try this instead:
function addScript(src) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
document.head.appendChild(script);
}
You'll want to make sure that the page has loaded enough that the document.head is defined. You could use an event listener for this.
I have a small problem, I want to load data from a PHP file and put them on a DIV.
Here's the Jquery code
// Store the username in a variable
var jq_username = $("#txt_checkuser").val();
// Prepare the link variable
var link = 'user.php?action=check&username=' + jq_username;
$('div #checkuser_hint').load(link);
So it works! but instead of loading the result (compiled PHP) it loads the PHP code.
If I write the long URL "http://localhost/project..." it doesn't load anything!
Any idea how to do that?
I think you might be accessing your javascript file as a file on your local filesystem, a request to the same directory would go through the filesystem and not through your webserver, processing the PHP into the desired output. This also explains why http://localhost/project for the AJAX call doesn't work: Javascript might be enforcing the same-origin policy on you.
Verify that you're actually accessing this javascript file through http://localhost/ (as opposed to something like file://C:/My PHP Files/ ).
Does the page return anything when you use your browser?
Are you sure it should not be 'div#checkuser_hint' instead of 'div #checkuser_hint' ?
And this looks like the correct way according to the documentation.
var link = 'user.php';
$('div#checkuser_hint').load(link, {'action':'check', 'username':jq_username});
Are you able to access the script manually on your own? (try accessing it via your browser: htp://localhost/...) It may be the case that you're missing your opening <?php and/or closing ?> in the script-file itself.