Validate links with php - php

Can anyone tell me if its possible to validate a link with php? By validate, I mean check if the link is active and works not just the actual format of the link.

You need to do a HEAD request and check the response. 200 indicates the request succeeded. There are others that can be found here that you may want to treat as valid. (301 and 302 redirects spring to mind)
If you use cURL, you could use something like this
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, TRUE); //Include the headers
curl_setopt($ch, CURLOPT_NOBODY, TRUE); //Make HEAD request
$response = curl_exec($ch);
if ( $response === false ){
//something went wrong, assume not valid
}
//list of status codes you want to treat as valid:
$validStatus = array(200, 301, 302, 303, 307);
if( !in_array(curl_getinfo($ch, CURLINFO_HTTP_CODE), $validStatus) ) {
//the HTTP code is not valid. The url is not valid
}
curl_close($ch);

Related

cURL taking long time to get the final URL of redirect URL

Below code snippet is to get the final URL(which has media/zip/rar file) from redirect URL by using cURL. It gets the final URL, no doubt about it, but what it does is according to the size of file it varies in time to get URL.
Suppose file at final URL is 1MB, it will take around 5sec to retrieve. But if the file is about 35MB, it takes time about 150 sec. I think cURL is downloading result and finally fetching the URL from result.
<?php
echo get_rurl("x_url");//1.2MB -> 5-10sec
//echo get_rurl("y_url");//31.6MB -> 150sec
function get_rurl($url){
// initialize cURL
$curl = curl_init($url);
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
));
// execute the request
$result = curl_exec($curl);
// fail if the request was not successful
if ($result === false) {
curl_close($curl);
return null;
}
// extract the target url
$redirectUrl = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
curl_close($curl);
return $redirectUrl;
}
?>
i cant use file_get_content() because i just want to get the final URL from given redirect URL.
So in short - how to get the final URL from redirect URL without downloading results.
Hope i make it clear. Any help will be appreciated.
This works fine with CURLINFO_EFFECTIVE_URL, but for it the option CURLOPT_FOLLOWLOCATION must set to TRUE. This is on the grounds that CURLINFO_EFFECTIVE_URL returns precisely what it says, the effective url that ends up getting loaded. If the CURLOPT_FOLLOWLOCATION=False then the effective url will be requested url, else it will be final url that is redirected to.
I did this using curl_getinfo. which gives me information regarding the last transfer
<?php
echo get_rurl("xurl");
//echo get_rurl("yurl");
function get_rurl($url){
// initialize cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); //specify your URL
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); //disable follow redirects
$http_data = curl_exec($ch); //hit the $url
$curl_info = curl_getinfo($ch);
return $curl_info['redirect_url'];// extract final url
}
?>
or
Even you can use CURLINFO_REDIRECT_URL or CURLINFO_EFFECTIVE_URL depending upon your use cases. refer here
<?php
echo get_rurl("xurl");
//echo get_rurl("yurl");
function get_rurl($url){
// initialize cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url); //specify your URL
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false); //disable follow redirects
$http_data = curl_exec($ch); //hit the $url
return curl_getinfo($ch, CURLINFO_REDIRECT_URL);
}
?>
Hope this helps to others users too.
According to the documentation of libcurl (https://curl.haxx.se/libcurl/c/CURLOPT_FOLLOWLOCATION.html), this is exactly as is expected when using CURLOPT_FOLLOWLOCATION => true,. You probably want to change this to false.

How can I check if an image/link exist on a page with php?

I'm goging to design benners and stuff for people and then I'll give them an image to put their profiles. I want to make a page on my localhost to check if image exist on their profile. Basically I want to see if "example1.com/myimg.jpg" exist on "example2.com/theirprofile".
I want to see if the image exists on an external page.
I don't have much experience with php. Is it possible to do sometihng like this?
This is what I usually do:
The idea is to make a cURL request just to check the result. If it's 200 then the resource exists.
function externalResourceExists($url) {
$ch = curl_init($url); //$url is the url you need to check
curl_setopt($ch, CURLOPT_NOBODY, true); //Don't get the body, we don't need it.
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_exec($ch);
$retcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $retcode == 200;
}
Then check if the function returns true.

Get last available URL

I am using an API to get the users profile picture. The call looks something like this
https://familysearch.org/platform/tree/persons/{$rid}/portrait?access_token={$_SESSION['fs-session']}&default=https://eternalreminder.com/dev/graphics/{$default_gender}_default.svg
This link only works for about an hour because the user's session token expires then. I was wondering if there was any way to retrieve the last returned returned URL, which would be the direct link to the image, so I could store that in a database.
I have tried Google but I don't really know where to start.
Thanks in advance!
I was able to solve my own problem. It was doing a redirect to get the image and I just needed that URL. Here is my code that helped me get there.
$url="http://libero-news.it.feedsportal.com/c/34068/f/618095/s/2e34796f/l/0L0Sliberoquotidiano0Bit0Cnews0C12735670CI0Esaggi0Eper0Ele0Eriforme0Ecostituzionali0EChiaccherano0Ee0Eascoltano0Bhtml/story01.htm";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Must be set to true so that PHP follows any "Location:" header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$a = curl_exec($ch); // $a will contain all headers
$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); // This is what you need, it will return you the last effective URL
// Uncomment to see all headers
/*
echo "<pre>";
print_r($a);echo"<br>";
echo "</pre>";
*/
echo $url; // Voila

cURL operation and PHP

I have a frontend code
$ch = curl_init();
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json'));
curl_setopt($ch, CURLOPT_URL, $url);
//make the request
$responseJSON = curl_exec($ch);
$response_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($response_status == 200) { // success
// remove any "problematic" characters from the json string and then decode
if (debug) {
echo "----finish API of getAPI inside basic_function with status==200---";
echo "<br>";
echo "-------the json response is-------" ; //.$responseJSON;
var_dump($responseJSON);
//print_r($responseJSON);
echo "<br>";
}
return json_decode( preg_replace( '/[\x00-\x1F\x80-\xFF]/', '', $responseJSON ) );
}
and I have a backend code which executed when cURL fired its operation with its URL. The backend code would therefore activated. So, I know cURL is operating.
$output=array (
'status'=>'OK',
'data'=>'12345'
)
$output=json_encode($output)
echo $output;
and $output shown on browser as {"status":"OK","data":"12345"}
However, I gone back to the frontend code and did echo $responseJSON, I got nothing. I thought the output of {"status":"OK","data":"12345"} would gone to the $responseJSON. any idea?
Here's output on Browser, something is very odd! the response_status got 200 which is success even before the parsing of API by the backend code. I expect status =200 and json response after the {"status":"OK","data":"12345"}
=========================================================================================
inside the get API of the basic functions
-------url of cURL is -----http://localhost/test/api/session/login/?device_duid=website&UserName=joe&Password=1234&Submit=Submit
----finish API of getAPI inside basic_function with status==200---
-------the json response is-------string(1153)
"************inside Backend API.php******************
---command of api is--/session/login/
---first element of api is--UserName=joe
--second element of api is---Password=1234
---third element of api is----Submit=Submit
----fourth element of api is---
-------inside session login of api-------------
{"status":"OK","data":"12345"}
Have you tried with curl_setopt($ch, CURLOPT_TIMEOUT, 10); commented?
See what happends if you comment that line.
Also try with the a basic code, if that works, smthing you added later is wrong:
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.example.com/");
curl_setopt($ch, CURLOPT_HEADER, false);
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
Try var_dump($responseJSON)
If it returns false try
curl_error ( $ch )
Returns a clear text error message for the last cURL operation.
Are you sure your $url is correct?

PHP redirect after checking website is up

I want to do 300 redirect by php but first I want script will check whether the site is online or not if online then it will redirect else it will show unable to redirect. Can any one tell me how is possible?
thanks
This should do it (edited for betterness)
$destination = 'http://www.google.com';
$ch = curl_init($destination);
// use request type HEAD because it's faster and lighter
curl_setopt($ch, CURLOPT_NOBODY, true);
// prevent curl from dumping any output
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// prevent curl from producing any output
curl_setopt($ch, CURLOPT_HEADER, false);
// run request
curl_exec($ch);
// consider request a success if the HTTP Code is less than 400 (start of errors)
// change this to whatever you expect to get, e.g. "equal to 200 (OK)"
$success = (bool) ((int)curl_getinfo($ch, CURLINFO_HTTP_CODE) < 400);
curl_close($ch);
// redirect or die
if ($success) {
header('Location: ' . $destination, true, 301);
} else {
die('Unable to redirect to '.$destination.'');
}

Categories