I am getting a image source from a URL dynamically, but sometimes the URL returns empty or the image does not exist so i created a PHP function to check if the image source do exist or not so i can display a default image to my users when the image is not accessible.
My concern, is my function enough to catch the data?
My current php function which works when its sure that a image do exist.
function get_image_by_id($ID) {
$url = 'http://proweb/process/img/'.$ID.'.jpg';
if(empty($url)){
return 'default.jpg';
}else{
return $url;
}
}
My index.php
<img src="<?php echo get_image_by_id($ID);?>" />
Here CURL can also be helpful, tested it and working fine. Here we are using curl to get HTTP response code for the URL. If status code is 200 it means it exists.
function get_image_by_id($ID)
{
$url = 'http://proweb/process/img/' . $ID . '.jpg';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
$info = curl_getinfo($ch);
if ($info["http_code"] != 200)
{
return 'default.jpg';
}
else
{
return $url;
}
}
You can use php is_file()to determine.
if (is_file($url) {
//its a file
}
You can use a ternary operator(one liner)
return is_file($url) ? $url : 'default.jpg';
you can use like this
<?PHP
function get_image_by_id($ID) {
$url = 'http://proweb/process/img/'.$ID.'.jpg';
// Checks to see if the reomte server is running
if(file_get_contents(url) !== NULL)
{
return $url;
}
else
{
return 'default.jpg';
}
}
?>
function get_image_by_id($ID) {
if(empty($url)){
$url = 'http://proweb/process/img/default.jpg;
}else{
$url = 'http://proweb/process/'.$ID.'.jpg';
}
return $url
}
Related
I'm trying to create a simple script that'll let me know if a website is based off WordPress.
The idea is to check whether I'm getting a 404 from a URL when trying to access its wp-admin like so:
https://www.audi.co.il/wp-admin (which returns "true" because it exists)
When I try to input a URL that does not exist, like "https://www.audi.co.il/wp-blablabla", PHP still returns "true", even though Chrome, when pasting this link to its address bar returns 404 on the network tab.
Why is it so and how can it be fixed?
This is the code (based on another user's answer):
<?php
$file = 'https://www.audi.co.il/wp-blabla';
$file_headers = #get_headers($file);
if(!$file_headers || strpos($file_headers[0], '404 Not Found')) {
$exists = "false";
}
else {
$exists = "true";
}
echo $exists;
You can try to find the wp-admin page and if it is not there then there's a good change it's not WordPress.
function isWordPress($url)
{
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1 );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
// grab URL and pass it to the browser
curl_exec($ch);
$httpStatus = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
// close cURL resource, and free up system resources
curl_close($ch);
if ( $httpStatus == 200 ) {
return true;
}
return false;
}
if ( isWordPress("http://www.example.com/wp-admin") ) {
// This is WordPress
} else {
// Not WordPress
}
This may not be one hundred percent accurate as some WordPress installations protect the wp-admin URL.
I'm probably late to the party but another way you can easily determine a WordPress site is by crawling the /wp-json. If you're using Guzzle by PHP, you can do this:
function isWorpress($url) {
try {
$http = new \GuzzleHttp\Client();
$response = $http->get(rtrim($url, "/")."/wp-json");
$contents = json_decode($response->getBody()->getContents());
if($contents) {
return true;
}
} catch (\Exception $exception) {
//...
}
return false;
}
so i have this website where people can submit url's for certain items, but I dont know how i can validate that a url was submitted not just some crap!.
Atm i have this piece of code:
if(filter_var('http://www.example.com/test.html', FILTER_VALIDATE_URL)) {
echo 'this is URL';
} else {
echo 'this is no url!';
}
But this piece of code is easy to bypass since it only checks for "http" in the string,
And users will submit "host" separately so i need to check if $host is a valid host.
Thx in advance! you guys rock!
Here is an example that solves your problem :
<?php
$url = "http://www.example.com/test.html";
if (preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&##\/%?=~_|!:,.;]*[-a-z0-9+&##\/%=~_|]/i", $url)) {
echo "URL is valid";
}
else {
echo "URL is invalid";
}
?>
How about sending it an HTTP request?
function isValid($url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_NOBODY, true); //make it a HEAD request
curl_exec($curl);
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return $statusCode == 200;
}
var_dump(isValid('http://www.google.co.uk')); // bool(true)
var_dump(isValid('some invalid URL')); // bool(false)
This question already has answers here:
How can one check to see if a remote file exists using PHP?
(24 answers)
Closed 9 years ago.
I am working around fetch image URL from database & show image in php like following
<?php
$row['blog_url'] = "http://www.nasa.gov/images/content/711375main_grail20121205_4x3_946-710.jpg";
<img src="<?php echo $row['blog_url']; ?>" height="200" width="200" alt="image"/>
?>
but i want display no_imgae.jpeg if image not getting loaded from specified url as blog_url
if there any way to find out image is exist or not in php
thanks in advance...
This function will solve your problem :
function checkRemoteFile($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
// don't download content
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if(curl_exec($ch)!==FALSE)
{
return true;
}
else
{
return false;
}
}
Just pass the image url in this function and it will return yes if image exists otherwise false
$file = "http://www.nasa.gov/images/content/711375main_grail20121205_4x3_946-710.jpg";
$file_headers = #get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}
<?
$img = $row['blog_url'];
$headers = get_headers($img);
if(substr($headers[0], 9, 3) == '200') {
?>
<img src="<?php echo $img; ?>"/>
<?
} else {
?>
<img src="noimage.jpg"/>
<?
}
?>
I am writing a PHP program that downloads a pdf from a backend and save to a local drive. Now how do I check whether the file exists before downloading?
Currently I am using curl (see code below) to check and download but it still downloads the file which is 1KB in size.
$url = "http://wedsite/test.pdf";
$path = "C:\\test.pdf;"
downloadAndSave($url,$path);
function downloadAndSave($urlS,$pathS)
{
$fp = fopen($pathS, 'w');
$ch = curl_init($urlS);
curl_setopt($ch, CURLOPT_FILE, $fp);
$data = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
echo $httpCode;
//If 404 is returned, then file is not found.
if(strcmp($httpCode,"404") == 1)
{
echo $httpCode;
echo $urlS;
}
fclose($fp);
}
I want to check whether the file exists before even downloading. Any idea how to do it?
You can do this with a separate curl HEAD request:
curl_setopt($ch, CURLOPT_NOBODY, true);
$data = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
When you actually want to download you can use set NOBODY to false.
Call this before your download function and it's done:
<?php function remoteFileExists($url) {
$curl = curl_init($url);
//don't fetch the actual page, you only want to check the connection is ok
curl_setopt($curl, CURLOPT_NOBODY, true);
//do request
$result = curl_exec($curl);
$ret = false;
//if request did not fail
if ($result !== false) {
//if request was ok, check response code
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($statusCode == 200) {
$ret = true;
}
}
curl_close($curl);
return $ret;
}
?>
Since you are using HTTP to fetch a resource on the internet, what you really want to check is that the return code is a 404.
On some PHP installations, you can just use file_exists($url) out of the box. This does not work in all environments, however. http://www.php.net/manual/en/wrappers.http.php
Here is a function much like file_exists but for URLs, using curl:
<?php function curl_exists()
$file_headers = #get_headers($url);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}
} ?>
source: http://www.php.net/manual/en/function.file-exists.php#75064
Sometimes the CURL extension isn't installed with PHP. In that case you can still use the socket library in the PHP core:
<?php function url_exists($url) {
$a_url = parse_url($url);
if (!isset($a_url['port'])) $a_url['port'] = 80;
$errno = 0;
$errstr = '';
$timeout = 30;
if(isset($a_url['host']) && $a_url['host']!=gethostbyname($a_url['host'])){
$fid = fsockopen($a_url['host'], $a_url['port'], $errno, $errstr, $timeout);
if (!$fid) return false;
$page = isset($a_url['path']) ?$a_url['path']:'';
$page .= isset($a_url['query'])?'?'.$a_url['query']:'';
fputs($fid, 'HEAD '.$page.' HTTP/1.0'."\r\n".'Host: '.$a_url['host']."\r\n\r\n");
$head = fread($fid, 4096);
$head = substr($head,0,strpos($head, 'Connection: close'));
fclose($fid);
if (preg_match('#^HTTP/.*\s+[200|302]+\s#i', $head)) {
$pos = strpos($head, 'Content-Type');
return $pos !== false;
}
} else {
return false;
}
} ?>
source: http://www.php.net/manual/en/function.file-exists.php#73175
An even faster function can be found here:
http://www.php.net/manual/en/function.file-exists.php#76246
In the first example above $file_headers[0] may contain more than or something other than 'HTTP/1.1 404 Not Found', e.g:
HTTP/1.1 404 Document+%2Fdb%2Fscotbiz%2Freports%2FR20131212%2Exml+not+found
So it's important to use some other test, e.g., regex, as '==' is not reliable.
I wanted to ask you help I have an xml source (http://livefmhits.6te.net/nowplay.xml) it gives me the source of the song and I wanted to remove the cover through the lastfm (artist.getinfo) in echo I tried as follows:
<?php
$xml = simplexml_load_file('http://livefmhits.6te.net/nowplay.xml');
$artist = urlencode($xml->TRACK["ARTIST"]);
$url = 'http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist='.$artist.&api_key=b25b959554ed76058ac220b7b2e0a026;
$xml2 = #simplexml_load_file($url);
if ($xml2 === false)
{
echo("Url failed"); // do whatever you want to do
}
else
{
if($xml2->track->album->image[3])
{
echo '<img src="';
echo((string) $xml2->track->album->image[3]);
echo '">';
}
else
{
echo "<img src='http://3.bp.blogspot.com/-SEsYAbASI68/VZ7xNuKy-GI/AAAAAAAAA3M/IWcGRDoXXms/s1600/capaindisponivel.png'"; // do whatever you want to do
}
}
I'm not able to extract the source must be wrong echo, I like to remove the image that says "mega". I present to you the complete link
http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&lang=ru&artist=COLDPLAY&api_key=ae9dc375e16f12528b329b25a3cca3ee and yet I was to do a post yours but I could not (Get large artist image from last.fm xml (api artist.getinfo))
I came to ask your help in this work from the outset thanks for availability
Here is how I'm doing it in json. It's pretty much the same in XML.
First, we define the API KEY:
define('YOUR_API_KEY', 'b25b959554ed76058ac220b7b2e0a026');
It's better to separate it from the code, it makes things easier if you need to reuse it somewhere else in your code. (for eg. in another function)
Then, we create the 2 functions we need to make the magic happen.
1) To query Lastfm's API and get its content, we will use CURL:
function _curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
if(strtolower(parse_url($url, PHP_URL_SCHEME)) == 'https')
{
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,1);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,1);
}
curl_setopt($ch, CURLOPT_URL, $url);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
2) Lastfm offers many options. Personally, I find it's easier to separate main queries into functions. But as you simply target images, here is the function I'd use:
function lfm_img($artist)
{
$url = "http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist=$artist&api_key=".YOUR_API_KEY."&format=json";
$json = _cul($url);
$data = str_ireplace("#text", "text", $json);
$list = json_decode($data);
//If an error occurs...
if($list->error)
return 'ERROR.'. $list->error;
//That's where we get the photo. We try to get the biggest size first, if not we try smaller sizes. Returns '0' if nothing is found.
if($list->artist->image[4])
$img = $list->artist->image[4]->text;
else if($list->artist->image[3])
$img = $list->artist->image[3];
else if($list->artist->image[2])
$img = $list->artist->image[2];
else if($list->artist->image[1])
$img = $list->artist->image[1];
else if($list->artist->image[0])
$img = $list->artist->image[0];
else
$img = 0;
return $img;
}
And finally, use them:
$artist_query = 'Nirvana';
$artist_image = lfm_img($artist);
//display image
echo '<img src="'. $artist_image .'" alt="'. $artist_query .'" />';
I think it's self explanatory here. ;)
Hope it helped!