Check if file exist in multiple domains - php

I need to check if a file exist in multiple domains/servers and then show the download link to the user or write an error message. I have this script working for 1 domain:
<?php
$domain0='www.example.com';
$file=$_GET['file']
$resourceUrl = 'http://$domain0/$file';
$resourceExists = false;
$ch = curl_init($resourceUrl);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
//200 = OK
if ($statusCode == '200') {
$resourceExists = true;
}
if ($resourceExists == true) {
echo "Exist! $file";
} else {
echo "$file doesnt exist!";
}
?>
Now I need to check if that file exist in 4 domains, how can I do this? I don't know how to use arrays, so maybe if someone explain me ho to do this, I'll be very grateful.

I would create an array for domains
I would loop through the array with "foreach"
I would call a function to get the result
function checkFileOnDomain($file,$domain) {
$resourceUrl = "http://$domain/$file";
$ch = curl_init($resourceUrl);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if($statusCode == '200')
return true;
}
$file=$_GET["file"];
// $_GET should be sanitized!
$domain_list=array("www.test1.com","www.test2.com");
foreach ($domain_list as $domain) {
echo "Check DOMAIN: $domain <hr/>";
if (checkFileOnDomain($file,$domain)) {
echo ">> [ $file ] EXISTS";
} else {
echo ">> [ $file ] DOES NOT EXIST";
}
echo "<br/><br/>";
} unset($domain);
EDIT:
To apply your specifications, you need an extra variable before foreach.
$link_to_file="";
foreach ($domain_list as $domain) {
if (checkFileOnDomain($file,$domain)) {
$link_to_file="$domain/$file";
break; // get first result and quit
}
} unset($domain);
if (!empty($link_to_file)) {
echo $link_to_file; //file is here
} else {
echo "404";
}

An array should solve the problem for you. This creates an array of the domains you want to check, and then cycles through them one by one running the code you wrote.
If you're struggling with arrays, have a look here for some more information
<?php
// Create an array of domains
$domains = ['www.example.com', 'www.example2.com', ...];
// Cycle through all the domains and run the code
foreach($domains as $domain) {
$domain0='www.example.com';
$file=$_GET['file']
$resourceUrl = 'http://$domain0/$file';
$resourceExists = false;
$ch = curl_init($resourceUrl);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$statusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
//200 = OK
if($statusCode == '200') {
$resourceExists = true;
} else if($resourceExists == false) {
}
if ($resourceExists == true) {
echo "Exist! $file";
} else {
echo "$file doesnt exist!";
}
}
?>

Related

Returning results after Post PHP

I have a script that loops through 3 files.
Each file posts data to a api and returns a result, either Accepted or Rejected in variable $result.
On a Accepted response the script stops running and echo out the result.
On a Rejected it echo's out the rejected response and carries on to the next file.
The problem is : Lets say all 3 files give a Rejected reponse , it echo's out 3 rejected responses.
How can i only echo out a single generic response if it does not get a Accepted Response.
foreach($getSeq as $key){
$fileName = $key->file;
include_once 'Lenders/' . $fileName;
if($result == 'Accepted'){
echo 'Accepted';
break;
}
if($result == 'Rejected'){
echo 'Rejected';
}
}
you can do it with array() like below:
<?php
$resultArr = array(); // suppose we insert below Accepted = 1 and Rejected = 0
foreach($getSeq as $key){
$fileName = $key->file;
include_once 'Lenders/' . $fileName;
if($result == 'Accepted'){
echo "Accepted";
$resultArr[] = 1;
break;
}
if($result == 'Rejected'){
$resultArr[] = 0;
}
}
if(!in_array(1, $resultArr)){
echo 'Rejected';
}
Try this, this is specifically for 3 reject response
$failed = 0;
foreach($getSeq as $key){
$fileName = $key->file;
include_once 'Lenders/' . $fileName;
if($result == 'Accepted'){
echo 'Accepted';
break;
}
if($result == 'Rejected'){
$failed++;
}
}
if($failed == 3) {
echo "Rejected";
}
You didn't said if what will happens to other ratio (1A:2R, 2A:1R), so I just created it for 3 rejects

checking header response in PHP for multiple URLs

I am trying to check the header response of multiple URLs at the same time without having a complicated php block.
<?php
$url = array("http://www.simplysup.co.uk/download/dl/trjsetup692.exe");
$headers = get_headers($url);
$response = substr($headers[0], 9, 3);
if ($response != "404") {
echo "PASS";
} else {
echo "FAIL";
}
?>
The above code checks for a single URL at a time. How to perform the same for multiple URLs at the same time? I will also need to trigger an email with the URL when the Header response is 404. Any help would be much appreciated.
I think this could solve your problem.
$fail = false;
$urls = array("http://www.simplysup.co.uk/download/dl/trjsetup692.exe");
foreach ($urls as $url) {
$headers = get_headers($url);
$response = substr($headers[0], 9, 3);
if ($response === "404") {
$fail = true;
}
}
if ($fail) {
echo "FAIL";
} else {
echo "PASS";
}

Multi Curl, error handling

I'm working with multi Curl and was wondering how to handle the errors. I want to check which error occured and if it is an error like, rate limit exceeded I want to crawl that link again after some delay (sleep()). My question: "Is there a build in function which can do this for me or do I need to collect all Urls in an array and just run those again?"
This is what I've got now:
<?php
$urls = array( "https://API-URL.com",
"https://API-URL.com",
"https://API-URL.com",
"https://API-URL.com",
...);
//create the multiple cURL handle
$mh = curl_multi_init();
//Number of elements in $urls
$nbr = count($urls);
// set URL and options
for($x = 0; $x < $nbr; $x++){
// create both cURL resources
$ch[$x] = curl_init();
// set URL and other appropriate options
curl_setopt($ch[$x], CURLOPT_URL, $urls[$x]);
curl_setopt($ch[$x], CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch[$x], CURLOPT_SSL_VERIFYPEER, false);
//add the two handles
curl_multi_add_handle($mh,$ch[$x]);
}
//execute the handles
do {
curl_multi_exec($mh, $running);
} while ($running);
for($x = 0; $x < $nbr; $x++){
$result = curl_multi_getcontent($ch[$x]);
$decoded = json_decode($result, true);
//get info about the request
$error = curl_getinfo($ch[$x], CURLINFO_HTTP_CODE);
//error handling
if($error != 200){
$again[] = array("Url" => $urls[$x], "errornbr" => $error);
} else {
// Here I do what ever I want with the data
}
curl_multi_remove_handle($mh, $ch[$x]);
curl_close($ch[1]);
}
curl_multi_close($mh);
?>
For multiple handles there is
https://www.php.net/manual/en/function.curl-multi-info-read.php
so error check (assuming http connection) should look like:
while ($a = curl_multi_info_read($mh))
{
if ($b = $a['result'])
{
echo curl_strerror($b);# CURLE_* error
}
elseif (!($b = curl_getinfo($a['handle'], CURLINFO_RESPONSE_CODE)))
{
echo 'connection failed';
}
elseif ($b !== 200)
{
echo 'HTTP status is not 200 OK';
}
}
Consider this code as pseudo-code for modern PHPs (i didn't test this exact variant, but scheme will work). Calling curl_errno() on "easy" handles added to "multi" handle will return 0 which is not an error.
In the second for-loop, when you are cycling through the curl handlers to examine what did each curl handler return, I hope, this approach will answer you question
foreach ($ch as $key => $h) {
//This code is actually checking for any error that may occur, whatever that
//error is you can handle it in the if-part of the condition. and save those
//urls to the array $again to call them on a later stage.
if (curl_errno($h)) {
//this is how you will get complete information what did happened to the
//curl handler. And why did it fail. All the inforation will be stored in //error_info.
$again[] = array("Url" =>curl_getinfo($h, CURLINFO_EFFECTIVE_URL), "error_info" => curl_getinfo($h));
}
else{
//here you will handle the success scenario for each curl handler.
$responses[$key] = ['data' => curl_multi_getcontent($h)];
}
//remove curl handler as you are doing in the loop
}

show image based on presence of a URL

I would like to add an image in case a URL is present/active. Ive tried many things myself to make it work but without success.
What I want is: if url1 exist show image1 else nothing, if url2 exist show image2 else nothing, etc.
foreach ($urlsArray as $url) {
if(#fopen($url,'r')){
echo 'Exist';
}
else {
echo 'Doesnt exist';
}
}
Sorry I have to be more specific!
$urlArray = array(
'http://www.domain.com/page1.php' => 'images/image1.jpg',
'http://www.domain.com/page2.php' => 'images/image2.jpg',
etc);
foreach($urlsArray as $url){
if(#fopen($url,'r')){
echo '<img src="$image" />' /* if url1 exist show image1, etc */
}else{
echo '';
}
}
How to get this to work?
assuming that $url = path/to/pic/pic.gif - meaning that url actually leads to a pic to be displayed
foreach ($urlsArray as $url) {
if(#fopen($url,'r')){
echo '<img src="'.$url.'" />';
}
}
updated (use $key => $value for your foreach):
foreach ($urlsArray as $url => $img) {
if(#fopen($url,'r')){
echo '<img src="'.$img.'" />';
}
}
Maybe this will help ?:
<?php
foreach($urlsArray as $url){
if(!empty(file_get_contents($url))){
echo "exist";
}else{
echo "Doesn\'t exist";
}
}
?>
To the extent of my knowledge and past experience fopen for an external URL requires allow_url_fopen to be set to On. Normally it would be disabled as a security measure in deployment environments, suggest using some alternate method like cURL to check the URL is present or not with the http response code returned. Then proceed to show or not show the image based on the response code.
Sample code:
$url_exists_1 = check_url($url1);
if ($url_exists_1) {
// show image 1;
}
else {
// don't;
}
function check_url($url='') {
if (!function_exists('curl_init')) {
die("Please enable curl");
}
$curl_options_array = array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => TRUE,
CURLOPT_FOLLOWLOCATION => TRUE,
CURLOPT_MAXREDIRS => 5
);
if ($url != '') {
$ch = curl_init();
curl_setopt_array($ch, $curl_options_array);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($code == 200) {
return TRUE;
}
else {
return FALSE;
}
}
else {
return FALSE;
}
}

Getting header response code

This is part of a PHP script I am putting together. Basically a domain ($domain1) is defined in a form and a different message is displayed, based on the response code from the server. However, I am having issues getting it to work. The 3 digit response code is all I am interested in.
Here is what I have so far:
function get_http_response_code($domain1) {
$headers = get_headers($domain1);
return substr($headers[0], 9, 3);
foreach ($get_http_response_code as $gethead) {
if ($gethead == 200) {
echo "OKAY!";
} else {
echo "Nokay!";
}
}
}
$domain1 = 'http://google.com';
function get_http_response_code($domain1) {
$headers = get_headers($domain1);
return substr($headers[0], 9, 3);
}
$get_http_response_code = get_http_response_code($domain1);
if ( $get_http_response_code == 200 ) {
echo "OKAY!";
} else {
echo "Nokay!";
}
If you have PHP 5.4.0+ you can use the http_response_code() function. Example:
var_dump(http_response_code()); // int(200)
Here is my solution for people who need send email when server down:
$url = 'http://www.example.com';
while(true) {
$strHeader = get_headers($url)[0];
$statusCode = substr($strHeader, 9, 3 );
if($statusCode != 200 ) {
echo 'Server down.';
// Send email
}
else {
echo 'oK';
}
sleep(30);
}
You directly returned so function wont execute further foreach condition which you written. Its always better to maintain two functions.
function get_http_response_code($domain1) {
$headers = get_headers($domain1);
return substr($headers[0], 9, 3); //**Here you should not return**
foreach ($get_http_response_code as $gethead) {
if ($gethead == 200) {
echo "OKAY!";
} else {
echo "Nokay!";
}
}
}

Categories