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
Related
I have a php file on my server that takes in two inputs through the URL and then comes back with a result. When a page is loaded, I'd like to have the result of that calculation already loaded. For example:
$var = load("http://mysite.com/myfile.php?&var1=var1&var2=var2");
I know that load isn't a real function for this, but is there something simple that suits what I'm looking for? thanks
Use file_get_contents
$foo = file_get_contents('http://mysite.com/myfile.php?&var1=var1&var2=var2');
Or, a better solution if the file is located on your server:
include('myfile.php');
and either set the $_GET variables in the included script itself, or prior to including it.
If they are running on the same server, consider calling the script directly?
$_GET["var1"] = "var1";
$_GET["var2"] = "var2";
include "myfile.php";
You could use file_get_contents, but it may be a more practical solution to simply include the file and call the function directly in the file, rather than trying to manually load the file.
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;
}
?>
I have a little problem here, and no tutorials have been of help, since I couldn't find one that was directed at this specific problem.
I have 2 hosting accounts, one on a server that supports PHP. And the other on a different server that does not support PHP.
SERVER A = PHP Support, and
SERVER B = NO PHP Support.
On server a I have a php script that generates a random image. And On server b, i have a html file that includes a javascript that calls that php function on server a. But no matter how I do it, it never works.
I have the following code to retrieve the result from the php script:
<script language="javascript" src="http://www.mysite.com/folder/file.php"></script>
I know I'm probably missing something, but I've been looking for weeks! But haven't found any information that could explain how this is done. Please help!
Thank you :)
UPDATE
The PHP script is:
$theimgs= array ("images/logo.png", "images/logo.png", "images/logo.png", "images/logo.png", "images/logo.png");
function doitnow ( $imgs) {
$total = count($imgs);
$call = rand(0,$total-2);
return $imgs[$call];
}
echo '<img src="'.doitnow($theimgs).'" alt="something" />';
<img src="http://mysite.com/folder/file.php" alt="" /> ?
It's not clear, why you include a PHP file as JavaScript. But try following:
Modify your PHP Script so that it returns a image file directly. I'll call that script image.php. For further information, look for the PHP function: header('Content-type: image/jpeg')
In your JavaScript file use image.php as you would any normal image.
Include the JavaScript on server B as a *.js file.
UPDATE:
It's still not clear, why you need JavaScript.
Try as image.php:
$theimgs= array ("images/logo.png", "images/logo.png", "images/logo.png", "images/logo.png", "images/logo.png");
function doitnow ( $imgs) {
$total = count($imgs);
$call = rand(0,$total-2);
return $imgs[$call];
}
$host = $_SERVER['HTTP_HOST'];
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$extra = 'mypage.php';
header("Location: http://$host$uri/" . doitnow($theimgs));
And on server b:
<img src="www.example.org/image.php"/>
You didn't specify, but I assume the two servers have different domain/hostnames. You may be running into a browser security model problem (same origin policy).
If that's the case, you need to use JSONP.
You may be using outdated sources to learn, since the language attribute is deprecated and you should use type="text/javascript" instead. It's also not clear what kind of output does the .php script produce. If it's image data, why are you trying to load it as a script and not an image (i.e., with the <img> tag)?
Update: The script is returning HTML, which means it should be loaded using Ajax, but you can't do that if it's on a different domain due to the same origin policy. The reason nothing is working now is that scripts loaded using the <script> tag aren't interpreted as HTML. To pass data between servers, you should try JSONP instead.
It seems that server A generates an HTML link to a random image (not an image). The URL is relative to wherever you insert it:
<img src="images/logo.png" alt="something" />
That means that you have an images subdirectory everywhere you are using the picture. If not, please adjust the URL accordingly. Forget about JavaScript, PHP or AJAX: this is just good old HTML.
Update
The PHP Script displays pics randomly.
Pics are hosted on server A, and they
are indeed accessible and readable
from the internet. The PHP Script has
been tested by itself, and works.
If these statements are true, Māris Kiseļovs' answer should work. So either your description of the problem is inaccurate or you didn't understand the answer...
i am using ajax to load pages into a div
the page is loading fine
but i cant run the php and javascript
in that loaded page
in server i am loading the page like this
file_get_contents('../' . $PAGE_URL);
in the browser i am setting the content of the div
using
eval("var r = " + response.responseText);
and setting the innerHTML for that div
with the retrieve information
but when i get the new inner page
no php or java script is working
is that suppose to be like that ?
Well the php is not going to work I think because the way you are handling it, it is just text. I would suggest using something like include('../' . $PAGE_URL); and that should parse the php.
The javascript problem probably has to do with the fact that you are loading <html> <body> <head> tags in a div I'm not sure what happens when you do that, but it shouldn't work properly. Try using some type of <frame> tag.
In order for your javascript to be executed properly, you have to wait until the browser has finished to load the page.
This event is named onload(). Your code should be executed on this event.
<?php
$file = false;
if(isset($_GET['load'] && is_string($_GET['load'])) {
$tmp = stripclashes($_GET['load']);
$tmp = str_replace(".","",$tmp);
$file = $tmp . '.php';
}
if($file != false && file_exists($file) && is_readable($file)) {
require_once $file;
}
?>
called via file.php?load=test
That process the PHP file, and as long as you spit out HTML from the file simply
target = document.getElementById('page');
target.innerHTML = response.responseText;
Now, i'm fairly certain parts of that are insecure, you could have a whitelist of allowable requires. It should ideally be looking in a specific directory for the files also. I'm honestly not all too sure about directly dumping the responseText back into a DIV either, security wise as it's ripe for XSS. But it's the end of the day and I haven't looked up anything on that one. Be aware, without any kind of checking on this, you could have a user being directed to a third party site using file_get_contents, which would be a Very Bad Thing. You could eval in PHP a file_get_contents request, which... is well, Very Very Bad. For example try
<?php
echo file_get_contents("http://www.google.com");
?>
But I fear I must ask here, why are you doing it this way? This seems a very roundabout way to achieve a Hyperlink.
Is this AJAX for AJAXs sake?
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.