问题
I've been working with php curl to create a login script for my school's network, but I've hit a snag. I got my script to login, but the home page is made up of frames. The content isn't showing up for either frame, saying the url was not found on the server. The urls for each of the frames are relative, so the browser is looking on my server for the files instead of the other server (and obviously won't find them). I set the referer field with CURLOPT_REFERER, but the problem persists. Is there a simple way to get around this relative url problem?
回答1:
First off, I would like to state that I know this is an old question, but I have come across it a few times when searching for curl solutions and think it would be helpful for other people looking for this answer.
Question Clarification
From what I understand, you can see the frame, but you cannot see the contents of the frame because the src attribute of the frame is relative. You also wish to follow the frame through php curl.
Example Code
<?php
// Simple curl function
function get_page($url){
$msg = "";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$html = curl_exec($ch);
if (!curl_errno($ch)) {
$msg = $html;
} else {
$msg = 'Curl error: ' . curl_error($ch);
}
curl_close($ch);
return $msg;
}
// Desired domain
$domain = "http://www.w3schools.com";
$page_content = get_page("$domain/tags/tryit.asp?filename=tryhtml_iframe");
// Display fetched page
var_dump($page_content);
// Navigate dom to iframe in question
$xml = new DOMDocument();
@$xml->loadHTML($page_content);
$path = new DOMXPath($xml);
$forms = $path->query("//iframe[@id='iframeResult']");
$relative_uri = "";
foreach ($forms as $form) {
// Should be only 1 result
if (strtolower($form->getAttribute('id')) === strtolower("iframeResult")) {
$relative_uri = $form->getAttribute('src');
}
}
// Display fetched iframe
$page_content = get_page("$domain/tags/$relative_uri");
var_dump($page_content);
?>
Notes on Example
I choose www.w3schools.com because I am guessing that their example won't change in a while and will probably have better up-time than some randomly selected website.
I would also like to state that the right example frame itself on the w3schools website is a relative frame, not the actual example frame they show! Look for yourself by searching for iframeResult
in an element inspector.
Running Example
Page to be navigated
http://www.w3schools.com/tags/tryit.asp?filename=tryhtml_iframe
Example of php curl navigating the page
http://ipatenco.com/example/curl-iframe.php
来源:https://stackoverflow.com/questions/4011546/how-to-use-php-curl-with-frames