I'm having an issue creating / setting a cookie on the click of a link, is there a proper way to do this? Either PHP or Javascript is fine.
<html>
<a href="2.html" id="cookie">
<div class="yes">
<p>Yes</p>
</div>
</a>
</html>
<script>
$("a#cookie").bind("click", function() {
});
</script>
<?php
setcookie( "cookie")
?>
Obviously both JS and PHP wouldn't exist in the same instance it was just to show what I have.
You can't mix JavaScript and PHP. By the time your JavaScript code loads, your PHP code would have already executed.
In your case, it may be easier for you to set cookies without using PHP.
$("a#cookie").bind("click", function() {
document.cookie="cookie=value";
});
Here is a good example of setting cookies with javascript w3schools demo And I doubt it will be possible to set cookies to other domains except the origin of the page.
With PHP it is done in the next way: 1st you send http request to the server using javascript native xhr or jquery etc. and then php script must set cookie headers and return back to client. In this case browser will automatically set cookies received in headers.
Related
I'm using jQuery to display a certain page to a user through it's .load() function. I am doing this to allow user customization to the website, allowing them to fit it to their needs.
At the moment, I am trying to display the file feed.php inside of a container within main.php;
I have come across a problem where I would like to prevent direct access to the file (i.e: going directly to the path of it (./feed.php)), but still allowing it to be served through the .load() function.
If I use the .htaccess deny from all method for this, I get a 403 on that specific part of the page. I can't find any other solution to this problem; disallowing me to achieve what I want.
This is my current (simplified) script and html:
<script type="text/javascript">
$("#dock-left-container").load("feed.php"); // load feed.php into the dock-left-container div
</script>
<div class="dock-leftside" id="dock-left-container"></div> // dock-left-container div
If anyone could suggest a solution through .htaccess, php, or even a completely different way to do this, I'd be very grateful!
Thanks in advance.
Please follow below steps to achieve:
In the .load function of jquery post a security code.
In the Feed.php page place a PHP condition if the posted security_code params found and match with security_code passed in the .load then only allow to access the page otherwise restrict.
Please follow below changes in your existing code to achieve it.
JS
<?php
$_SESSION['security_code'] = randomCode();
?>
<script type="text/javascript">
$("#dock-left-container").load("feed.php", {
security_code: '<?= $_SESSION['security_code']; ?>'
}); // load feed.php into the dock-left-container div
</script>
PHP
Place php condition in the top of feed.php
if(isset($_POST['security_code']) && $_POST['security_code'] == $_SESSION['security_code']){
//Feed.php page's all the stuff will go here
}else{
echo "No direct access of this page will be allowed.";
}
feed.php:
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
readfile('myfeed.xml');
} else {
header('HTTP/1.0 403 Forbidden');
}
jQuery sends a HTTP_X_REQUESTED_WITH header by default. This is not, by far, anything remotely secure since HTTP headers are easily sent/spoofed. But it will stop the occasional user trying to access the feed directly.
You can, additionaly, check the $_SERVER['HTTP_REFERER'] header (but, again, this is easily spoofed) and, ofcourse, use your normal session logic to make sure the user is logged on if that's a requirement to access the feed.
Either way: there's no way to make this 'water tight'. If your browser can (should be able to) access the feed in some way then it's simply a matter of opening the debugger, having a look at the actual request sent in the network tab and sending the exact same headers/request to get to the file from, say, Curl. Actually, you will see the response of the request (i.e. the actual feed) in the debugger as well.
Repeat after me: if my (or a user's) browser can access the feed 'from jQuery' (via an AJAX request or whatever) then the feed is accessible to that user if he's even just a little bit more persistent than giving up immediately. Only using a session will keep out 'unauthorized' users because it relies on being logged in. After having logged in the request is visible no matter what and that request can be 'forged' to be sent from any other application no matter what.
I've been trying to set a third party cookie using the following method:
SiteA
<img src="http://www.siteB.co.uk/cookie.php" />
SiteB
<script>
document.cookie = "name=thirdpartytest; expires=07/07/2013; path=/;domain=SiteB.co.uk";
</script>
When I visit SiteB/cookie.php directly the cookie drops as expected. But accessing SiteA does not drop any cookie.
When I use the same methodology but use PHP to drop the cookie, it works great. Is there a reason why Javascript won't drop the cookie in this scenario? I thought it might be because there are no HTTP content-type headers being sent to say the .php page is an image. But I didn't seem to need that in place for the PHP version of the code to work.
Any ideas how to get this working using JS? Is it even possible? How does Doubleclick make this work for example?
For reference: this is the PHP code that successfully dropped the cookie
<?php
$CookieName = "my3Pcookie"; // Cookie's name
$CookieValue = "hello, there"; // Cookie's value
$CookieDirectory = "/"; // Cookie directory ("/" for all directories)
$DaysCookieShallLast = 31; // Days before expiration (decimal number okay.)
$lasting = ($DaysCookieShallLast<=0) ? "" : time()+($DaysCookieShallLast*24*60*60);
setcookie($CookieName,$CookieValue,$lasting,$CookieDirectory);
?>
Your problem is definitively based to the <img>-tag you're using. No JavaScript Code will be executed in an image.
The reason why it works if you do it by PHP is because the server is pre-processing your code at the time of requesting the file. Although this probably wont show you anything because you did not provide any valid image header.
If you would use the <iframe>-tag everything would work because the client can read and execute your JS-Code:
<iframe src='http://www.siteB.co.uk/cookie.php'></iframe>
But if you try to set the cookie by the <img>-tag you need to do it with a server-side language like PHP in this example.
Agencies like Doubleclick working with iframe, javascript snippets you sould insert into your page or|and a server-side solution.
Hope this helps.
I am trying to create a web application that loads content dynamically. When I do this, of course I want to do the development locally, i.e. localhost. Some of the "functionality" is a form and when posting that form an e-mail is sent from the server. Because I want to access the servers e-mail functionality, I am linking that specific page to the server. But the problem is that it is not loaded.
In my script below it works, but if I change the comments so I am pointing to iandapp.com, than I just get empty string. It's exactly the same page, just copied it to the server.
$("#support").click(function () {
if(support_page==null){
//$("#section2").load("http://www.iandapp.com/smic/subscription_2.php", function(data) {
$("#section2").load("subscription_2.php", function(data) {
support_page = data;
});
}
The script is located inte the main page (index.html) and content should be loaded into a div with id="section2".
I know that (support_page==null) is true because I have a break point inside where it stops.
Please let me know what the probelm is and how I can fix it. I have been going on for hours trying to get this working.
Thanks in advance!
google about
cross domain ajax requests
. This is disabled in the browser level. There are ways to circumvent this, both client side and server side.
It probably has something to do with it being a cross-domain request. You could use what I consider to be a "hack", http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/, but I.M.O. it's not worth it.
Have you considered sending through an SMTP server instead? If so, you'd have no problem with the file (sending the mail) being local.
And what about adding proper headers on server's http response to allow crossdomain ?
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Access-Control-Origin: *
Use .getJSON() instead of .load(), this method supports cross-domain requests. You'll need to make sure your PHP script does something like the following:
echo $_GET['callback'] . '(' . json_encode($results) . ')';
jQuery will append something like ?callback=callback0234 to the request url because it wants you to 'call' the callback function when your script returns. So the output of your script may look something like:
callback0234('mydata': '<p>This is my data</p>')
I want to redirect someone to index.php, how do i do this? But not the "meta" method, because it needs to be in header, and i can not have it there.
window.location.href = 'http://your-new-url.com';
or
window.location.pathname = 'index.php';
if you need to use a relative pathname.
Do not use JavaScript for this. If the user has JavaScript disabled (or most likely is browsing with a browser without support for JavaScript), the redirection will not work.
From your PHP code, you can send an HTTP header to direct your user to the page of your choice. Use the header() function to do this.
header('Location: index.php');
exit; // Important, stops execution of PHP page
If PHP complains that it cannot send the header because data has already been sent to the browser, simply go to the top of your script and enable output buffering by using ob_start():
ob_start();
With output buffering enabled, you can send headers anywhere in your code since data is only sent at the end of your script.
PHP Documentation: header()
PHP Documentation: ob_start()
Use window.location
<script type="text/javascript">
window.location.href = "http://www.yoursite.com/index.php"
</script>
This is the first time ever I'm using AJAX, and I want to do the following on an otherwise static page www.xyz.org/some_site.html:
Send a GET request to another url "www.xyz.org/testscript"
if response has either status code != 200 or content != 'ok': do nothing
else: include sth on the website (i.e. set style="display:block" on an element that previously had "display:none")
I've implemented that successfully using basic AJAX. But:
There is an Apache redirect installed pointing from www.xyz.org/testscript to subdomain.xyz.org/testscript, the URL where the actual testscript lives (as AJAX doesn't support cross-domain calls even to subdomains afaik).
When I call www.xyz.org/testscript I get a 302 status code, and the content says "The document has moved here: subdomain.xyz.org/testscript".
How can I grab the 'final' return value?
I guess/hope any AJAX expert can give me a one-liner to solve that ...
AJAX (or XMLHttpRequest to be acurate) won't be tricked by a redirect. To be able to get content from another domain you need to use a proxy on the server. The following is a simple PHP proxy:
if(strpos($_GET['q'], "http://") === 0){
echo file_get_contents($_GET['q']);
}
use it like this:
xhr.open(GET, "www.xyz.org/proxy.php?q=subdomain.xyz.org/testscript", true);
The answer is, according to the comments above:
It's not possible to achieve what I want to do, as AJAX can't be tricked into following a redirect.
EDIT: I tried to solve it by adding another javascript file at subdomain.xyz.org/another.js and throwing all AJAX code from my static html site into it.
Then, on the static html site, I included this script with an ordinary
<script src="subdomain.xyz.org/another.js">
tag. But that wouldn't work either ... cheated myself: Including the javascript on my static page results in the original problem again (cross-domain calls forbidden).