Hi I am basically trying to fetch a page via php, get its html and change the html(to highlight some keywords) to a bit and display it as a overlay in my page(jquery).
//My php page data.php
<?php
$html= file_get_contents($_GET['url']);
echo $html;
?>
//My jquery ajax request to data.php from page main.html
function test()
{
$.ajax({
type: 'GET',
url: 'data.php',
data: 'url=http://www.developphp.com/view_lesson.php?v=338',
cache: false,
success: function(result)
{
$("#overlay").append(result);
}
});
}
}
As you can see, since the webpage uses relative URL, I am having issues displaying it in a overlay. I tried searching for a way to convert relative to absolute but did not find anything useful. Can you guys please point me in the right way?
Can start here
function test(){
var domain='http://www.developphp.com/', path= 'view_lesson.php?v=338';
$.ajax({
type: 'GET',
url: 'data.php',
data: { url: domain + path},
cache: false,
success: function(result)
{
var $html=updatePaths( $(result) );
$("#overlay").append($html);
}
});
}
function updatePaths( $html, domain){
/* loop over all images and adjust src*/
$html.find('img').attr(src,function(i, src){
if(src.indexOf(domain) ==-1){
src= domain+src
}
return src;
})
/* return updated jQuery object*/
return $html;
}
This will only work for simplest case where remote site isn't using a variation of the domain you use like not using www and you do. Also won't work if image paths are set usng ../ to move up a directory.
You would have to create a far more robust set of tests to manipulate the final path you use correctly.
My intent was to show you how to manage situation
I ilke #charlietfl's solution. However, somehow I think it gives more sense to manipulate the scraped content serverside before passing it to the client. You can do that by using DomDocument.
The following code converts all <img> src relative paths to absolute paths before echoing the result. Use the same approch for the <a> tags href attributes and so on,
error_reporting(0); //suppress DOM errors
$basePath='http://www.developphp.com/'; //use parse_url to get the basepath dynamically
$content=file_get_contents('http://www.developphp.com/view_lesson.php?v=338');
$dom=new DomDocument();
$dom->loadHTML($content);
$images = $dom->getElementsByTagName('img');
foreach ($images as $image) {
$src=$image->attributes->getNamedItem("src")->value;
if (strpos($basePath, $src)<=0) {
$image->attributes->getNamedItem("src")->value=$basePath.$src;
}
}
echo $dom->saveHTML();
With all your help, I did something like this,
Instead of trying to replace the relative by absolute path, I appended the base url html tag to the scrapped content.
<?php
include 'URL2.php';
error_reporting(0); //suppress DOM errors
$content=file_get_contents($_GET['fullURL']); //http://somewebsite.com/page1.html
$url = new Net_URL2($_GET['fullURL']);
$baseURL= $url->host; //http://somewebsite.com
if(strpos($baseURL,'http://')<0)
{
$baseURL='http://'.$baseURL;
}
$dom=new DomDocument();
$dom->loadHTML($content);
$head = $dom->getElementsByTagName('head')->item(0);
$base = $dom->createElement('base');
$base->setAttribute('href',$_GET['baseURL']);
if ($head->hasChildNodes()) {
$head->insertBefore($base,$head->firstChild);
} else {
$head->appendChild($base);
}
echo $dom->saveHTML();
?>
Related
I'm trying to use a free translation server (this is offered by someone else) for my website that returns the translation of what is at the end of the URL. For example typing this url will return a translation in English
http://www.edrdg.org/cgi-bin/wwwjdic/wwwjdic.cgi?1ZUQ%E7%BF%BB%E8%A8%B3
My question is how can I capture the output of this url using html/php/javascript/ajax without having my webpage leave my site.
So far I have tried creating a function which is put into the tag of my html
<script>
function foo()
{
var translation;
$.get('http://www.edrdg.org/cgi-bin/wwwjdic/wwwjdic.cgi?1ZUQ%E7%BF%BB%E8%A8%B3', function(data)
{
translation = data;
}
}
</script>
and trying to call it like this
<div>
<p><?php echo foo(); ?></p>
</div>
To me this looks terrible and doesn't work so my main question is how to capture what that URL gives me and also how can I store that data and display it on my html? Thanks.
You're trying to use JavaScript function from PHP. Of course it won't work. JavaScript is executed in browser and PHP is executed on server.
The easiest way to get data from URL in php is to use file_get_contents:
<div>
<p>
<?php
echo file_get_contents('http://www.edrdg.org/cgi-bin/wwwjdic/wwwjdic.cgi?1ZUQ%E7%BF%BB%E8%A8%B3');
?>
</p>
</div>
file_get_contents will work fine for this particular case since the page is just text content, but I'd use a combination of CURL and XPath in the event you want to grab some nodes values without any wrapping html.
PHP curl.php
<?php
$url = $_REQUEST['url'];
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
$html = curl_exec($curl);
curl_close($curl);
$dom = new DOMDocument();
libxml_use_internal_errors(true);
$dom->loadHTML($html);
libxml_clear_errors();
$xpath = new DOMXPath($dom);
// Find stuff
$result = $xpath->query("/html/body/pre");
$data = array();
if (!is_null($result)) {
foreach ($result as $key => $element) {
$nodes = $element->nodeValue;
$data[$key] = $nodes;
}
}
print_r($data[0]);
?>
JavaScript/jQuery
$.ajax({
url: 'curl.php',
type: 'POST',
data: {
url: 'http://www.edrdg.org/cgi-bin/wwwjdic/wwwjdic.cgi?1ZUQ%E7%BF%BB%E8%A8%B3'
},
})
.done(function (data) {
$('body').append(data);
})
.fail(function (data) {
console.log("error", data);
})
So I'm making a website for a client, and the client has tons of photos from tons of different bands they photographed in the 80s and 90s that they would like to try and sell.
Instead of making a page for each band (theres over 100) like the previous site did, I am trying to make one page that uses Javascript/PHP to change the image directory to that band when the text for that band is clicked.
So far, I am able to use a PHP function to find photos in the slideshow folder, but I have been unable to update this function to search through a sub directory in the slideshow folder. (For example, when 'Metallica' is clicked, I empty #imageGal, and then I would like to append all the new metallica images from the metallica folder to the gallery).
My PHP code is:
<?php
$imagesDir = '';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
echo json_encode($images);
?>
This PHP code seems to work great.
I get the images using this JQuery code:
$('#imageGal').empty();
$.ajax({
url: "slideshow/getimages.php",
dataType: 'json',
success: function(json){
for(var i=0;i<json.length;i++){
$('#imageGal').append('<img src="slideshow/' + json[i] + '">');
}
}, failure: function(json){
alert('Something went wrong. Please try again.');
}
});
When a user clicks on a band (ie Metallica), this code is executed.
$('.options').mousedown(function() {
var name = $(this).attr('id');
//$('#output').html(name);
$.ajax({
type: "POST",
url: "slideshow/getimages.php",
data: {
imageDir: name
}, success: function(msg){
alert( "Data Saved: " + msg );
}
});
$('#imageGal').empty();
$.ajax({
url: "slideshow/getimages.php",
dataType: 'json',
success: function(json){
for(var i=0;i<json.length;i++){
$('#imageGal').append('<img src="slideshow/' + json[i] + '">');
}
}, failure: function(json){
alert('Something went wrong. Please try again.');
}
});
});
I am unable to get the $imagesDir variable to change, but if I were to manually enter "Metallica" in $imagesDir = "Metallica" variable, it loads those images perfectly.
Can anyone offer any help/advice? I've been at this for a many hours now. Thanks for anything!
Unless you have register_globals on then you need to reference the variable through the global $_POST array. $_POST['imagesDir'] instead of $imagesDir.
However I would state in it's current form it would be a very bad idea to simply replace it as someone could attempt to exploit your code to list any directory on the server.
You should append the parent directory to prevent an exploit. Something like this:
EDIT you have to chdir() to the path before glob will work. I've updated my code below.
<?php
$imagesDir = $_SERVER['DOCUMENT_ROOT']; // this is the root of your web directory
$images = array();
// and this line ensures that the variable is set and no one can backtrack to some other
// directory
if( isset($_POST['imagesDir']) && strpos($_POST['imagesDir'], "..") === false) {
$imagesDir .= "/" . $_POST['imagesDir'];
chdir($imagesDir);
$images = glob('*.{jpg,jpeg,png,gif}', GLOB_BRACE);
}
echo json_encode($images);
?>
I'm not an ajax expert but you seem to be posting imageDir.
So your PHP code should be looking for $_POST['imageDir'].
<?php
$imagesDir = $_POST['imageDir'];
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
echo json_encode($images);
?>
Does this solve it?
PHP
<?php
$deleteImage = null;
if(isset($_POST["deleteImage"])){$deleteImage = $_POST["deleteImage"];}
unlink($deleteImage);
?>
I'm sending $deleteImage to the php page via ajax.and I got following
Jquery response OUTPUT
$deleteImage = '../pard_media/Upload/upload/23.jpg';
There is a image called 23.jpg in my upload directory. but images does to delete .Do i want to add absolute path to delete the image ?
My AJAX
$.ajax({
url: "../pard_media/Upload/delete.php",
type: "POST",
data: "deleteImage=" + data,
success: function (response) {
alert(response);
}
});
It's better, also safety wise to use an absolute path. But you can get this path dynamically.
E.g. using:
getcwd();
Depending on where your PHP script is, your variable could look like this:
$deleteImage = getcwd() . '/upload/23.jpg';
I have a PHP script that loads XML content dynamically:
require_once 'directory/directory/';
$nice= '1149632';
$key = 'adf995jdfdfddda44rfg';
$mixer = new Live_Products($key);
$result = $mixer->product($nice)
->show(array('name','Price'))
->query();
echo $result
This will work fine when it is loaded. But I am trying to use an ajax/jquery script to send the value $nice to the PHP script; and to ultimately send the result back from the dynamically created XML file. I've been trying to figure this out for hours
Here is the ajax Script
function sendValues() {
$("$nice")
$.ajax({
url: "/myphp.php",
data: {str}
cache: false
});
}
Has anybody done something similar to this concept?
Why not pass it as a GET param like so...
jQuery
function sendValues(something) {
$.ajax({
url: "/myphp.php?nice=" + something,
cache: false,
dataType: 'xml',
success: function(xml) {
// Work with the XML
}
});
}
PHP
require_once 'directory/directory/';
$nice= '1149632';
$key = 'adf995jdfdfddda44rfg';
$mixer = new Live_Products($key);
$result = $mixer->product($_GET['nice'])
->show(array('name','Price'))
->query();
// You said it is XML?
header('Content-Type: text/xml');
echo $result;
I'm looking for a php script server side that load an image in a div on client side.
first shot:
ajax.php
if((isset($_POST['id'])) && ($_POST['id']=="loadphoto") && (ctype_digit($_POST['idp']))) {
$query=mysql_query("SELECT articleid, photoid FROM articles_photos WHERE id='".$_POST['idp']."'", $mydb);
if(mysql_num_rows($query)!=0){
while($row=mysql_fetch_array($query, MYSQL_NUM)) {
$path="./articles/photos/".$row[0]."/".$row[1];
}
echo $path;
}
}
myjs.js
function loadPhoto(mexid) {
$.ajax({
type: 'POST',
cache: false,
url: './auth/ajax.php',
data: 'idp='+escape(mexid)+'&id=loadphoto',
success: function(msg) {
$('.articleviewphoto1').find("img").each(function(){
$(this).removeClass().addClass('photoarts');
});
$('#'+mexid).removeClass().addClass('photoartsb');
$('#visualizator').html('<img src="'+msg+'" class="photoartb" />');
}
});
return false;
}
Are you looking to host a list of possible images in the PHP file and load different images based on the id you send? If so, you can set:
$Img = $_POST['idp'];
And use a switch statement to pass back the image file path:
switch ($Img){
case (some_value):
echo 'images/some_file.jpg';
break;
case (another_value):
echo 'images/another_file.jpg';
break;
}
Then place the file path in an tag and load that into $('#visualizator').html();
Am I on track at least with what you want? If so, I can flesh the answer out a bit.
I'm assuming the image already exists somewhere and isn't being generated on the fly. In the PHP script, you can access the variables with $_POST['idp'] and $_POST['id']. Do whatever processing you need, and then simply echo the URL. The variable msg in the javascript will be everything echo'd by the PHP script. Then, you could just do this:
$('#visualizator').html('<img src="' + msg + '" />');