We help IT Professionals succeed at work.

HTTP authentication with PHP

fradolcino
fradolcino asked
on
Medium Priority
525 Views
Last Modified: 2013-12-13
hello!
i want to parse an xml in php (that part i done it)
problem is :
the xml file is on a web server and access to the file is possible with a autentification (username, password). Is not a post authentification (.php script).
I know the username and the password (i don't want to hijack anything).
but how can i get my file directly ???
Thanks
Comment
Watch Question

Commented:
is your php script reside on the same server or on a different server?
Senior Software Developer
Commented:
Quick way would be to use a context ...

<?php
define ('REMOTE_USER', 'your_username');
define ('REMOTE_PASSWORD', 'your_password');
$am_security_context = array(
      'http' => array
            (
            'method' => 'GET',
            'header' => 'Authentication: Basic ' . base64_encode(REMOTE_USER . ':' . REMOTE_PASSWORD) . "\r\n",
            ),
      );

$r_secure_default_context = stream_context_get_default($am_security_context);

$fp = fopen('http://www.securesite.com/file.xml');

?>


OR

<?php
define ('REMOTE_USER', 'your_username');
define ('REMOTE_PASSWORD', 'your_password');
$am_security_context = array(
      'http' => array
            (
            'method' => 'GET',
            'header' => 'Authentication: Basic ' . base64_encode(REMOTE_USER . ':' . REMOTE_PASSWORD) . "\r\n",
            ),
      );

$r_secure_context = stream_context_create($am_security_context);

$fp = fopen('http://www.securesite.com/file.xml', False, $r_secure_context);
?>

As long as the security is basic authentication (i.e. you get a browser window popup) then this mechanism is how you supply your credentials.

If the site is protected by a login form, then you will need to create a POST context with alll the data for the form.
Submit it.
Get the session cookie.
Send the session cookie with the request for the file.

That SHOULD work, but I've never done that.

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Richard QuadlingSenior Software Developer

Commented:
Oops. Ignore tht last bit about the login form as I forget you said it wasn't a POST.

Author

Commented:
for alain : my php script is on my server, the xml file is on other server
for RQuadling : i try your script but nothing happens
any more ideeas?
thx

Commented:
Well, did you manage to open the file.
The code from RQuadling is just opening the file. Have you added some code to read the file and display the content!!!

Author

Commented:
ok, i will put here my code
(i use for parse xml , miniXML - who work fine with a file from local server)
<?
define ('REMOTE_USER', 'my_username');
define ('REMOTE_PASSWORD', 'my_password');
$am_security_context = array(
     'http' => array
          (
          'method' => 'GET',
          'header' => 'Authentication: Basic ' . base64_encode(REMOTE_USER . ':' . REMOTE_PASSWORD) . "\r\n",
          ),
     );

$r_secure_default_context = stream_context_get_default($am_security_context);?>
require("inc/minixml.inc.php");
$xmlDoc = new MiniXMLDoc();
$xmlDoc->fromString(file_get_contents('http://www.my_secure_site.com/myfile.xml'));
$all_news=$xmlDoc->toArray();
print_r ($all_news);
?>

Richard QuadlingSenior Software Developer

Commented:
Can you give us the URL to the file, just so that we can confirm the type of request required.
Richard QuadlingSenior Software Developer

Commented:
Ah. There is a REALM of REALTIME.

I think that needs to be included in there somewhere.

Hold on.
Richard QuadlingSenior Software Developer

Commented:
Try Authorization rather than Authentication

Richard QuadlingSenior Software Developer

Commented:
'header' => 'Authorization: Basic ' . base64_encode(REMOTE_USER . ':' . REMOTE_PASSWORD) . "\r\n",
Richard QuadlingSenior Software Developer

Commented:
I'm just testing this with ethereal. See what ACTUALLY happens from the browser.
Richard QuadlingSenior Software Developer

Commented:
Yep. Authorization!

Richard QuadlingSenior Software Developer

Commented:
Sorry about that.

And the realm stuff is not required. That is something that comes FROM the server to the client.

Commented:
try the following. Could you save that on your php server with your real userid and password and fire it up from your browser. Than post here what is given back. Make sure that you look at the source code on your browser and not at your browser window!!!

<?php

$credentials = base64_encode("yourUserid:yourPassword");

$data  = "GET /online/realtime/bet.xml HTTP/1.1\r\n";
$data .= "Authorization: Basic $credentials\r\n";
$data .= "UserAgent: myUserAgent\r\n";
$data .= "Host: www.bvb.ro\r\n";
$data .= "Connection: Close\r\n\r\n";  


$fp = fsockopen('http://www.bvb.ro', 80, $errno, $errstr, 15);
if (!$fp) {
   echo "$errstr ($errno)<br />\n";
} else {
  fputs($fp, $data);
  }

// for debugging/response handling you can view the data returned
while(!feof($fp)) {
  echo fgets($fp, 1024);
  }
 
?>

Commented:
I don't really want any point, but for my own satifaction, could you tell me if my solution is working at all!!!!
Richard QuadlingSenior Software Developer

Commented:
Your solution would have worked, but the context mechanism is cleaner maybe.

If it is up, take a look at the user notes on http://www.php.net/manual/en/function.stream-context-get-default.php. Not there yet. Check tomorrow when it is up.

Or ...

One way of achieving a system wide default context is to use the php.ini setting auto_prepend_file.

By creating a php script which is placed anywhere in the include_dir paths, you can assign the default context for all streams.

This is of most use when you are behind a firewall and without the context, stream functions like fopen('http://www.site.com/page.html')
fail as the proxy server rejects the request.

The auto_prepend_file itself can be anything you like.

The sort of things you can include in it are ...

1 - __autoload()

Control the automatic loading of classes on demand. This helps reduce the amount of loading and memory usage when a script starts.

2 - Global Uncaught Exception Handling

By placing a set_exception_handler() function in this file you can catch ALL exceptions. A much nicer way than having the page be just an error.

3 - Global error handling

Pretty much the same as 2 really, but for generic PHP errors. Ideally, these are the things you should engineer out of the code.

4 - Default Stream Context.

As I mentioned, if you are behind a firewall, then having a default context is EXTREMELY useful. Thanks to tiago at mdtestudio for alerting me to this function.


The great thing about the auto_prepend_file is that is can be set on a per directory basis. This means that if you are on a shared host, you can see the auto_prepend_file setting within your webroot.

There is also auto_append_file which probably has more use for traditional HTML footers. I've not found a PHP specific reason for this setting. Yet.
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.