I'm trying to grab an svg file with php and output it onto a page. Site is built on Wordpress.
<?php
echo file_get_contents("site.com/wp-content/themes/oaklandcentral/img/fb_logo.svg");
?>
Nothing is displaying. The actual link is correct and goes directly to the svg. Any thoughts?
Path is wrong, use file_get_contents( get_template_directory() . '/img/fb_logo.svg' )
echo file_get_contents("site.com/wp-content/themes/oaklandcentral/img/fb_logo.svg");
Assumptions:
your "filename" string starts with the protocol e.g. "http://"
that you can access the file directly from a browser (i.e. not a
file/folder permissions issue);
that file_get_contents is returning FALSE? (does the E_WARNING tell
you anything?)
I recollect seeing that some servers are not configured to allow file_get_contents (or readfile with URLs) so I would check investigate this first (maybe allow_url_fopen in php.ini???).
If this is not the case (or is a limitation by host provider) and you cannot find the cause of the problem then CURL should work (on most servers!).
$url = 'http://example.com/path-to/fb_logo.svg';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_URI']);
$svg = curl_exec($ch);
curl_close($ch);
echo $svg;
Edit:
It also appears you could also use php include if you remove the xml header tag from your SVG file.
I assume you want to display the SVG image not its text code, in which case why not simply <img src="<?php echo $mySvgFileUrl"; ?>"> like any other image?
Add header using: header("Content-Type: image/svg+xml"); before you echo the svg. sometimes the browser assumes the data received is html by default.
What could possibly be the problem.
The file isn't where you think it is.
File permission isn't allowing the code to read the file.
Try to debug:
<?php
$file = "site.com/wp-content/themes/oaklandcentral/img/fb_logo.svg";
if ( file_exists($file) ) {
echo file_get_contents($file);
} else {
echo "File $file does not exist";
}
?>
Try to get the page with curl. Take a look at the headers and the raw https response.
curl -v URL_TO_PAGE
Try:
<?php echo file_get_contents(get_template_directory().'/theme/img/chevron-right-solid.svg'); ?>
this seemed to work for me, where using get_template_directory_uri() did not (it threw an OpenSSL error)
Then, you can target the SVG and style how you wish.
For example:
<button class="btn btn-primary">
<?php echo file_get_contents(get_template_directory().'/theme/img/chevron-right-solid.svg'); ?>
</button>
CSS might be:
.btn svg { line-height: 1.2; max-height: 1rem;}
Try to use below code.
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
$file = file_get_contents('site.com/wp-content/themes/oaklandcentral/img/fb_logo.svg', false, $context);
Related
I want to get the whole element <article> which represents 1 listing but it doesn't work. Can someone help me please?
containing the image + title + it's link + description
<?php
$url = 'http://www.polkmugshot.com/';
$content = file_get_contents($url);
$first_step = explode( '<article>' , $content );
$second_step = explode("</article>" , $first_step[3] );
echo $second_step[0];
?>
You should definitely be using curl for this type of requests.
function curl_download($url){
// is cURL installed?
if (!function_exists('curl_init')){
die('cURL is not installed!');
}
$ch = curl_init();
// URL to download
curl_setopt($ch, CURLOPT_URL, $url);
// User agent
curl_setopt($ch, CURLOPT_USERAGENT, "Set your user agent here...");
// Include header in result? (0 = yes, 1 = no)
curl_setopt($ch, CURLOPT_HEADER, 0);
// Should cURL return or print out the data? (true = retu rn, false = print)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
// Download the given URL, and return output
$output = curl_exec($ch);
// Close the cURL resource, and free system resources
curl_close($ch);
return $output;
}
for best results for your question. Combine it with HTML Dom Parser
use it like:
// Find all images
foreach($output->find('img') as $element)
echo $element->src . '<br>';
// Find all links
foreach($output->find('a') as $element)
echo $element->href . '<br>';
Good Luck!
I'm not sure I get you right, But I guess you need a PHP DOM Parser. I suggest this one (This is a great PHP library to parser HTML codes)
Also you can get whole HTML code like this:
$url = 'http://www.polkmugshot.com/';
$html = file_get_html($url);
echo $html;
Probably a better way would be to parse the document and run some xpath queries over it afterwards, like so:
$url = 'http://www.polkmugshot.com/';
$xml = simplexml_load_file($url);
$articles = $xml->xpath("//articles");
foreach ($articles as $article) {
// do sth. useful here
}
Read about SimpleXML here.
extract the articles with DOMDocument. working example:
<?php
$url = 'http://www.polkmugshot.com/';
$content = file_get_contents($url);
$domd=#DOMDocument::loadHTML($content);
foreach($domd->getElementsByTagName("article") as $article){
var_dump($domd->saveHTML($article));
}
and as pointed out by #Guns , you'd better use curl, for several reasons:
1: file_get_contents will fail if allow_url_fopen is not set to true in php.ini
2: until php 5.5.0 (somewhere around there), file_get_contents kept reading from the connection until the connection was actually closed, which for many servers can be many seconds after all content is sent, while curl will only read until it reaches content-length HTTP header, which makes for much faster transfers (luckily this was fixed)
3: curl supports gzip and deflate compressed transfers, which again, makes for much faster transfer (when content is compressible, such as html), while file_get_contents will always transfer plain
How can i show an image from a server with standard http protection without showing the authentication window?
I now use standard html
<img src="...">
but because the image is protected this asks for an authentication window. I do have the login data, how can i show the image?
Regards, Tom.
This should work. Simply replace the username and password with your authentication details. (Warning: Doesn't work in all browsers)
<img src="http://username:password#server/Path" />
I would recommend putting this in a separate file on your server. That way you can reference it without exposing the authentication info.
I used IrishGeeks tip to get a solution. It works on all browsers. The script.php is
<?php
$url = $_GET['url'];
$c = curl_init($url);
$authString = 'user:pass';
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_USERPWD, $authString);
$content = curl_exec($c);
$contentType = curl_getinfo($c, CURLINFO_CONTENT_TYPE);
header('Content-Type:'.$contentType);
print $content;
?>
Then use
<?php
print '<img src="script.php?url='.urlencode('http://www.example.com/image.bmp').'" />';
?>
To get the image.
I have two domains sharing the same server. One of them, site_1.com, holding images at directory /images and the other one site, site_2.com, must to show those images. I have the following code at site_2:
<html>
<body>
<img src="http://site_1.com/images/img.png" />
</body>
</html>
Result: It didn't work. After reading a lot of answers and comment here and other forums I applied their sugges of using for example an api at site_1 like this:
/api/get_image.php at site_1.com:
<?php
$file_name = $_GET['file_name'];
$url = 'http://site_1.com/images/'.$file_name;
header('Content-type: image/png');
imagepng(imagecreatefrompng($url));
?>
And call the api at site_2.com like this:
<html>
<body>
<img src='http://site_1.com/api/get_image.php?file_name='img.png' />
</body>
</html>
It didn't work.
Another way using file_get_contens():
<?php
$file_name = $_GET['file_name'];
$url = 'http://site_1.com/images/'.$file_name;
$img = file_get_contents($url) ;
echo $img ;
?>
It didn't work.
Another way using CURL library:
<?php
$file_name = $_GET['file_name'];
$url = 'http://site_1.com/images/'.$file_name;
//
$ch = curl_init();
$timeout = 0;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$image = curl_exec($ch);
curl_close($ch);
echo $image ;
?>
It didn't work.
It's problably that I'm doing something wrong but I don't know what is. By the way, allow_url_fopen is ON and may be I have to active some other flag in some configuration file of apache or php. Please, could anybody tell me where is the problem? I appreciate any help.
sharing the same server.
Put images to some shared folder (i.e. both users for site_1 and site_2 can have access to it) and create symlinks to public folders of both sites
If you want to use your solution I think you should send appropriate header, e.g. header('Content-type: image/jpg');
header('Content-Type: image/'.$fileType);
readfile($filePath);
I would like to have code for an image that counts the number of times the image is viewed, regardless of what site the image is found on. I want to use the img src tag, and have src point to a php page that counts that view and then returns the image to be viewed. I was thinking something like this:
<img src="www.mywebsiteurl.com/something.php" />
How would I go about writing "something.php" so that it returns the proper image file? I know how to record the page view, but if I must do something different in this case, please tell me.
Your script needs to:
Record the hit.
Set the content type of the output ( header('Content-Type: image/jpeg'); )
Output the image ( readfile( $path_to_image ) );
For examples, please see the readfile documentation and Output an Image in PHP.
Loading images / files from php is slow than normal loading files.
Main cons:
Images can't be cached due to dynamic query most browser dont support on dynamic queries.
Overhead on sever and apache both.
If you use database and want to increment column after image loads than a person can load your image again and again. So you need to use conditions on every query.
Alternative Solution
Enter this code in footer of page on which you want to show images
A ajax call
$.get("inc_img_view.php?img_id="+<?php echo $img_id; ?>);
This is the most barebones version you can have:
<?php
header('Content-type: image/jpeg');
readfile('somepic.jpg');
You can call an image using a URL similar to: www.mywebsiteurl.com/image_renderer.php?url=url_to_image.
image_rendered.php:
<?php
header("Content-Type: image/jpeg");
$url = urldecode($_GET['url']);
$headers = array(
"GET ".$url." HTTP/1.1",
"Content-Type: text/xml; charset=UTF-8",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache"
);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
$r = curl_exec($ch);
// you can connect to your database and increment the number of times this image was viewed
echo $r;
?>
Hope this will point you into the right direction.
Yes you're on a good start.
I'd do something like this
<img src="www.mywebsiteurl.com/image_counter.php?src=image.jpg" />
In image_counter.php, take $src = $_GET['src'] for image source.
Then +1 the hit for that image in the database.
Then do
header('Content-type: image/jpeg');
readfile($src);
Something like this should work:
<?php
$file = $_GET['img'];
$path = "images/";
// do an increment of views on the image here - probably in a database?
$exifImageType = exif_imagetype($path.$file);
if ($exifImageType !== false) {
$type = image_type_to_mime_type($exifImageType);
}
header('Content-Type: $type');
echo file_get_contents($path.$file);
Note: this would make something like:
<img src="getimage.php?img=image.jpg" />
show the correct image after incrementing the views.
You could always add some .htaccess to make all calls to /images/anything go through your image file. It'd mean you could keep the URL looking as though it's getting an actual image file (e.g. /images/logo.jpg would be re-written to actually go through getimage.php?img=logo.jpg)
I need to get the complete output from an aspx site. When the user leaves I will save what's in some specific elements in cookies. The problem is that the aspx is on a domain I don't have access to. I want the output to behave as in an iframe so links need to be clickable but it won't leave my page.
I think of either AJAX with PHP-proxy or an iframe that I can modify content in.
Is this possible?
If it is possible and it involves server-side code I would like to know if there are any free web hosts that support the full code( for example almost every free web host has safe_mode on for PHP).
EDIT: I want to display this page : School scheme. The URL doesn't to change, it just sends requests to the server (think via JavaScript). When the user leaves I will see what's in the select box id="TypeDropDownList" and what's in the select box id="ScheduleIDDropDownList".
When the user returns to my page I will print those values to the page via URL like this "http://www.novasoftware.se/webviewer/(S(lv1isca2txx1bu45c3kvic45))/design1.aspx?schoolid=27500&code=82820&type=" + type + "&id=" + id + "
I tried several php proxy scripts on 000webhost before I posted here.
for example this :
<?php
ob_start();
function logf($message) {
$fd = fopen('proxy.log', "a");
fwrite($fd, $message . "\n");
fclose($fd);
}
?>
<?
$url = $_REQUEST['url'];
logf($url);
$curl_handle = curl_init($url);
curl_setopt($curl_handle, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, "Owen's AJAX Proxy");
$content = curl_exec($curl_handle);
$content_type = curl_getinfo($curl_handle, CURLINFO_CONTENT_TYPE);
curl_close($curl_handle);
header("Content-Type: $content_type");
echo $content;
ob_flush();
?>
But it returns Warning: curl_setopt(): supplied argument is not a valid cURL handle resource in /home/a5379897/public_html/ajax-proxy.php on line 16
I tried to contact them about this because they say they have cURL enabled but they haven't responded yet.
I think it would be possible to just display the two select boxes when the user first visit the page. When options is selected it will make an iframe show the right page by passing "http://www.novasoftware.se/webviewer/(S(lv1isca2txx1bu45c3kvic45))/design1.aspx?schoolid=27500&code=82820&type=" + type + "&id=" + id + " to the src attribute.
The problem with that is that I will need to retrieve the select boxes someway and I will have the same problem.
You would need to use PHP as Javascript doesn't doesn't allow cross domain requests. Your PHP code would literally grab the page the client wants, process it (changing link's href to your page with a get variable of the page the original href links to). When they click the link they will be sent to the same page they are on now but the page will grab the new page and return that(processing that page too) and so on.
000webhost are a nice free webhost that allow you to do most of PHP's functions and don't put adverts on your site.
To get the whole aspx output as a string to manipulate, you can use file_get_contents(http://yoursite.com/yourpage.aspx);
For best results, open a stream as the context via http.
<?php
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
?>
Thanks to greg I could create this script that gets the page.
<html>
<head>
</head>
<body>
<?php
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
$host = 'http://www.novasoftware.se/webviewer/(S(bkjwdqntqzife4251x4sdx45))/';
$url = '/design1.aspx?schoolid=27500&code=82820&type=3&id={7294F285-A5CB-47D6-B268-E950CA205560}';
$changetothis='src="'.$host;
// Open the file using the HTTP headers set above
$file = file_get_contents($host.$url, false, $context);
$changed = str_replace('src="', $changetothis,$file);
echo $changed;
?>
</body>
</html>