How to get domain expires date using whois response data on php? - php

How to get domain expires date using whois response data on php ?
Normally i use whois response for check domain availability.
eg: check DRGDRGDRGRGDRG.COM if whois response data have word No match for it's mean this domain is available.
No match for domain "DRGDRGDRGRGDRG.COM".
But now i want to check domain expires date using whois response data like this
Domain Name: GOOGLE.COM
Registrar: MARKMONITOR INC.
Sponsoring Registrar IANA ID: 292
Whois Server: whois.markmonitor.com
Referral URL: http://www.markmonitor.com
Name Server: NS1.GOOGLE.COM
Name Server: NS2.GOOGLE.COM
Name Server: NS3.GOOGLE.COM
Name Server: NS4.GOOGLE.COM
Status: clientDeleteProhibited https://icann.org/epp#clientDeleteProhibited
Status: clientTransferProhibited https://icann.org/epp#clientTransferProhibited
Status: clientUpdateProhibited https://icann.org/epp#clientUpdateProhibited
Status: serverDeleteProhibited https://icann.org/epp#serverDeleteProhibited
Status: serverTransferProhibited https://icann.org/epp#serverTransferProhibited
Status: serverUpdateProhibited https://icann.org/epp#serverUpdateProhibited
Updated Date: 20-jul-2011
Creation Date: 15-sep-1997
Expiration Date: 14-sep-2020
How can i do that ? thank you

This is not a simple question of parsing the response string as it might sound at the first moment because domain name registrars provide information in different format.
I guess we have two options here:
Use some library and when it fails parse the string
Do everything yourself, do not use any library and parse the output.
I suggest to start with some library but I really do not know the 'perfect' one. I'm going to try phpWhois. If it fails it gives raw data to try and parse it on our own.
First you need to install the library. I do this using Composer. Below is my composer.json file
{
"require": {
"phpwhois/phpwhois":"dev-master",
"mso/idna-convert": "0.9.1"
}
}
Note that latest phpWhois version does not work with latest idna-convert version, this is why I have to specify it in my requirements.
Execute composer install to download the libraries.
And finally PHP script to query the domain:
<?php
require(__DIR__ . '/vendor/autoload.php');
use phpWhois\Whois;
$whois = new Whois();
$whois->deepWhois = true;
$query = isset($argv[1]) ? $argv[1] : 'google.com';
$result = $whois->lookup($query);
$registered = isset($result['regrinfo']['registered']) && $result['regrinfo']['registered'] == 'yes';
if (!$registered) {
echo 'Domain: '.$query.' not registered.'.PHP_EOL;
} else {
if (isset($result['regrinfo']['domain']['expires'])) {
echo 'Domain: '.$query.PHP_EOL;
echo 'Expired: '.$result['regrinfo']['domain']['expires'].PHP_EOL;
} else {
echo 'Domain: '.$query.PHP_EOL;
echo 'Trying to find expires date...'.PHP_EOL;
foreach ($result['rawdata'] as $raw) {
if (strpos($raw, 'Expiry Date:') !== false) {
echo 'Expired: '.trim(explode(':', $raw)[1]).PHP_EOL;
}
}
}
}
It takes domain name as the first script argument $argv[1].
If the library does not parse the results from registrar we try to parse it manually. I've added a simple check
if (strpos($raw, 'Expiry Date:') !== false) {
echo 'Expired: '.trim(explode(':', $raw)[1]).PHP_EOL;
}
You might search for 'Expiration Date' in the raw response data or do some better logic based on your experience with parsing data if you will. Perfectly the library should do this but sometimes it fails.

Related

How to Return List of Project Tasks in ActiveCollab

Sorry this may be a trivial question but I am new to PHP. In the documentation to retrieve project tasks, the following code is provided to connect to an Active Collab cloud account:
<?php
require_once '/path/to/vendor/autoload.php';
// Provide name of your company, name of the app that you are developing, your email address and password.
$authenticator = new \ActiveCollab\SDK\Authenticator\Cloud('ACME Inc', 'My Awesome Application', 'you#acmeinc.com', 'hard to guess, easy to remember');
// Show all Active Collab 5 and up account that this user has access to.
print_r($authenticator->getAccounts());
// Show user details (first name, last name and avatar URL).
print_r($authenticator->getUser());
// Issue a token for account #123456789.
$token = $authenticator->issueToken(123456789);
// Did we get it?
if ($token instanceof \ActiveCollab\SDK\TokenInterface) {
print $token->getUrl() . "\n";
print $token->getToken() . "\n";
} else {
print "Invalid response\n";
die();
}
This works fine. I can then create a client to make API calls:
$client = new \ActiveCollab\SDK\Client($token);
and get the list of tasks for a given project as shown in the documentation.
$client->get('projects/65/tasks'); // PHP object
My question is, what methods/attributes are available to get the list of tasks? I can print the object using print_r() (print will obviously not work), and what I really want is in the raw_response header. This is private however and I cannot access it. How do I actually get the list of tasks (ex: the raw_response either has a string or json object)?
Thanks in advance.
There are several methods to work with body:
$response = $client->get('projects/65/tasks');
// Will output raw JSON, as string.
$response->getBody();
// Will output parsed JSON, as associative array.
print_r($response->getJson());
For full list of available response methods, please check ResponseInterface.
If you wish to loop through tasks, use something like this:
$response = $client->get('projects/65/tasks');
$parsed_json = $response->getJson();
if (!empty($parsed_json['tasks'])) {
foreach ($parsed_json['tasks'] as $task) {
print $task['name'] . "\n"
}
}

Asynchronous API handling with PHP

I have this PHP function that logs the visitors to a .txt file (for security reasons). It uses an API to get their location. It works fine on localhost, but when it's actually live it logs empty values. I'm assuming it's because the functions runs before the API has had time to return the data. Is there a way to write something like a Javascript promise or some asynchronous function that will wait for the data to return before logging it?
This is what I currently have:
function getLocation() {
$query = #unserialize (file_get_contents('http://ip-api.com/php/'));
if ($query && $query['status'] == 'success') {
$user = $_SERVER['REMOTE_ADDR'].' - '.date("H:i:s d-m-Y").' - '.$query['country'].', '.$query['regionName'].', '.$query['city'].', '.$query['zip'];
$file = '../logs/userlog.txt';
$currentFileData = file_get_contents($file);
$currentFileData .= $user . PHP_EOL;
file_put_contents($file, $currentFileData);
}
}
What the output should be:
127.0.0.1 - 11:59:33 03-04-2020 - South Africa, Western Cape, Cape Town, 8001
What the actual output is:
127.0.0.1 - 11:59:33 03-04-2020 - , , ,
Your help will be greatly appreciated!
You are not passing the IP address as stated in the documentation after the /php/ part of the URL. It should be
$query = #unserialize (file_get_contents('http://ip-api.com/php/' . $_SERVER['REMOTE_ADDR']));
SOLVED: Thanks to #DanielProtopopov's post I actually found on the documentation that this php version of the API has been deprecated. So using #DanielProtopopov's fix I have to use the JSON API for it to work:
$query = json_decode(file_get_contents('http://ip-api.com/json/' . $_SERVER['REMOTE_ADDR']));

Plivo PHP API 4.0, can't get callstatus or duration (action URL does not execute?)

I hope you can help me with an issue with phone call dialings using Plivo PHP (new SDK 4.0). First I will indicate what I want to achieve:
- A client on my website wants to talk with an agent of main, so he introduces his telephone number in a form, choose an agent, and finally when submit, the website connect both of them dialing (this works). But then, (here begin my problems), I can't retrieve the call details (status, duration, initial and end dates of the call, etc...) for invoicing the client according to some of these details.
Edited 2018/02/23:
Ramya, the 600 error has dissapeared and everything seems to be ok as I see in the Plivo debug log. Below are my new codes (I think better done thanks to your instructions), and then, I show you the Plivo debud log (perhaps it's better you can see it inside my account, call made Feb 23, 2018 18:33:15), and finally I see my server debug error log is empty!.
The main problem is that dialstatus.php file, although seems to receive the parameters, I don't know how to access them because dialstatus.php does not execute showing the data in my monitor (in my code for example, this line never shows in the monitor screen:)
echo "Status = $estado, Aleg UUID = $aleg, Bleg UUID = $bleg";
So even though it receives the parameters, I can not access them to manipulate them, print them on the screen, do ifs with them, etc. May it be perhaps a permission problem with the files? (These php files have 6,4,4 permissions on my server, the same as the others).
Thank you!
Code 1: makecall.php
require 'vendor/autoload.php';
use Plivo\RestClient;
$client = new RestClient("**********", "**************************");
$telefono_cliente = "34*******";
$telefono_experto = "34*********";
$duracion = 50;
try {
$response = $client->calls->create(
"3491111111",
[$telefono_experto],
"https://www.ejemplo.com/llamar/response.php?telf=$telefono_cliente",
'POST',
[
'time_limit' => $duracion,
]
);
$id = $response->requestUuid;
echo "<br>Este es el requestUuid: " . $id . "<br><br>";
}
catch (PlivoRestException $ex) {
print_r($ex);
}
?>
Code 2: response.php
require 'vendor/autoload.php';
use Plivo\XML\Response;
$resp = new Response();
$params = array(
'callerId' => '3491111111',
'action' => "https://www.ejemplo.com/llamar/dialstatus.php",
'method' => "POST",
'redirect' => "false"
);
$body3 = 'Desde ejemplo un cliente desea hablar con usted.';
$params3 = array(
'language' => "es-ES", # Language used to read out the text.
'voice' => "WOMAN" # The tone to be used for reading out the text.
);
$resp->addSpeak($body3,$params3);
$dial = $resp->addDial($params);
//$number = "34**********";
$number = $_GET['telf'];
$dial->addNumber($number);
Header('Content-type: text/xml');
echo($resp->toXML());
/*
Output:
<?xml version="1.0" encoding="UTF-8"?>
<Response>
<Speak language="es-ES" voice="WOMAN">Desde ejemplo un cliente desea hablar con usted.</Speak>
<Dial redirect="false" method="POST" action="http://www.ejemplo.com/llamar/dialstatus.php" callerId="3491111111">
<Number>34********</Number>
</Dial>
</Response>
*/
?>
Code 3: dialstatus.php
// Print the Dial Details
$estado = $_REQUEST['DialStatus'];
$aleg = $_REQUEST['DialALegUUID'];
$bleg = $_REQUEST['DialBLegUUID'];
echo "Status = $estado, Aleg UUID = $aleg, Bleg UUID = $bleg";
?>
Plivo Sales Engineer here.
Redirect = true is used only when you want to continue the call by returning another XML in your action URL. For you use case, you don't have to use this parameter. Even if the Redirect is set to false, Plivo will make a request to the action URL with a list of parameters. I looked into your account (here) and I can see this request getting sent with DialStatus, ALegUUID, BLegUUID along with other parameters.
Dial Action URL is the best place to know the DialStatus and DialHangupCause.
You can find the call duration and billing amount in Hangup URL request as well. This Hangup URL can be configured in your first API call (to the expert). By default, hangup URL is set to Answer URL.
Please raise a support ticket with us for further assistance.

file_get_contents() returns extra underscore on angular.callbacks

I built a PHP file with the sole purpose of hiding the API keys for Google Search, but part of the file_get_contents() always echo angular.callbacks._0_({ instead of angular.callbacks._0({
This small change makes the rest of the response worthless as Angular throws Uncaught TypeError: angular.callbacks._0_ is not a function. Although the workaround does works flawlessly, I would like to know if someone found the root of this issue or a better solution that is strictly PHP (no curl or any other package.)
search.php
<?php // Created by Deovandski on 2/14/2016
header('Content-type: application/json');
# Setup Base URL and array for Parameters
$host = 'https://www.googleapis.com/customsearch/v1?';
$queries = array();
$queries['cx'] = "XXX";// CSE KEY
$queries['key'] = "XXX"; // API KEY
# Setup possible incoming params
if (isset($_GET['search_term'])) $queries['q'] = $_GET['search_term'];
if (isset($_GET['result_count'])) $queries['result_count'] = $_GET['result_count'];
if (isset($_GET['callback'])) $queries['callback'] = $_GET['callback'];
# Build query and Final URL
$queriesURL = http_build_query($queries) . "\n";
$finalURL = $host.$queriesURL;
echo $finalURL;
/* echo $finalURL output (I only edited the keys out):
https://www.googleapis.com/customsearch/v1?cx=XXX&key=XXX&q=Hatsune+Miku&result_count=10&callback=angular.callbacks._0
*/
// Setup Response
$response = file_get_contents($finalURL);
// workaround
$fixedResponse = str_replace("angular.callbacks._0_", "angular.callbacks._0", $response);
echo $fixedResponse;
?>
This is part of a correct Google API response:
// API callback
angular.callbacks._0({
"kind": "customsearch#search",
"url": {
"type": "application/json",
"template": "https://www.googleapis.com/customsearch/v1?q={searchTerms}&num={count?}&start={startIndex?}&lr={language?}&safe={safe?}&cx={cx?}&cref={cref?}&sort={sort?}&filter={filter?}&gl={gl?}&cr={cr?}&googlehost={googleHost?}&c2coff={disableCnTwTranslation?}&hq={hq?}&hl={hl?}&siteSearch={siteSearch?}&siteSearchFilter={siteSearchFilter?}&exactTerms={exactTerms?}&excludeTerms={excludeTerms?}&linkSite={linkSite?}&orTerms={orTerms?}&relatedSite={relatedSite?}&dateRestrict={dateRestrict?}&lowRange={lowRange?}&highRange={highRange?}&searchType={searchType}&fileType={fileType?}&rights={rights?}&imgSize={imgSize?}&imgType={imgType?}&imgColorType={imgColorType?}&imgDominantColor={imgDominantColor?}&alt=json"
},
I put up a live version of this issue that can be seen on my FTP server. The PHP file can be viewed through this link (AngularJS parameters included on it).
The problem is the escape sequences \n. Which is passed as part of the request. And which is interpreted as space and as part of the callback function name and replaced by the side of the API to underline.
To understand just try this option and look at the result:
$queriesURL = http_build_query($queries) . "\n" . "after";
So just take away a newline.

WSO2 WS Security Password only without certificate possible?

we want to create a PHP WSO2 Webservice Client which uses WS Security, but without signature nor encryption. Instead we want to use a simple Password. Problem is: we always get an certificate error (see below). Do we really have to install a certificate, and if so: where ? Java Keystore ?
Environment: PHP 5.3.10, WSO2 PHP 2.10, Apache 2.2.x
wfs_client_log:
[error] key_mgr.c(295) [rampart][rampart_signature] Public key certificate file is not specified.
[error] rampart_signature.c(856) [rampart][rampart_signature] Cannot get certificate
[error] rampart_sec_header_builder.c(131) [rampart][shb] Signing failed. ERROR
[error] rampart_sec_header_builder.c(601) [rampart][shb] Asymmetric Binding failed
[error] rampart_out_handler.c(130) [rampart]Security header building failed.
[error] phase.c(224) Handler RampartOutHandler invoke failed within phase Security
[error] engine.c(657) Invoking phase Security failed
PHP Code is:
<?php
// Endpoint WebService
$endPoint = 'http://xxx.xxxx.xxx:7000/orabpel/selfservice/passwortAendernMBE/1.0';
// Security-Payload
$user = 'mustermann123';
$passwortAlt = 'foo';
$passwortNeu = 'bar';
// create Security-Token
$secToken = new WSSecurityToken(array(
"user" => $user,
"password" => $passwortAlt,
"passwordType" => "PlainText"));
// create SecurityPolicy
$policy = new WSPolicy(array(
"security" => array(
"useUsernameToken" => TRUE)));
// create WS-Client
$client = new WSClient( array(
"to" => $endPoint,
"useSOAP" => "1.1",
"action" => "process",
"policy" => $policy,
"securityToken" => $secToken));
// create SOAP-Payload
$soapPayload = '
<ns1:passwortAendern_processElement xmlns:ns1="http://xxxx.xxxx.xxxxxe/Integration/prozesse/xxxxxxSchema"
xmlns:ns2="http://xxxx.xxxx.xxx/types/xx.xxx.xxxx.selfService.prozesse.xxx.xxxxMessage">
<ns1:passwortAendernMessage>
<ns2:benutzerkennung>' . $user . '</ns2:benutzerkennung>
<ns2:passwortAlt>' . $passwortAlt . '</ns2:passwortAlt>
<ns2:passwortNeu>' . $passwortNeu . '</ns2:passwortNeu>
</ns1:passwortAendernMessage>
</ns1:passwortAendern_processElement>';
// Request
$soapResponse = null;
try {
// soap Request
$soapResponse = $client->request( $soapPayload );
// print out Response
echo '<pre>';
print_r(htmlspecialchars( str_replace('>','>'.PHP_EOL,$soapResponse->str ) ));
echo '</pre>';
} catch(Exception $e) {
echo '<h1>Error:</h1>' . PHP_EOL;
var_dump($e);
}
// dump Soap-Parameters
echo '<h1>Soap-Parameter</h1>' . PHP_EOL;
var_dump($soapPayload);
// dump Soap-Response
echo '<h1>Soap-Response</h1>' . PHP_EOL;
var_dump($soapResponse);
Finally successful! Calling the Webservice (with above mentioned vector/intent) now works.
Many attempts and another example by Nandika later we've found out that for us (Matthias and I) changing the creation of the WS-SecurityPolicy -object did the trick.
Instead of using above array as initialisation-parameter:
// create SecurityPolicy
$policy = new WSPolicy(array(
"security" => array(
"useUsernameToken" => TRUE)));
...we now use a xml-policy-file like so:
// load Policy (xml) file...
$policy_file = file_get_contents("policy.xml");
// ...and create SecurityPolicy
$policy = new WSPolicy($policy_file);
Content of "policy.xml":
<wsp:Policy xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
xmlns:sp="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702">
<wsp:ExactlyOne>
<wsp:All>
<sp:TransportBinding>
<wsp:Policy>
</wsp:Policy>
</sp:TransportBinding>
<sp:SignedSupportingTokens>
<wsp:Policy>
<sp:UsernameToken
sp:IncludeToken="http://docs.oasis-open.org/ws-sx/ws-securitypolicy/200702/IncludeToken/AlwaysToRecipient">
<wsp:Policy>
<sp:WssUsernameToken10 />
</wsp:Policy>
</sp:UsernameToken>
</wsp:Policy>
</sp:SignedSupportingTokens>
</wsp:All>
</wsp:ExactlyOne>
</wsp:Policy>
Beginning to use WSO2 with WS-Security WSF/PHP 2.1 feels rather touchy. Therefore I'll try to list some thoughts that knowing (would have) helped me save time:
most common error reflected to me by wsf/php is (an exception-object with the message): "Error , NO Response Received". This now happens almost whenever anything goes wrong, for example:
my request-xml (-structure) is not valid
a parameter has an incorrect type
the webservice throws an Exception (any exception really: be it because of a wrong WS-Security user/password, missing/unknown namespace, even some exceptions of type 'WS-Fault')
anything going wrong on the service-side really
a misconfiguration / configuration-change on php/wsf -side that disallowes anything relevant
network problems? (...not confirmed)
no request is sent by wso2 (for example when having trouble with TransportBinding -confinguration)
sometimes I do get a WS-Fault -ojbect (in a resopnse envelope) which I can check for my client-code [$e typeof WSFault]
always have a tool with proxy-capabilities nearby to route through + inspect your request and response. At the moment I use Oracles JDeveloper 10 and 11 which both have a neat little "HTTP Analyzer" inside (but there sure are smaller and/or better tools out there for this purpose).
Playing around with the settings in policy.xml a comrad and I found out that:
having a instead of the needed node (in your security_policy.xml) you'll get a WS-Fault: "policy requires authentication token"
having an empty node results in connection terminated in browser and wsf/php crashing (without signifficant error message - as far as i can see).
Thanks everyone (especially Nandika) for your help!
I've encountered the same issue once, but it was concerning WSServer, not WSClient. Since version 2.1 (or even earlier) WSF consideres WS-Policy signed by default, you need a WSPolicy file which declared signatureless behaviour. I've posted an article on this topic, but it's in Russian. Use Google Translate.
http://habrahabr.ru/post/132353/
The default generated policy is failing because, wsf/php 2.1.0 version is expecting signed messages for default generated policy for
$policy = new WSPolicy(array( "security" => array("useUsernameToken" => TRUE)));
Try with the following policy file.
https://svn.wso2.org/repos/wso2/trunk/wsf/php/samples/security/username_token/call_back/policy.xml
You can load the policy as
$policy_file = file_get_contents("policy.xml");
$policy = new WSPolicy($policy_file);

Categories