I am using ajax on a website that calls a php script that then parses another page and returns the part of the page that I want to display. I have used this technique in the past and it works well, except this time the part of the page that is being returned has some php code in it and it is being returned raw with out the php code being processed.
Here is the php script that is doing the parseing and returning the results.
require_once('simple_html_dom.php');
$dom = new simple_html_dom;
if(isset($_GET['url'])) {
$url = $_GET['url'];
$html = file_get_html($url);
/*get contents*/
$contents = $html->getElementById('content');
echo $contents;
}
As I mentioned what is being returned in $contents is being returned raw with out the php code inside the $contents string being processed, how can I get it to process the php code before returning the $contents string?
Thank you in advance for your help.
Parsing the HTML generated by another PHP script is rather hackish. If you are developing a new site, at a minimum, you should divide your PHP script into functions and then, for AJAX requests, only call the necessary functions.
Even if you are working on an existing, complex site, keep in mind that jQuery's .load() allows you to insert a specific fragment of the server's response into the document, discarding the rest:
$('#content').load('script.php #content');
That said, what you are asking about is possible:
PHP's output control functions allow you to capture a script's output as a string, which you can parse using str_get_html(). To make this work, you would have to include the existing PHP script. Note that any script you include will have access to global functions and variables, superglobals, and classes.
Warning: Make sure you check the requested filename against a whitelist of specific files to prevent file inclusion attacks. Merely blacklisting URLs and disabling allow_url_fopen are not sufficient to protect your site.
ob_start();
require $filename; // might have to be outside of a function
$html = str_get_html(ob_get_clean());
Alternatively, you could have the AJAX script make its own HTTP request using either file_get_contents() or cURL (specifying an absolute URL, not a filename). Unless you configure your web server otherwise, this internal request would show up in your web server's access log as coming from 127.0.0.1 or your web server's IP address.