Using CORS for Angularjs IONIC - php

I am using $http.post() to access an api but I get the response back
XMLHttpRequest cannot load http://tester.com/cp/api/index.php?action=1. Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.
And I have added <?php header('Access-Control-Allow-Origin: *'); ?> to the index.php.
I don't know why it is not working.

Create a proxy service running on the top of NodeJS by executing these line in your console:
npm install -g corsproxy
Then simply start the proxy with:
corsproxy
It will ask you where/on which port do you want to run it. Choose something and it will output something like (in my case was that):
http://localhost:8100/
Then you will be able to make requests like:
http://localhost:8100/yourdomain.com/api/endpoint
Remember the 'CORS problem' persists only on your local machine's browser and therefore there is no need for CORSPROXY when you make API calls from the mobile device.
Read more about it here: http://ionicinaction.com/blog/how-to-fix-cors-problems-and-no-access-control-allow-origin-header-errors-with-ionic/

Related

How can I set the Access-Control-Allow-Origin header?

I know this is a really simple question, but after searching a lot I can't find how to set headers.
Here's what I want to do:
Whenever the user goes to https://www.google.com/, then an extension should log that into a logfile. I currently am developing the extension on my own device, and using http://localhost/log.php to get POST requests and log information to files based on the information POSTed. My manifest is working and I have tested it. Below is my track.js:
function log(info){
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function(){
if(this.readyState===4&&this.status===200){
console.log(this.responseText);
}
}
xhttp.open("POST","http://localhost/log.php",true);
// xhttp.setRequestHeader("Access-Control-Allow-Origin","*");
// above: my first attempt to set a header (did not work)
xhttp.send("log_info="+info);
}
if(location.href==="https://www.google.com/")log("We're at google.com!");
This is my log.php:
<?php
header("Access-Control-Allow-Origin: *");
if(isset($_POST["log_item"]))
file_put_contents("log.txt", $_POST["log_item"]."\n",FILE_APPEND);
And log.txt is an empty file. I know CORS is the problem because when I open the console on https://www.google.com/, I see this:
Access to XMLHttpRequest at 'http://localhost/log.php' from origin 'https://www.google.com' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
POST http://localhost/log.php net::ERR_FAILED
This seems really simple to me but I can't find how to set headers. Thanks for any help.
You should add "Access-Control-Allow-Origin: *" on your webserver configuration (Nginx or Apache or ...) that you are currently using on your localhost.
You can not bypass CORS from your code or your request at all.
For nginx (/etc/nginx/nginx.conf):
https://enable-cors.org/server_nginx.html
Apache:
https://enable-cors.org/server_apache.html

How can i pass cookies in jmeter?

After recording script, I have added 'Cookie Manager'.
2. While running, Cookies are not showed for Request headers in Jmeter and the Connection closed error showing for listener.
But, Browser cookies are passing the request headers in my application.
So, How can i pass cookies in jmeter. kindly give me a solution.
Please refer the snapshot.
Thanks,
Vairamuthu.
Just add to Test Plan an HTTP Cookie Manager before your request.
I don't think you should be sending cookie. I would rather expect that you need to extract the value of this _xsrf cookie from the /api/login request and add the extracted value as X-Xsrftoken header.
Add the next line to user.properties file (located in JMeter's "bin" folder"
CookieManager.save.cookies=true
and just in case this line as well:
CookieManager.check.cookies=false
Restart JMeter to pick the properties up
Add HTTP Header Manager to the request which is failing
Make sure it contains the following like:
Name: X-Xsrftoken
Value: ${COOKIE__xsrf}
More information:
Configuring JMeter
How to Load Test CSRF-Protected Web Sites

How do I end a PHP connection with a client and still log to an external service?

I was wanting to log to Keen.IO (an external logger service) after a php session was over but I didn't want the user to need to wait for that process to finish. Is there a way to end the connection with the client before this happens? Additionally, I didn't want the client session to hang if for some reason the Keen.IO service goes down.
You can forcefully close the connection with fastcgi_finish_request() if you're using PHP-FPM. See this answer for more details.
<?php
echo 'Page content';
fastcgi_finish_request(); // cut connection
do_logging();
I have tried other methods before (eg. setting HTTP headers to disable keep-alive and defining the response length), but none of them worked. So if you're not using FPM, you're out of luck.

block direct access to PHP file and only allow local javascript to access it

I need a way to block all access to a php file but to allow a javascript file that send xmlhttp request to it. that js file is hosted on my server and must stay on my server for it to work
I have the following
header('Access-Control-Allow-Origin: *');
but that allows anyone to access it.
Well, I don't think this would be possible. Anyone can make a request to your server but your server chooses who to respond to and how to respond to a request. Now, if you want only your JS to be responded to by your server, then you will have to inform the server at the time of making an HTTP request from your JS. That cannot be done without exposing your Javscript file's identity on the basis of which your JS can be identified by the server. But anyone can open your JS and read it and figure out how you are making the request and use the same thing.
One possible solution could be, use header('Access-Control-Allow-Origin: *') to allow everyone to make a request to your server but at the server's end, keep a list of allowed domains/origins in a database on your server who may use or are going to use your JS file on their website. Based on the AJAX request that you get, you check from your database that if the origin of the request is allowed or not and respond accordingly. Now, if someone tries to request your PHP file by any other means than your JS, on the basis of the data in your DB you can reject the request or accept the request. If an allowed user/website does this, then they will be knowingly messing around with their own data.
Try this:
if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) <> 'xmlhttprequest')
{
die('direct access is not allowed');
}
Also, you can always check referrer like $_SERVER['HTTP_REFERER'] to be sure that only your script from your domain can access it.

can you use curl to post to a local file?

I tried using curl to post to a local file and it fails. Can it be done? my two management systems are on the same server and it seems unnecessary to have it traverse the entire internet system just to go to a file on the same hard drive.
Using localhost didn't do the trick.
I also tried to $_SERVER[DOCUMENT_ROOT].'/dir/to/file.php' using post data. It's for an API that is encrypted, so I'm not sure exactly how it works. It's for a billing system I have and I just realized that it sends data back (API).
It's simply post data and an XML response. I could write an html form tag and input fields and get the same result, but there isn't really anything else to know.
The main question is: Does curl have the ability to post to a local file or not?
it is post data. it's for an API that is encrypted so i'm not sure exactly how it works
Without further details nobody can answer then what you should do.
But if it's indeed a POST receival script on the local server, then you can send a POST request to it using the URL:
$url = "https://$_SERVER[SERVER_NAME]/path/to/api.php";
And then receive its output from the cURL call.
$data = curl($url)->post(1)->postdata(array("billing"=>1234345))
->returntransfer(1)->exec();
// (you would use the cumbersome curl_setopt() calls instead)
So you get a XML or JSON or whatever response.
If they're on the same drive, then use file operations instead:
file_put_contents('/path/to/the/file', $contents);
Using CURL should only be done if you absolutely NEED the http layer to get involved for some reason, or if you're dealing with a remote server. Using HTTP would also mean you need to have the 'target' script be able to handle a file upload plus whatever other data you need to send, and then that script would end up having to do file operations ANYWAYS, so in effect you've gone on a round-the-world flight just so you can move from your living room to the kitchen.
file://locafilespec.ext worked for me. I had 2 files in the same folder on a linux box, in a folder that is not served by my webserver, and I used the file:// wrapper to post to file://test.php and it worked great. it's not pretty, but it'll work for dev until I move it to it's final resting place.
Does curl have the ability to post to a local file or not?
To curl local file, you need to setup HTTP server as file:// won't work, so:
npm install http-server -g
Then run the HTTP server in the folder where is the file:
$ http-server
See: Using node.js as a simple web server.
Then test the curl request from the command-line to localhost like:
curl http://127.0.0.1:8081/file.html
Then you can do the same in PHP.

Categories