Get Root Domain Name and subdomain Of Website using PHP - php

I am using this function code
public function getRootDomain($domain)
{
$domain = explode('.', $domain);
$tld = array_pop($domain);
$name = array_pop($domain);
$domain = "$name.$tld";
return $domain;
}
And the output i get is something like example.com
but i want to show m.example.com or www.example.com
Help related this ..thankx

Use parse_url(). You would want the host:
<?php
$url = '//www.example.com/path?googleguy=googley';
// Prior to 5.4.7 this would show the path as "//www.example.com/path"
var_dump(parse_url($url));
?>
The above example will output:
array(3) {
["host"]=>
string(15) "www.example.com"
["path"]=>
string(5) "/path"
["query"]=>
string(17) "googleguy=googley"
}
You would use it like so:
public function getRootDomain($domain)
{
$parts = parse_url($domain);
return $parts['host'];
}
If you're using PHP 5.4+:
public function getRootDomain($domain)
{
return parse_url($domain)['host'];
}

Related

Openpgp php decrypt returns null

I am trying to implement the following openpgp-php library to encrypt my text. But when I'm trying to decrypt, it gives null!
https://github.com/singpolyma/openpgp-php
My code implementation
<?php
require_once 'vendor/autoload.php';
require_once 'lib/openpgp.php';
require_once 'lib/openpgp_crypt_rsa.php';
require_once 'lib/openpgp_crypt_symmetric.php';
$public_key_ascii = file_get_contents('mypubkey.pgp');
$key = OpenPGP_Message::parse($public_key_ascii);
$data = new OpenPGP_LiteralDataPacket('Hello world!');
$encrypted = OpenPGP_Crypt_Symmetric::encrypt($key, new OpenPGP_Message(array($data)));
echo '<pre>Encrypted object: <br/>';
var_dump($encrypted);
$decryptor = new OpenPGP_Crypt_RSA($key);
$decrypted = $decryptor->decrypt($encrypted);
echo '<br/>Decrepted: ';
var_dump($decrypted);
Now when I'm running the script I'm getting the following output:
Encrypted object:
object(OpenPGP_Message)#10 (2) {
["uri"]=>
NULL
["packets"]=>
array(1) {
[0]=>
object(OpenPGP_IntegrityProtectedDataPacket)#7 (4) {
["version"]=>
int(1)
["tag"]=>
int(18)
["size"]=>
NULL
["data"]=>
string(68) "u��0��Y
�W~�-rS}e�#�2DJ�p����l�k�FakΩ-���pk� #Y�ft�Nm�S�zt�"
}
}
}
Decrepted: NULL
Any suggestions will be appreciated. Thanks

Storing a parameter in an array in a URL as a variable in PHP

Here is the URL:
https://all.burgbuilderdev.com/results-page/?address%5B0%5D=Milwaukee%2C%20WI%2053207&post%5B0%5D=project&distance=30&units=imperial&per_page=5&lat=42.971207&lng=-87.904057&form=2&action=fs
I realize it is in an array but I can't figure out how to target it and store it as a variable. I'm certain this is dumb (I'm a beginner with PHP) but I've tried things like:
$address = $_GET['address'];
and
$address = $_GET ['address%5B0%5D'];
and
$address = $_GET['address[0]'];
to no avail.. Thanks for stopping by!
Given:
$url = 'https://all.burgbuilderdev.com/results-page/?address%5B0%5D=Milwaukee%2C%20WI%2053207&post%5B0%5D=project&distance=30&units=imperial&per_page=5&lat=42.971207&lng=-87.904057&form=2&action=fs';
We can parse it like PHP automatically does:
$parsed = parse_url($url);
parse_str($parsed['query'], $parsedQuery);
var_dump(
$parsed,
$parsedQuery,
$parsedQuery['address'][0] // <<< Here is like $_GET
);
Renders (partial):
array(9) {
["address"]=> // <<< address key
array(1) { // <<< Address is array w/one item
[0]=> // <<< First item, zero index
string(19) "Milwaukee, WI 53207" // <<< Here
}
["post"]=>
array(1) {
[0]=>
string(7) "project"
}
["distance"]=>
string(2) "30"
...
https://3v4l.org/S7X7L
So in other words, PHP automatically does the above for GET, so it would be:
$_GET['address'][0]

Group URLs into single object output in API response

So I'll try to explain this as best as possible, but I'm having some issues with how the links are being rendered so I'll go into more detail below.
Here is the full method:
public function link_urls($text)
{
if (!$urls = $this->get('entities', 'urls')) {
return $text;
}
foreach ($urls as $url) {
$text = str_replace(
$url->url,
'' . $url->display_url . '',
$text
);
}
return $text;
}
What this method does is it takes the ['text'] param response from the API and then it goes through and searches for URLs and appends HTML outputs.
Let's say that we have $text which outputs the following tweet data:
string(316) “As we continue to celebrate #BlackHistoryMonth , our next Black Artist Spotlight 🎨 is local painter #EbonyLewisArt https:// t.co/LaRa7GDk4i”
This particular tweet has 4 images, but Twitter groups them all into one "tweet" link as shown above.
Next, I'm checking the tweets $urls object that it returns, which is $urls = $this->get('entities', 'urls') which gives me:
object(stdClass)#1958 (5) {
["start"]=>
int(115)
["end"]=>
int(138)
["url"]=>
string(23) "https:// t.co/LaRa7GDk4i"
["expanded_url"]=>
string(65) "https://twitter.com/dallasmavs/status/1491079415375495168/photo/1"
["display_url"]=>
string(26) "pic.twitter.com/LaRa7GDk4i"
}
object(stdClass)#1737 (5) {
["start"]=>
int(115)
["end"]=>
int(138)
["url"]=>
string(23) "https:// t.co/LaRa7GDk4i"
["expanded_url"]=>
string(65) "https://twitter.com/dallasmavs/status/1491079415375495168/photo/1"
["display_url"]=>
string(26) "pic.twitter.com/LaRa7GDk4i"
}
object(stdClass)#1735 (5) {
["start"]=>
int(115)
["end"]=>
int(138)
["url"]=>
string(23) "https:// t.co/LaRa7GDk4i"
["expanded_url"]=>
string(65) "https://twitter.com/dallasmavs/status/1491079415375495168/photo/1"
["display_url"]=>
string(26) "pic.twitter.com/LaRa7GDk4i"
}
object(stdClass)#1736 (5) {
["start"]=>
int(115)
["end"]=>
int(138)
["url"]=>
string(23) "https:// t.co/LaRa7GDk4i"
["expanded_url"]=>
string(65) "https://twitter.com/dallasmavs/status/1491079415375495168/photo/1"
["display_url"]=>
string(26) "pic.twitter.com/LaRa7GDk4i"
}
Here is the problem:
I'm calling a foreach loop which grabs all the URLs and converts $url->url with an <a> tag and displaying the $url->display_url as shown below:
foreach ($urls as $url) {
$text = str_replace(
$url->url,
'' . $url->display_url . '',
$text
);
}
The problem is that $text just has one URL to look on and the foreach loops through 4 times which causes issues and outputs the following:
As we continue to celebrate #BlackHistoryMonth , our next Black Artist
Spotlight 🎨 is local painter #EbonyLewisArt
pic.twitter.com/LaRa7GDk4i”
target=”_blank”>pic.twitter.com/LaRa7GDk4i”
target=”_blank”>pic.twitter.com/LaRa7GDk4i”
target=”_blank”>pic.twitter.com/LaRa7GDk4i
When I have one $urls object with one link in $text it's perfectly fine, the problem shows up when Twitter groups the links in $text and outputs multiple objects.
Here are my questions:
If there are multiple objects which are exactly the same, can I delete the other objects and just output one?
In the foreach, if the objects are the same, can I somehow skip all but one?
All help is appreciated on this!
Kindly change your foreach loop to this
foreach ($urls as $url) {
if( strpos($text, $url->url) !== false ){
$text = str_replace(
$url->url,
'' . $url->display_url . '',
$text
);
break;
}
}

SimpleXML and PHP XPath expression not returning correct data

The following PHP code:
<html>
<?php
$name = Secrezy;
$server = Sunstrider;
$raidurl='http://eu.wowarmory.com/character-achievements.xml?r='.$server.'&cn='.$name.'&c=168';
print_r($raidurl); // This is to check if the link is valid. Follow the link printed here and you should find a valid XML page
echo "<br>";
$xmlraid = simplexml_load_file($raidurl);
$achievement = array($xmlraid->xpath("/category/achievement[#id='4602']"));
print_r($achievement);
?>
</html>
Isn't working as I would expect it to. Shouldn't $achievement be populated with this:
<achievement categoryId="168" dateCompleted="2010-03-26T00:01:00+01:00" desc="Complete the 10-player raid achievements listed below." icon="inv_helmet_74" id="4602" points="25" reward="Reward: Bloodbathed Frostbrood Vanquisher" title="Glory of the Icecrown Raider (10 player)">
Instead, I just get an empty array.
Here is the full URL to the page http://eu.wowarmory.com/character-achievements.xml?r=Sunstrider&cn=Secrezy&c=168
Thanks!
Edit: After changing the xpath to /achievements/category/achievement[#id='4602'] which I completely missed, everything works fine. So thanks for that. However, if I implement this into my original code, it still doesn't work as I would expect. I'm sure I'm doing something terribly wrong, so thanks for the help.
<?php
echo "<html>
<head>
<title>ARMORY.</title>
<meta http-equiv='Content-Type' content='text/html' charset=iso-8859-1>
</head>
<body>
<table width='50%' border='1' cellpadding='10' cellspacing='10'>";
ini_set("user_agent", "Mozilla/5.0 (X11; U; Linux i686; pl-PL; rv:1.9.0.2) Gecko/20121223 Ubuntu/9.25 (jaunty) Firefox/3.8");
$server = "Sunstrider";
$guild = "Operation+Eskimo";
$url='http://eu.wowarmory.com/guild-info.xml?r='.$server.'&gn='.$guild;
$xml = simplexml_load_file($url);
$array = array();
foreach($xml->guildInfo->guild->members->character as $char)
if(strtolower($char['level']) === '80')
{
$array[] = $char['name']."<br />";
}
$i = 0;
while($array[$i] != null)
{
$name = $array[$i];
$raidurl='http://eu.wowarmory.com/character-achievements.xml?r='.$server.'&cn='.$name.'&c=168';
$xmlraid = simplexml_load_file($raidurl);
var_dump($xmlraid);
echo "<br><br>";
$achievement = array($xmlraid->xpath("/achievements/category/achievement[#id='4602']"));
$i++;
}
?>
</body>
</html>
That var_dump of xmlraid only produces this (many many times due to $i):
object(SimpleXMLElement)#3 (2) { ["#attributes"]=> array(2) { ["lang"]=> string(5) "en_us" ["requestUrl"]=> string(27) "/character-achievements.xml" } ["category"]=> object(SimpleXMLElement)#2 (1) { ["category"]=> array(12) { [0]=> object(SimpleXMLElement)#5 (0) { } [1]=> object(SimpleXMLElement)#6 (0) { } [2]=> object(SimpleXMLElement)#7 (0) { } [3]=> object(SimpleXMLElement)#8 (0) { } [4]=> object(SimpleXMLElement)#9 (0) { } [5]=> object(SimpleXMLElement)#10 (0) { } [6]=> object(SimpleXMLElement)#11 (0) { } [7]=> object(SimpleXMLElement)#12 (0) { } [8]=> object(SimpleXMLElement)#13 (0) { } [9]=> object(SimpleXMLElement)#14 (0) { } [10]=> object(SimpleXMLElement)#15 (0) { } [11]=> object(SimpleXMLElement)#16 (0) { } } }
I should add that I'm very new to PHP so my code isn't great.
Shouldn't the xpath be:
/achievements/category/achievement[#id='4602']
Or:
//category/achievement[#id='4602']
http://www.w3schools.com/xpath/xpath_syntax.asp
Update:
The issue with that code is the fact that you were adding <br /> to the end of each name in $array. Generally, avoid adding formatting in this way, unless there's a good reason.
Also, note my notes in the comments. Especially, urlendcode(). I left this for you to do with $url as I didn't notice it until after starting this edit and I'm lazy. ;) Note, that once you pass those query string params through urlencode() the + in the guild name won't be necessary and it will actually get in the way.
ini_set("user_agent", "Mozilla/5.0 (X11; U; Linux i686; pl-PL; rv:1.9.0.2) Gecko/20121223 Ubuntu/9.25 (jaunty) Firefox/3.8");
$server = "Sunstrider";
$guild = "Operation+Eskimo";
$url='http://eu.wowarmory.com/guild-info.xml?r='.$server.'&gn='.$guild;
$xml = simplexml_load_file($url);
$array = array();
foreach ($xml->guildInfo->guild->members->character as $char)
{
if (strtolower($char['level']) === '80')
{
$array[] = $char['name'];
}
}
foreach ($array as $i => $name)
{
// note that this if statement and $i in the foreach are only here to limit this to 1 for testing, the full list spews out A LOT of data and takes A LONG time
if ($i)
{
exit;
}
// note the urlencode() call, that's important
$raidurl='http://eu.wowarmory.com/character-achievements.xml?r=' . urlencode($server) . '&cn=' . urlencode($name) . '&c=168';
$xmlraid = simplexml_load_file($raidurl);
// note the pre tags around var_dump, makes things easier to read in the browser
// also note print instead of echo, I lke to do this for debugging, as it makes
// it easier to determine what's is debug output for those long running debugging sessions
print '<pre>';
var_dump($xmlraid);
print '</pre>';
echo "<br><br>";
// quick and dirty solution for viewing the XML
/*print '<textarea cols="400" rows="2000">';
print $xmlraid->asXML();
print '</textarea>';*/
$achievement = $xmlraid->xpath("/achievements/category/achievement[#id='4602']");
print '<pre>';
var_dump($achievement);
print '</pre>';
}
No, check the doc. simplexml_load_file() returns an object representing the XML into $xmlraid. I suggest doing a var_dump($xmlraid); and to verify your xpath expression.
The document element is achievements.
Your XPATH statement should be:
/achievements/category/achievement[id='4602']
Damn, those people are nasty browser-sniffers. I didn't do it all in vain though, this works:
<?php
$opts = array(
'http' => array(
'header' => 'User-Agent: Firefox/3.5.9\r\n'
)
);
$context = stream_context_create($opts);
libxml_set_streams_context($context);
$d = simplexml_load_file('http://eu.wowarmory.com/character-achievements.xml?r=Sunstrider&cn=Secrezy&c=168');
var_dump($d->xpath("//achievement[#id='4602']"));
The __extremely_ sad thing is, at first I just hoped it would be at least Accept or at the most Accept-Encoding - headers. But no, the "shouldn't mean anything significant"-User-Agent-header. A fine example why browser sniffing is bad if I ever saw one.

How extract part of an URL in PHP to remove specific part?

So, I have this URL in a string:
http://www.domain.com/something/interesting_part/?somevars&othervars
in PHP, how I can get rid of all but interesting_part?
...
$url = 'http://www.domain.com/something/interesting_part/?somevars&othervars';
$parts = explode('/', $url);
echo $parts[4];
Output:
interesting_part
Try:
<?php
$url = 'http://www.domain.com/something/interesting_part/?somevars&othervars';
preg_match('`/([^/]+)/[^/]*$`', $url, $m);
echo $m[1];
You should use parse_url to do operations with URL. First parse it, then do changes you desire, using, for example, explode, then put it back together.
$uri = "http://www.domain.com/something/interesting_part/?somevars&othervars";
$uri_parts = parse_url( $uri );
/*
you should get:
array(4) {
["scheme"]=>
string(4) "http"
["host"]=>
string(14) "www.domain.com"
["path"]=>
string(28) "/something/interesting_part/"
["query"]=>
string(18) "somevars&othervars"
}
*/
...
// whatever regex or explode (regex seems to be a better idea now)
// used on $uri_parts[ "path" ]
...
$new_uri = $uri_parts[ "scheme" ] + $uri_parts[ "host" ] ... + $new_path ...
If the interesting part is always last part of path:
echo basename(parse_url($url, PHP_URL_PATH));
[+] please note that this will only work without index.php or any other file name before ?. This one will work for both cases:
$path = parse_url($url, PHP_URL_PATH);
echo ($path[strlen($path)-1] == '/') ? basename($path) : basename(dirname($path));
Here is example using parse_url() to override the specific part:
<?php
$arr = parse_url("http://www.domain.com/something/remove_me/?foo&bar");
$arr['path'] = "/something/";
printf("%s://%s%s?%s", $arr['scheme'], $arr['host'], $arr['path'], $arr['query']);

Categories