I am trying to set up a tool to get someone's Twitter ID without using twitter's API.
In my example, my username is quixthe2nd.
So if you enter someone's twitter username in this link:
https://twitter.com/quixthe2nd/profile_image?size=original
It would redirect to:
https://pbs.twimg.com/profile_images/1116692743361687553/0P-dk3sF.jpg
The ID is 1116692743361687553
. It is listed after https://pbs.twimg.com/profile_images/
.
My code is:
$url = "https://twitter.com/quixthe2nd/profile_image?size=original";
function get_redirect_target($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$headers = curl_exec($ch);
curl_close($ch);
// Check if there's a Location: header (redirect)
if (preg_match('/^Location: (.+)$/im', $headers, $matches))
return trim($matches[1]);
// If not, there was no redirect so return the original URL
// (Alternatively change this to return false)
return $url;
}
function get_redirect_final_target($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // follow redirects
curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // set referer on redirect
curl_exec($ch);
$target = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
curl_close($ch);
if ($target)
return $target;
return false;
}
$s = $target;
if(preg_match('/profile_images\/\K[^\/]+/',$s,$matches)) {
print($matches[0]);
}
My code doesn't output anything. How would I be able grab that via PHP?
You can use this regex and grab your value from group1,
profile_images\/([^\/]+)
Alternatively, you can use \K
so your full match is your intended text.
profile_images\/\K[^\/]+
$s = "https://pbs.twimg.com/profile_images/1116692743361687553/0P-dk3sF.jpg";
if(preg_match('/profile_images\/\K[^\/]+/',$s,$matches)) {
print($matches[0]);
} else {
echo "Didn\'t match";
}
Prints,
1116692743361687553