Compare an array string with a string - php

i am finishing a project, but i need to compare if a HTTP Status Code is the same as another. I have a big algorithm and i reduced them and i identified the problem:
I have an array called "$file_headers", and in the ["Status"] position saves "HTTP/1.1 301 Moved Permanently", and in the if clause i compare to "HTTP/1.1 301 Moved Permanently" (which obviously is the same), but my code doesn't say the same as me. I detect the HTTP Status Code using cURL. My PHP code is the following:
<?php
// create curl resource
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "fb.com");
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//enable headers
curl_setopt($ch, CURLOPT_HEADER, 1);
//get only headers
curl_setopt($ch, CURLOPT_NOBODY, 1);
// $output contains the output string
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
$data = explode("\n",$output);
$headers_one = $data;
$headers_two = array();
$headers_two['Status'] = $data[0];
array_shift($data);
foreach($data as $part){
$middle = explode(":",$part);
$msg = null;
if(sizeof($middle) > 2){
if(strpos($middle[0],"Location") === false){
for($i = 1; $i <= sizeof($middle)-1;$i++){
$msg .= $middle[$i];
}
} else {
for($i = 1; $i <= sizeof($middle)-1;$i++){
if($i == 1){
$msg .= $middle[$i] . ":";
} else {
$msg .= $middle[$i];
}
}
}
} else if(isset($middle[1])){
$msg = $middle[1];
}
$headers_two[trim($middle[0])] = trim($msg);
}
array_pop($headers_one);
array_pop($headers_one);
array_pop($headers_two);
$file_headers = $headers_two;
if($file_headers["Status"] === ("HTTP/1.1 301 Moved Permanently") || $file_headers["Status"] === ("HTTP/1.1 301")){
echo "OK!";
} else {
echo "NO!";
}
//print all headers as array
/*echo "<pre>";
print_r($headers_one);
echo "</pre><br />";*/
echo "<pre>";
echo $file_headers["Status"];
echo "</pre>";
?>
If anyone can help me i would appreciate it. THANKS AND HAVE A NICE DAY DEV!

$headers_two['Status'] is the only element you're not trim()ing, so it has some whitespace around it, which makes the comparison fail. Do it like this:
$headers_two['Status'] = trim($data[0]);
And it'll work just fine.

Related

get array out of loop

I need get array out of loop (I need used array, and not, last value)
loop
for ($x = 1; $x < $numero; $x++) {
$frase = $frase_script[$x];
$distrito1 = (explode(',',$frase));
echo $distrito1[0]}
Variable out
$ultimo_nome = $distrito1[0];
I need used array, and not, last value
echo "<br> I need print array, and not, last value".$ultimo_nome;
error: prints the last value and not an array.
Example
all code
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.geonames.org/searchJSON?username=country=pt&lang=pt&q=lisbon&fcode=ADM2&adminCode1=14&style=SHORT&maxRows=1000");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Accept: application/json"
));
$response = curl_exec($ch);
curl_close($ch);
$frase_script = (explode(',',$response));
$frase = $frase_script[0];
$palavra = (explode(':',$frase));
$numero = $palavra[1];
$frase_script = (explode('"name":',$response));
echo '[';
for ($x = 1; $x < $numero; $x++) {
$frase = $frase_script[$x];
$distrito1 = (explode(',',$frase));
echo $distrito1[0]; }
$ultimo_nome = $distrito1[0];
echo $ultimo_nome;
echo ']';
echo "<br> I need print array, and not, last value".$ultimo_nome;
if you need print all the elements but not the lasy you could use
$distrito1 = (explode(',',$frase));
$numElem = count($distrito1);
foreach ($distrito1 as $key => $value){
if ( $key < $numElem-1 ){
echo $value;
} else {
break;
}
}

How to call this curl API request to get the highest 'likelihood' json field name?

I'm trying to use this API from this site fullcontact for normalizing a number of possible names into 'likelihood values' for name extraction.
Tried the following code but it can't run Undefined offset: 2 error: $index_name = $possible_names[$n];. Moreover, I'm was stuck with the logic of extracting the name. Can someone help? Thanks
$possible_names = array("Jimmy Frank", "Wall Street"); // In this case Jimmy Frank should be the output person name
if (count($possible_names) > 1)
{
for ($n = 0; $n <= count($possible_names); $n++)
{
$index_name = $possible_names[$n];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.fullcontact.com/v2/name/normalizer.json?q=$index_name");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
$headers = array();
$headers[] = "X-Fullcontact-Apikey: APIKEY";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$namenormalizer_result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
else
{
$namejson_result = json_decode($namenormalizer_result, true);
$namejson_array[] = $namejson_result['likelihood'];
}
curl_close ($ch);
}
}
$possible_names is an array of size 2. Arrays are indexed from 0 so you need to remove the last index 2 which doesn't exist :
for ($n = 0; $n <= count($possible_names) - 1; $n++) {
}
or use strict condition :
for ($n = 0; $n < count($possible_names); $n++) {
}
For the extraction, you can use $namejson_result->nameDetails->fullName to extract fullName and $namejson_result->likelihood for likelihood :
$namejson_result = json_decode($result);
echo "likelihood for $index_name on " .
$namejson_result->nameDetails->fullName . " : " .
$namejson_result->likelihood . "\n";

php how to calculate numbers sum after the loop

I have following loop to calculate comments and likes
function AddCampaignDetails($next=null){
$AccessToken = ACCESS_TOKEN;
$url = "https://api.instagram.com/v1/tags/canonfanatic/media/recent?access_token=".$AccessToken;
if($url !== null) {
$url .= '&max_tag_id=' . $next;
}
/*//Also Perhaps you should cache the results as the instagram API is slow
$cache = './'.sha1($url).'.json';
if(file_exists($cache) && filemtime($cache) > time() - 60*60){
// If a cache file exists, and it is newer than 1 hour, use it
$jsonData = json_decode(file_get_contents($cache));
}else{
$jsonData = json_decode((file_get_contents($url)));
file_put_contents($cache,json_encode($jsonData));
}*/
$Ch = curl_init();
curl_setopt($Ch, CURLOPT_URL, $url);
curl_setopt($Ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($Ch, CURLOPT_TIMEOUT, 20);
$Result = curl_exec($Ch);
curl_close($Ch);
$Result = json_decode($Result);
$Data = $Result->data;
//echo "<pre>"; print_r($Data); echo "</pre>";
$CommentsSum = 0;
$LikesSum = 0;
for($i=0; $i<count($Data); $i++){
$CommentsSum += $Data[$i]->comments->count;
$LikesSum += $Data[$i]->likes->count;
}
//echo ' Comments '.$CommentsSum;
//echo ' Likes '.$LikesSum;
echo "<br />";
if(isset($Result->pagination->next_url) && !empty($Result->pagination->next_url)){
$next = $Result->pagination->next_url;
$this->AddCampaignDetails($next);
}else{
$NextUrl = "";
die;
}
return $result;
}
After this loop, I have echo $CommentsSum; variable and get this output
183
306
320
42
Now I want above number sum 851.
Any idea?
Thanks.
Your $Data[$i]->comments->count must be a number, and it's seem that is a string, so it's merging string instead of doing math.
And If you really have a new line between each number (like you said in echo) maybe $Data[$i]->comments->count is equal to "183\n"
use for example :
$CommentsSum += intval($Data[$i]->comments->count)

check to see if xml exists (not working)

i am trying to check through php if xml files exists on a url (incremental names till it fails)
why is this code not working?
<?php
for ($i = 1; $i <= 10; $i++) {
$url = "http://thetvdb.com/api/E676DF9578EF38D7/series/78901/default/".$i."/1/en.xml";
echo $url."<br />";
$xml = simplexml_load_file($url);
if ($xml) {
echo "yay"."<br />";
} else {
echo "fail"."<br />";
die();
}
}
?>
Your main problem is die(). This quits all execution.
I'd also try using fopen() instead of simplexml_load_file() unless you plan on using the XML later on, eg
$handle = #fopen($url, 'r');
if ($handle === false) {
echo 'fail<br />';
return; // check till it fails
} else {
echo 'yay<br />';
fclose($handle);
}
You could just use curl to find out whether a file exists:
function does_remote_file_exist($url){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($code == 200) $status = true;
else $status = false;
curl_close($ch);
return $status;
}

How can I re-code my php script to run as quickly as possible?

I'm running a script which will check the availability (10 times) of a domain name and output the domain, if available and a timestamp (with milliseconds).
Can you find anything which is slowing down the script even marignally?
If you could please adjust and re-post or advise what can be done better, it would be very much appreciated! Thank you.
<?php
date_default_timezone_set('Australia/Brisbane');
$loops = 0;
function udate($format, $utimestamp = null) {
if (is_null($utimestamp))
$utimestamp = microtime(true);
$timestamp = floor($utimestamp);
$milliseconds = round(($utimestamp - $timestamp) * 1000000);
return date(preg_replace('`(?<!\\\\)u`', $milliseconds, $format), $timestamp);
}
function GetCurlPage ($pageSpec)
{
$ch = curl_init($pageSpec);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$tmp = curl_exec ($ch);
curl_close ($ch);
$tmp = preg_replace('/(?s)<meta http-equiv="Expires"[^>]*>/i', '', $tmp);
$tmp = explode('<br>', $tmp);
foreach ($tmp AS $line) {
//echo '<pre>';
//print_r($line);
//echo '</pre>';
}
// Do something with each line.
echo $tmp[0];
echo "<br>";
echo $tmp[1];
//echo $tmp[2];
echo "<br>";
echo udate('H:i:s:u');
echo "<br><br>";
return $tmp;
}
while ($loops <= 10)
{
$suffixes=urlencode("com.au");
$domain = "sampledomain";
$fuzzysearch = "0";
$returnUrl="http://mydomain.com.au/test.php";
$url = "https://apidomain.com.au/check.php?domain=" .
$domain . "&suffixes=" . $suffixes . "&fuzzysearch=" . $fuzzysearch;
$output = GetCurlPage("$url");
++$loops;
}
?>
The slowness because you need to make 10 curl to external site
Two suggestions
update your test.php/check.php to allow multiple domain name check at one curl call (instead of checking one-by-one, pass an array)
use curl_multi_exec to allow parallel curl 10 different URLs at the same time
I would prefer suggestion 1
Don't put the code from $suffixes=urlencode("com.au"); until $domain . "&suffixes=" . $suffixes . "&fuzzysearch=" . $fuzzysearch; in the loop
Remove the empty foreach ($tmp AS $line) { loop
Don't do the regex stuff in udate and don't use a parameter there, instead let udate do it using string concatenation
Change if (is_null($utimestamp)) by if ($utimestamp === null) to prevent PHP from having to call the function is_null().

Categories