PHP_AUTH_USER not set in AJAX action - php

I have a site which is using Basic Authentication, visitor can login with predefined credentials. I can reach the $_SERVER["PHP_AUTH_USER"] variable, so everything works fine here.
But when I'm trying to post data with jQuery AJAX in the same domain, I can't reach the $_SERVER["PHP_AUTH_USER"] variable (not set in the $_SERVER).
Environment:
Server version: Apache/2.4.7 (Ubuntu)
PHP Version: 5.5.9-1
Ubuntu: 4.9
(Server API: Apache 2.0 Handler, so not CGI)
Chromium: 41.0.2272.76
Ubuntu 14.04 (64-bit)
Can anyone help with this problem?

Along with greet, commented that the server will accept your application if you send in the request authentication, therefore you within Jquery Ajax method, and define Dentrol method the Autentification property through getAllResponseHeaders () function, an important point is in basic mode of authentication uses javascript base 64 (btoa) to encrypt the username and pass, I hope you find it useful and invite you to visit my github, enter link description here, have some useful ools Built to to validate data when luck
$.ajax({
url : 'test_2.php',
type : 'GET',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Basic ZWxlbWVudG86ZWxlbWVudG8=');
},
data: {},
success: function (e) {
console.log(e)
},
error: function (e) {
console.log(e)
},
});

Related

Can't log in to Laravel API on staging server (Laravel Forge) via NextJs or Postman

I have developed an API project on Laravel with Sanctum (Token) and NextJs for the frontend. I have setup things up correctly and everything is working fine on Localhost.
I deployed the project on Laravel Forge with one custom subdomain (eg. api.example.com). I run php artisan storage:link and php artisan migrate:fresh --seed (with env as staging) as per their guide (cd /to the path && artisan command) and this works. FRONTEND_URL in env has also been updated to the live frontend url (eg. nextjs.example.com).
I tried logging in to the backend from nextjs after deploying Backend on Laravel Forge and NextJs on Vercel. https://api.example.com/sanctum/csrf-cookie is working correctly as it responds to the browser with the XSRF-TOKEN. But it fails on login with csrf-token mismatch.
Then I tried logging into it with Postman and the same thing happens. I can request the csrf-cookie separately but can not log in to the api backend with responded token. However, it is working fine on the localhost.
This is a piece of my working codes on localhost (NextJs)
const csrf = () => axios.get('/sanctum/csrf-cookie');
const login = async (loginDetails, setErrors) => {
setErrors('');
await csrf();
await axios
.post('/login', loginDetails, {
headers: {
'X-XSRF-TOKEN': getCookie('XSRF-TOKEN'),
},
})
.then(async (res) => {
if (res.data.status === 401) {
setErrors(res.data.message);
} else {
localStorage.setItem('user_token', res.data.data.token);
setCookie('user_token', res.data.data.token);
await axios
.get('/api/authenticated-user', {
headers: {
Authorization: `Bearer ${localStorage.getItem('user_token')}`,
},
})
.then((res) => {
localStorage.setItem(
'user_data',
JSON.stringify(res.data.data)
);
});
router.push('/dashboard/);
}
})
.catch((err) => {
setErrors(err.response.data.message);
});
};
I got the solution for this.
The reason it is not working on Postman is that X-Requested-With: XMLHttpRequest & X-XSRF-TOKEN: {{csrf-token}} were missing on the headers after duplicating the one that works on localhost for the live version. If you are experiencing the same issue, please double-check whether those headers are present on the request's headers. Then, it started working on Postman but not on the live NextJs project with the subdomain.
To make it work perfectly on the subdomain, please check this thread since I created a different question at the same time with the purpose of making it clear for the ones who wanted to answer.

ajax call to php not working 404 error mismatched localhost

I'm using xampp on my Windows 10 dev machine and when I launch my javascript app using chrome, the browser uses localhost:8080 as the root directory.
For my php ajax calls, I have to use the fully qualified path to get them to work. For example:
$.ajax({
type: "GET",
dataType: "json",
url: "http://localhost/get_user.php",
data: {email: $("#email").val()}
});
Note that I have to use localhost for the ajax calls whereas the javascript root is localhost:8080. My php files are stored locally in c:/xampp/htdocs.
I want to use a short form url that works on both my local dev machine and on the production website. Something like
$.ajax({
type: "GET",
dataType: "json",
url: "/get_user.php",
data: {email: $("#email").val()}
});
My understanding (and I'm new to this) is that if I use the short form url /get_user.php the system uses the same root as the client side app (i.e. http://localhost:8080/get_user.php). But only fully qualified http://localhost/get_user.php is working for my ajax calls.
I get the following error message when using the short form /get_user.php:
GET
http://localhost:8080/check_login.php?password=xxxxxxxxxx&email=drew%40aol.com
404 (Not Found)
So the client side uses localhost:8080 and the server side expects localhost. I'm sure this is probably an xampp config issue but haven't been able to solve on my own. Any insight would be appreciated.
Try changing your data type to jsonp rather than json. I think you are running into a cross-origin resource sharing problem. A permission problem, essentially. localhost and localhost:8080 are two different domains, as far as your browser is concerned. If your code is executed from localhost:8080 and you give it a relative url, like /something.php, it assumes you are requesting it from the same domain. localhost is equivalent to localhost:80.

Blueimp Codeigniter image upload ajax 500 internal server error

I am trying to implement blueimp to my codeigniter project for multiple image upload of images. i am facing 500 (internal server error) i know this appears if we have any error in our php script.
in my php script i am getting response as {"files":[]} to represent no of img's which are present in my img_upload folder. it have to return null object thats true but
in my console i am getting a error as the below image.
as i clicked on anonymous function Here in my.js redirecting me to below function.
$.ajax({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: $('#fileupload').fileupload('option', 'url'),
dataType: 'json',
context: $('#fileupload')[0]
}).always(function () {
$(this).removeClass('fileupload-processing');
}).done(function (result) {
$(this).fileupload('option', 'done')
.call(this, $.Event('done'), {result: result});
});
what i am thinking is this might be issue with return type html or json but not able to to get how to fix this issue. how can i solve this issue so i can upload image without getting internal error. Thanks in advance.
I am following the following github wiki and my code is same to same.
This blog
may be its php.ini problem
Open your php.ini file
search for extension=php_fileinfo.dll
if you are using xampp it may be commented by default
change
;extension=php_fileinfo.dll
to
extension=php_fileinfo.dll
and restart your xampp...
this was solve my problem

jQuery AJAX simple PHP Post not working

I've got a very basic one today! I'm trying to post from jQuery to a PHP file hosted on localhost.
My JS:
$("#searchNameButton").click(function() {
var name = $("#searchNameText").val();
$.ajax({
type: 'POST',
url: 'localhost:8080/getNameInfo.php', // -> this works fine from the browser
// data: { name: name }, -> commented out
success: function(){
alert('request successful');
},
error: function(xhr, textStatus, errorThrown){
alert('request failed');
}
})
});
My PHP file (getNameInfo.php), a very basic one for testing:
<?php
echo 'TEST';
?>
In jQuery, it will always bring me to error, saying 'Internal Server Error'.
I am using Ripple Emulator and this is what appears in the console:
POST https://rippleapi.herokuapp.com/xhr_proxy?tinyhippos_apikey=ABC&tinyhippos_rurl=localhost%3A8080/getNameInfo.php
500 (Internal Server Error)
I assume it has to do more with this than with what's written in the files. Any advice? Thanks!
EDIT: Found this: LINK but it won't fix my issue. If I do what it says here, I won't get any error thrown ("" instead) but will still fail.
EDIT 2: If I set Cross-Domain Proxy to Local in Ripple (that's suggested in the link above) I get
OPTIONS http://localhost:4400/ripple/xhr_proxy?tinyhippos_apikey=ABC&tinyhippos_rurl=http%3A//localhost%3A8080/getNameInfo.php net::ERR_CONNECTION_REFUSED
EDIT 3: Changed my URL to local
C://Mobile//Cross-Platform//TestApp//www//php//getNameInfo.php
and it's working now. Have no idea how to make it work on localhost. BUt will go with this now, as it's only a learning app.
Add a header access control at top of getNameInfo.php file :
header('Access-Control-Allow-Origin: *');
So, finally I found a solution.
Even though it's not a recommended one, running Chrome with
--disable-web-security
will allow me to call a PHP script hosted on localhost:8080 from localhost:3000 where PhoneGap / Ripple Emulator stays.

Connect to Homebrew PHP/MySQL from Angular App using $http

I am building an Angular App with Gulp locally on my dev machine, that will eventually be a SaaS. All the data is hardcoded JSON in a service purely to get the front-end working.
Now I am ready to connect to a local database and will use PHP/MySQL.
I have a local development environment on OSX setup with Homebrew that has PHP and MySQL ready to go.
The issue:
I get a 404 when I use the url: 'db-insert.php' line no matter where I put the db-insert.php file in my directory structure.
POST http://localhost:3000/db-insert.php 404 (Not Found)
var request = $http({
method: 'post',
url: 'db-insert.php',
data: {
name: $scope.name,
email: $scope.email,
message: $scope.message
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
I have investigated
• CORS: Tried open -a 'Google Chrome' --args -allow-file-access-from-files
• gulp-connect-php
• gulp-webapp-running-browsersync-and-php
• BrowserSync Proxies
The app uses Gulps BrowserSync which has a proxy option that leverages Express to connect to a defined middleware, but I am stumped at where to point it or if it is the correct option at all.
Any explanation of what the correct way to do this is would be great. I think the answer is probably a combination of what I have found, but the implementation is the issue. Thanks much.
Ok, This turned out to be a filesystem/CORS issue. Here is how I solved it:
1) Go through the server to get to the php file
http://127.0.0.1/dev/db-insert.php
NOT
file://myproject/dev/db-insert.php
I was trying to access the file directly in the file system and not by its URL on the PHP server I have running as my localhost. When I changed the url to go through the apache server to find the file, it was able find it.
2) Once I got to the file I got the CORS issue
Adding the code below to the top of db-insert.php executes allowed the file to be accessed.The server could then execute the code.
header('Access-Control-Allow-Origin: '. $_SERVER['HTTP_ORIGIN'] );
header('Access-Control-Allow-Credentials: true' );
header('Access-Control-Request-Method: *');
header('Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: *,x-requested-with,Content-Type');
header('X-Frame-Options: DENY');

Categories