I want to get session data from subdomain - php

I am on m.example.com and want to get session from www.example.com
php code (session.php):
<?php
ini_set('session.cookie_domain', '.jeelplus.com');
session_set_cookie_params(0, '/', '.jeelplus.com');
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: POST, GET');
header('Access-Control-Allow-Headers: Authorization, X-Requested-With, Content-Type, Origin, Accept');
//header('Access-Control-Allow-Credentials: true');
session_start();
print_r($_SESSION);
echo('11111111111111111');
exit;
?>
jquery code:
function userIsLoggedIn(){
var logged_in = null;
$.ajaxSetup({cache: false, crossDomain:true, headers: {"X-Requested-With": "XMLHttpRequest"}, xhrFields: { withCredentials: true }})
$.get("http://www.example.com/session.php", {requested: 'foo'}, function (data) {
alert(data);
logged_in = data;
});
}
response:
Array
(
)
11111111111111111
what are the missing steps??

Session is not managed for subdomains. You have to use cookie.

Related

Axios to php api - POST form empty

I'm sure this is an easy one, hopefully it's easy. In setting up axios (with VUE) and trying to post something, anything, POST is not received. Postman works fine, my vue app with Axios however does not, the POST array arrives empty.
The outgoing request payload in devtools has the variables (at the moment just 'test'='test.
From Vue
this.$axios.post("http://localhost/api/process.php?action=addEntry", {
test:"test"
}).then(function (response) {
alert(JSON.stringify(response));
})
.catch(function (error) {
alert("error");
alert(JSON.stringify(error));
});
return
},
From PHP Api - process.php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: User-Agent, Sec-Fetch-Mode, Referer, X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding");
header("Access-Control-Allow-Methods: POST");
header('Content-Type: application/json;charset=UTF-8');
echo (var_dump($_POST['test']));
echo (var_dump($_POST));
Output
The POST is not available.
The response
The headers
Try this
axios.post("urlapi",
data: {
foo: 'bar', // This is the body part
}, {
headers: {
'Content-Type': 'application/json'
}
}).then(function(res){
console.log(res);
}).catch();
This works for me.

Angular cross origin issue in API call Backend PHP?

Facing CORS in angular, when i was trying to make a API call between my localhost to another domain.I am getting 404 issue .
1.Front End : Angualr 7
Front end request part:
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Credentials': 'true',
'Access-Control-Allow-Methods':'POST',
'Access-Control-Allow-Headers': 'Content-Type'
})
}
login(username: string, password: string) {
return this.http.post<any>('http://remote/djaxtesting/enter_uiupgrade/index.php/api/v1/user/validate',
{acc_type: "ADMIN", uemail: "djax_admin#dreamajax.com", upw: "123456"},httpOptions)
.pipe(map(user => {}))
}
Back end coding :
<?php defined('BASEPATH') OR exit('No direct script access allowed');
header ("Access-Control-Allow-Origin: *");
header ("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json');
public function validate_post()
{
$role = array('ADVERTISER','TRAFFICKER','ADMIN','MANAGER');
if($this->post('acc_type') !='' and in_array($this->post('acc_type'),$role))
{
switch(strtoupper($this->post('acc_type')))
{
case "ADMIN":
$adminObj = $this->do_networks->validate_user($this->post('uemail'),$this->post('upw'),$this->post('acc_type'));
//$this->response($adminObj, 200);
}
}
}
enter image description here
We using php for api. Helping handing needs to solve this issue ?
The problem with the option method. Option request should be a 200 returning an empty response. Then the browser will send the real POST request.
for that replace with the headers in your PHP File in the constructor. It will work.
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
die();
}

How can use AngularJs $stateChangeSuccess to populate data to MySQL using PHP?

I have this funcion who list objects with arrays:
//onload event-- to set the values
$scope.$on('$stateChangeSuccess', function () {
$scope.cart=sharedCartService.cart;
$scope.total_qty=sharedCartService.total_qty;
$scope.total_amount=sharedCartService.total_amount;
});
I need get all datas and insert all (populate) in a database. I´m using MySQL and PHP.
Thanks.
You create a file let say its called save.php
In that file you will have something like
header("Access-Control-Allow-Origin: *");
Global $db;
$db = new PDO('mysql:dbname=databasename;host=localhost', 'dbuser', 'dbpassword');
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
$postdata = file_get_contents("php://input");
if (isset($postdata)) {
$request = json_decode($postdata);
$cart = $request->cart;
$total_qty = $request->total_qty;
$total_amount = $request->total_amount;
}
else {
echo "Not called properly!";
}
$query = $db->prepare("
INSERT INTO yourtable
(cart, total_qty, total_amount)
VALUES
(:cart, :total_qty, :total_amount)");
$query->execute(array(
':cart' => $cart,
':total_qty' => $total_qty,
':total_amount' => $total_amount));
And in your function in Angular (stateChangeSuccess) you make a post request on for example http://localhost:8080/save.php
$http.post(url, data, config)
.then(
function(response){
// success callback
},
function(response){
// failure callback
}
);

.ajax post to external server php file causing 500 error

I have a php file on an second server that creates JWT Tokens using the Firebase Token Generator (https://github.com/firebase/php-jwt).
When I make a post using .ajax in my app, it keeps giving me a 500 error. I think that use \Firebase\JWT\JWT; in the php file may be causing this issue, but i am not sure why. Would appreciate any assistance with pointing me in the right direction.
Here is the PHP
<?php header('Access-Control-Allow-Origin: *'); ?>
<?PHP
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
// include('./config.php');
require_once '../vendor/firebase/php-jwt/src/BeforeValidException.php';
require_once '../vendor/firebase/php-jwt/src/ExpiredException.php';
require_once '../vendor/firebase/php-jwt/src/SignatureInvalidException.php';
require_once '../vendor/firebase/php-jwt/src/JWT.php';
$issuedAt = time();
$expire = $issuedAt + 86400; //add 24 hours
$personalID = $_POST['personalID'];
$email = $_POST['email'];
$key = "stringkeyexample";
$token = array(
"iss" => "example.com",
"aud" => "example.org",
"iat" => $issuedAt,
"nbf" => $issuedAt,
"exp" => $expire,
"pid" => $personalID
);
if ($puid){
use \Firebase\JWT\JWT;
$jwt = JWT::encode($token, $key);
print_r($jwt);
}
here is the .ajax:
$.ajax({
type: "POST"
, dataType: "html"
, url: "https://external-server.com/jwt.php"
, data: {personalID: personalID, email: email}
, beforeSend: function(){
console.log("before");
}
, complete: function(){
console.log("done");
}
, success: function(html){
console.log(html);
}
});

angularjs and PHP : Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response

I'm trying to do a simple POST from angularjs to a dummy php file to understand how this works.
Here in my angularjs part:
<html ng-app="loginApp">
<head>
<meta charset="utf-8">
<title>Login</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script>
var logindata = {username:'abc', password:'abc'}
var loginApp = angular.module('loginApp', []);
loginApp.controller('loginCtrl', function ($scope, $http){
var request = $http({
method: "POST",
url: "http://different-ip/a.php",
data: logindata,
headers: { 'Content-Type': 'multipart/form-data', 'Authorization': 'Basic ' + btoa(logindata.username + logindata.password),
'Access-Control-Allow-Origin': "*"}
});
request.success(
function( data ) {
$scope.someVariableName = data;
}
);
});
</script>
</head>
<body ng-controller="loginCtrl">
<h2>Angular.js JSON Fetching Example</h2>
<p> {{ someVariableName }} </p>
</body>
</html>
Here is my PHP part (a.php) that resides on http://different-ip
<?php
header("Access-Control-Request-Method: *");
header("Access-Control-Request-Headers: *");
header("Access-Control-Allow-Origin: *");
file_put_contents("aa.txt", json_decode(file_get_contents('php://input'),true));
file_put_contents("aaa.txt", getallheaders());
?>
When I execute my angularjs file, the chrome console gives me this error:
Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.
When I try doing a post to this a.php using Postman, everything works fine. So why is angularjs not allowing it?
I've tried to read about CORS and there is no straightforward answer to how this issue can be resolved (code wise). Can someone please help me out? Thanks in advance.
Added this instead of current headers to my PHP file and now it works! Thanks #Armen for your help!
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
Add this 3 headers at top of a.php instead current ones with if condition
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header( "HTTP/1.1 200 OK" );
exit;
}
file_put_contents("aa.txt", json_decode(file_get_contents('php://input'),true));
file_put_contents("aaa.txt", getallheaders());
?>
You can check more about CORS here: http://www.w3.org/TR/cors/#access-control-allow-headers-response-header
Postman works because it is additional browser extension which don't cares about headers policy and don't check it before request.

Categories