开发者

Calling another site?

OK - Simply, I'm building a site that needs to incorporate an existing page, protected with a simple .htaccess/.htpasswd script.

How can I pass the username/password to the receiving site using PHP?

Thanks in advance for your help!!!

UPDATE - I think I may have over-complicated the question. What I'm needing to do is essentia开发者_运维问答lly:

<a href="http://username:password@url.com/" target="_blank">The link<a>

Which, actually, works perfectly in everything but IE . I'm golden if I can find a more universal, simple solution.

Thanks in advance for your help, all!


I agree with alxp that you should get to know cURL. The basic gist is that when using HTTP Basic Auth, credentials are sent as a base64 encoded string in the headers. Here's a simple example using PHP's cURL extension:

$url = '...';
$username = '...';
$password = '...';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    "Authorization: Basic " . base64_encode($username . ":" . $password)
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

$result = curl_exec($ch);
print $result; 

Hope that helps! Read up on HTTP Basic here and PHP's cURL extension here

Please keep in mind that this is example code and contains no error checking, etc.


If you are using the file_get_contents function to download the page, you can use something like this:

$data = file_get_contents('http://username:password@example.com/path/');


You'll be best off if you get to know the curl library, a good introduction can be found here, including how to submit a suername and password.


You can pass the username and password in plain-text via a simple http redirect, in the format

http://username:password@yoursite.com/yourpage

However, you probably shouldn't - some browsers now explicitly bother you for confirmation when they see this syntax.

You can hide this from the user however, by loading the above URL with file_get_contents() and dumping the results to the browser. This won't work if the HTML output of the page uses relative links to external files (images/js/css) on its server.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜