I used this way to get data from server to client side. but I have a problem to authenticate server files.
I want to check username and password before give permission to read data. I tried to that using an extra method but I it doesn't work.
class MyService
{
public function add($x, $y)
{
return $x + $y;
}
}
$options = array(
'uri' => 'http://server/namespace',
'location' => 'http://server/location',
);
$server = new SOAPServer(null, $options);
$server->setObject(new MyService());
$server->handle();
$options = array(
'uri' => 'http://server/namespace',
'location' => 'http://server/location',
);
$client = new SOAPClient(null, $options);
echo $client->add(10, 10);
If you can live with a hard-coded username and password and HTTP basic authentication, then you can put the following code on top of the server file:
if (! isset($_SERVER['PHP_AUTH_USER']) ||
$_SERVER['PHP_AUTH_USER'] !== 'foo' ||
$_SERVER['PHP_AUTH_PW'] !== 'bar') {
header('WWW-Authenticate: Basic realm="My service"');
header('HTTP/1.1 401 Unauthorized');
echo 'Unauthorized';
exit;
}
This checks whether HTTP authentication data is present, and if not, will send an HTTP 401 error back to the client. If authentication data is present, it will be validated against the hard-coded username foo and password bar.
In order to pass username/password from the client script, adjust $options
in the client as follows:
$options = array(
'uri' => 'http://server/namespace',
'location' => 'http://server/location',
'login' => 'foo', // username
'password' => 'bar' // password
);
$client = new SOAPClient(null, $options);
Please note that HTTP basic authentication is the simplest to set up, but that username and password will be transferred to the server in quasi plain text. You should therefore at least use SSL for the service endpoint, so all communication gets encrypted.
HTTP digest authentication is more secure, as it will only send hashes of the credentials, but it requires a bit more work to set up. A good starting point is the HTTP authentication page in the PHP manual.
For validating the received username/password data on the server side, you may also want to use a database with valid usernames/passwords/login tokens instead of the hard-coded credentials from the example.
Why not send the username+pass as a parameter in the soap. On the server side you should have a base object that has all the authentication logic and have "MyService" inherit that. The base object will always handle the request and then pass on the details to MyService if it passes authentication.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With