I used this tutorial to make a simple PHP file that uses Namecheap's API to check the availability of domain names. I followed the tutorial exactly, so my code is:
<?PHP
$command = 'https://api.sandbox.namecheap.com/xml.response?ApiUser=myusername&ApiKey=myapikeyed&UserName=myusername&Command=namecheap.domains.check&ClientIp='.$_SERVER['REMOTE_ADDR'].'&DomainList=adminpeak.com,kavin12345.com';
$data = file_get_contents($command);
$xml = simplexml_load_string($data);
if( ! $xml)
{
// Code to do when load failed.
echo 'unable to load XML file';
}
else
{
// Code to do when load successful.
foreach ($xml->CommandResponse->DomainCheckResult as $result) {
echo $result['Domain'].':'. $result['Available'].'<br />';
}
}
?>
However, when I run this in my terminal using $ php namecheap.php, I get the error message:
Warning: Invalid argument supplied for foreach() in /Users/MyName/Documents/NamecheapPHP/namecheap.php on line 14
Any ideas?
Related
I am creating a web crawler for a search engine like Google. The web crawler works well, that's what I see when I run it through terminal, but it is not writing any records in the mysql database.
I have already tried granting all permissions to the database user the web crawler uses, but it was of no use. My server is flawless, that I can be sure of.
<?php
$start = "http://localhost/mariophp/test.html";
$already_crawled=array();
$crawling=array();
function get_details($url)
{
$options=array('http'=>array('method'=>"GET", 'headers'=>"User-Agent: ZeroBot/0.2\n"));
$context=stream_context_create($options);
$doc = new DOMDocument();
#$doc->loadHTML(#file_get_contents($url,false,$context));
$title=$doc->getElementsByTagName("title");
$title=$title->item(0)->nodeValue;
$simg=$doc->getElementsByTagName("img");
//$simg=$simg->getAttribute("src");
//$simg=$simg->item(0)->nodeValue;
$description="";
$keywords="";
$metas=$doc->getElementsByTagName("meta");
for($i=0; $i<$metas->length; $i++)
{
$meta=$metas->item($i);
if($meta->getAttribute("name")==strtolower("description"))
$description=$meta->getAttribute("content");
if($meta->getAttribute("name")==strtolower("keywords"))
$keywords=$meta->getAttribute("content");
}
$_con=mysqli_connect("localhost","augustus","password");
mysqli_select_db($_con,"websited");
$title=$_POST["title"];
$url=$_POST["url"];
$keywords=$_POST["keywords"];
$description=$_POST["description"];
$simg=$_POST["simg"];
$sql="insert into websited(stitle,slink,skey,sdesc,simg) values('$title','$url',$keywords',$description','$simg')";
if(!mysqli_query($_con,$sql))
{
echo "Error: mysqli_error($_con))";
}
}
function follow_links($url)
{
global $already_crawled;
global $crawling;
$options=array('http'=>array('method'=>"GET", 'headers'=>"User-Agent: MarioBot/0.1\n"));
$context=stream_context_create($options);
$doc = new DOMDocument();
#$doc->loadHTML(#file_get_contents($url,false,$context));
$linklist = $doc->getElementsByTagName("a");
foreach ($linklist as $link)
{
$l = $link->getAttribute("href");
if(substr($l,0,1)=="/" && substr($l,0,2)!="//")
{
$l=parse_url($url)["scheme"]."://".parse_url($url)["host"].$l;
}
else if (substr($l,0,2)=="//")
{
$l=parse_url($url)["scheme"].":".$l;
}
else if(substr($l,0,2)=="./")
{
$l=parse_url($url)["scheme"]."://".parse_url($url)["host"].dirname(parse_url($url)["path"]).substr($l,1);
}
else if(substr($l,0,1)=="#")
{
$l=parse_url($url)["scheme"]."://".parse_url($url)["host"].parse_url($url)["path"].$l;
}
else if(substr($l,0,3)=="../")
{
$l=parse_url($url)["scheme"]."://".parse_url($url)["host"]."/".$l;
}
else if(substr($l,0,11)=="javascript:")
{
continue;
}
else if(substr($l,0,5)!="https" && substr($l,0,4)!="http")
{
$l=parse_url($url)["scheme"]."://".parse_url($url)["host"]."/".$l;
}
if(!in_array($l,$already_crawled))
{
$already_crawled[]=$l;
$crawling[]=$l;
echo get_details($l)."\n";
//echo $l."\n";
}
}
array_shift($crawling);
foreach ($crawling as $site) {
follow_links($site);
}
}
follow_links($start);
print_r($already_crawled);
?>
Note:The test.html file mentioned in the code is a simple file containing links to different websites.
You may need to setup a server first to successfully run this code.
I am getting the following output right now.
[augustoandro#Augustus zerophp]$ php crawle2.php
PHP Notice: Undefined index: title in /srv/http/zerophp/crawle2.php on line 30
PHP Notice: Undefined index: url in /srv/http/zerophp/crawle2.php on line 31
PHP Notice: Undefined index: keywords in /srv/http/zerophp/crawle2.php on line 32
PHP Notice: Undefined index: description in /srv/http/zerophp/crawle2.php on line 33
PHP Notice: Undefined index: simg in /srv/http/zerophp/crawle2.php on line 34
PHP Recoverable fatal error: Object of class mysqli could not be converted to string in /srv/http/zerophp/crawle2.php on line 39
[augustoandro#Augustoandro zerophp]$
Please help.
Get rid of these lines:
$title=$_POST["title"];
$url=$_POST["url"];
$keywords=$_POST["keywords"];
$description=$_POST["description"];
$simg=$_POST["simg"];
These are overwriting the variables that you got from scraping the website. $_POST is for getting parameters that are submitted from a form or AJAX, they're not needed here.
The call to mysqli_error() should not be inside a string. Change
if(!mysqli_query($_con,$sql))
{
echo "Error: mysqli_error($_con))";
}
to
if(!mysqli_query($_con,$sql))
{
echo "Error: " . mysqli_error($_con));
}
Very new to PHP here. I am playing around with PokeAPI and want to check if a data entry exists. On the API itself, a link to a page with an invalid number (e.g. https://pokeapi.co/api/v2/pokemon/6666666/) gives this:
{"detail":"Not found."}
I want a message to be displayed on my app if the entry is empty/invalid. Here is the code I have written (I have a form on another page which provides the integer 'dexno'):
if (!empty($_POST["dexno"])) {
$dexno = $_POST["dexno"];
$data = file_get_contents($base.$dexno);
if ($data != "") {
$pokemon = json_decode($data);
$img = $pokemon->sprites->front_default;
$imageData = base64_encode(file_get_contents($img));
echo '<img src="data:image/png;base64,'.$imageData.'">';
}
else{
die("No Pokemon found.");
}
}
When I run it in my browser I encounter the following message:
( ! ) Warning:
file_get_contents(http://pokeapi.co/api/v2/pokemon/6666666): failed to
open stream: HTTP request failed! HTTP/1.1 404 NOT FOUND in
C:\wamp64\www\pokemon\process.php on line 24
After this is shown, the "No Pokemon found." message is displayed correctly. Any ideas as to what might be wrong? I may have missed out some details so feel free to ask questions :)
My script load a title of url when this load by php_self in a html form.
<?php
$bk_url=$_REQUEST['bk_url'];
$remote_url = $bk_url;
$from_remote_url = implode("", file("".$remote_url));
if(preg_match("/<title>(.+)<\/title>/", $from_remote_url, $regs)) {
} else {
echo "<br> Title empty. Manual insert";
}
?>
When load the php page, are displayed two errors:
Warning: file(http://): failed to open stream: operation failed
and this error:
Warning: implode(): Invalid arguments passed
I have try to find a solution on stackoverflow but not find any solution.
How to fix this two errors?
Thanks
You need to run the code only when the user has submitted the form. So check first to see if the variable is set.
if (isset($_REQUEST['bk_url'])) {
$bk_url=$_REQUEST['bk_url'];
$remote_url = $bk_url;
$from_remote_url = implode("", file("".$remote_url));
if(preg_match("/<title>(.+)<\/title>/", $from_remote_url, $regs)) {
} else {
echo "<br> Title empty. Manual insert";
}
}
I've been using this over 2 months and worked fine until some days ago, when an error message appeared.
I use the steam api to get some info of the players.
$url = "http://steamcommunity.com/id/CGaKeepoN/?xml=1";
The page is not blank, it has an xml document. So my first thinking was that my host had turned allow_url_fopen off, but they don't (I asked them).
I also tried using error_reporting(E_ALL); ini_set('display_errors', 1);
And that's what I get:
Warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "" on line 6
Notice: Trying to get property of non-object on line 7
Now I'm using this: $xml = simplexml_load_file(file_get_contents($url));
And I would love to continue using it because installing cURL it's not an option right now. Do you know of a better (or a working) way to get this done? Or how to fix this error?
My full code:
error_reporting(E_ALL);
ini_set('display_errors', 1);
//$url = "http://steamcommunity.com/id/CGaKeepoN/?xml=1";
$url = "xml.txt";
ini_set('allow_url_fopen ','ON');
$xml = file_get_contents($url) or die ("file_get_contents failed");
$xml = simplexml_load_string($xml) or die ("simplexml_load_string failed");
$profilepic = $xml->avatarIcon;
$pic = $xml->avatarFull;
$steamID = $xml->steamID;
$lastonline = $xml->stateMessage;
echo $xml;
echo $profilepic;
echo $pic;
echo $steamID;
echo $lastonline;
EDIT:
If I use the internal url it loads the data, but when I try to use any url that uses http protocol just launches the file_get_contents failed error, even if the url is my website's one. I'm willing to use cURL if there's no other solution. I also thought about making a php script that loads the data and saves it in a file in the server (and then run a cronjob every 10 min), but it would use the file_get_contents anyway...
file_get_content returns a string so use simplexml_load_string instead.
This code works for me, tested.
$url = "http://steamcommunity.com/id/CGaKeepoN/?xml=1";
$xml = simplexml_load_string(file_get_contents($url));
$profilepic = $xml->avatarIcon;
$pic = $xml->avatarFull;
$steamID = $xml->steamID;
$lastonline = $xml->stateMessage;
var_dump($url);
var_dump($xml); //-> string(45) "http://steamcommunity.com/id/CGaKeepoN/?xml=1" bool(false)
echo $xml;
echo $profilepic;
echo $pic;
echo $steamID;
echo $lastonline;
I built a very basic webAPI that when called prints some json data on the screen.
I'm calling the api with the following
function getEnvironmentList(){
$fullUrl = "localhost/serverList/api/rest.php?action=allenvironments&format=json";
$jsonDataRaw = file_get_contents($fullUrl);
return $jsonDataRaw;
}
$jsonData = getEnvironmentList();
echo "<PRE>";
var_dump(json_decode($jsonData, true));
echo "</PRE>";
I get the error Warning: file_get_contents(localhost/serverList/api/rest.php?action=allenvironments&format=json): failed to open stream: No error in C:\path\inc\getJSONdata.php on line 6
Yet when I visit that URL I see this
{"1":{"environmentID":"1","envName":"UAT","envCreatedBy":"mhopkins","envCreatedDtTm":"2013-06-30 00:34:57","envUpdatedBy":"mhopkins","envUpdatedDtTm":"2013-06-30 00:34:57"},"3":{"environmentID":"3","envName":"Platinum","envCreatedBy":"mhopkins","envCreatedDtTm":"2013-06-30 00:37:38","envUpdatedBy":"phpsense","envUpdatedDtTm":"2013-06-30 00:37:38"}}
I'm really confused why the code can't seem to realize there is json data there...
You forgot the http.
$fullUrl = "http://localhost/serverList/api/rest.php?action=allenvironments&format=json";