Wordpress theme causing high server load - php

I have a theme that I edited causing very high load on my server,
First i used this code to get only text from content
$response = get_the_content();
$content = $response;
$content = preg_replace("/(<)([img])(\w+)([^>]*>)/", "", $content);
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
Then i wanted to fetch all images inside my post content so i used "DOMDocument" Code:
$document = new DOMDocument();
libxml_use_internal_errors(true);
$document->loadHTML($response);
libxml_clear_errors();
$images = array();
$imgsq = $document->getElementsByTagName('img');
I have every post contains a static part than is in all photo pages so i used that code to get it
function findit($mytext,$starttag,$endtag) {
$posLeft = stripos($mytext,$starttag)+strlen($starttag);
$posRight = stripos($mytext,$endtag,$posLeft+1);
return substr($mytext,$posLeft,$posRight-$posLeft);
}
$project = #findit($content , '-projectinfostart-' , '-projectinfoend-');
$check = str_replace('ializer-buttons clearfix">', '', $project);
if($project != $check) $project = '';
$replace = array('-projectinfostart-' , '-projectinfoend-' , $project , '<p> </p>');
$content = str_replace( $replace, '', $content);
Then at last i wanted to get all photos in thumb size so i used that code:
foreach($imgsq as $key => $img) :
// Extract what we want
$image = array('src' => $img->getAttribute('src') );
if( ! $image['src'])
continue;
if($key == $page) :
echo '<center><img style="height: auto !important;max-height:450px;" class="responsiveMe" src=" ' . $image['src'] . '" /> ';
endif;
$srcs[$key] = array();
$srcs[$key]['src'] = wp_get_attachment_thumb_url(get_attachment_id_by_url($image['src']));
$srcs[$key]['full'] = $image['src'];
if(!empty($project)) $description = '<p>' . $project . '</p>';
else $description = '';
endforeach;
My server is 16 GB Ram and can't work with 1500 online users on single post page ! any ideas about what is causing this high load ?
Thanks.

Related

How to replace strings except inside tag attributes in PHP?

Problem
I have a working script to mass replace all occurrences of listed strings:
function replace_content( $text_content ) {
$input = file_get_contents(__DIR__ . "/strings.json");
$data = json_decode($input, true);
$textlist = array();
foreach($data as $item) {
$text_content = str_ireplace( $item['n.name'], "<span class='hello'>" . $item['n.name'] .'</span>', $text_content );
}
return $text_content;
}
add_filter( 'the_content', 'replace_content' );
However, for occurrences inside tag attributes, I don't want them to be replaced. For example, if I have:
<div id="AListedString" foobar="bla n.name='AnotherListedString' bla">
AListedString YetAnotherListedString
</div>
then the desired output is:
<div id="AListedString" foobar="bla n.name='AnotherListedString' bla">
<span class='hello'>AListedString</span>
<span class='hello'>YetAnotherListedString</span>
</div>
So far the script replaces all occurrences of AListedString, AnotherListedString, YetAnotherListedString. How should I do this?
Attempt
I found this question How to replace text except when it's between two tags in PHP?, but when I use this code:
function replace_content( $text_content ) {
$input = file_get_contents(__DIR__ . "/node.json");
$inputclean = removeBOM($input);
$data = json_decode($inputclean, true);
$textlist = array();
foreach($data as $item) {
// $replaceStr = "<span class='beliefnode'>" . $item['n.name'] .'</span>'
$text_content = str_ireplace( $item['n.name'], "<span class='beliefnode'>" . $item['n.name'] .'</span>', $text_content );
$domElem = new DOMDocument();
$domElem->loadXML("<temp_tag>".$text_content."</temp_tag>");
$nodes = $domElem->getElementsByTagName('div');
$index = 0;
while($nodes->item($index)->nodeValue)
{
$nodes->item($index)->nodeValue = str_replace("<span class='beliefnode'>" . $item['n.name'] .'</span>',
$item['n.name'],
$nodes->item($index)->nodeValue);
$index++;
}
echo $domElem->saveHTML();
}
return $text_content;
}
add_filter( 'the_content', 'replace_content' );
It throws a lot of errors that I think it's really not the way to solve this.

Php download image from html tag and return the downloaded image

please help me with the blow code on where am having error, i have two php function, one copies an external image from and website in any string that has [img]here is the image link[/img]. and the other function returns the image downloaded in our sever and set to the previous external link which was copied from.
here is the two functions
function covertContentToHTML($title, $content)
{
$regex = '#\[img( alt="(.+?)\")?( caption="(.+?)\")?](.+?)\[\/img\]#is';
$content = preg_replace_callback($regex, function ($matches) use ($title) {
$imageAlt = $matches[2];
$caption = $matches[4];
$imageUrl = $matches[5];
$caption = trim(preg_replace('/\s+/', ' ', $caption));
$imageUrlToLocalPath = copyimage($imageUrl);
return '<figure class="center"><img src="' . $imageUrlToLocalPath . '" alt="' . (empty($imageAlt) ? $title : $imageAlt) . '" title="' . $title . '">
' . (!empty($caption) ? '<br><figcaption><span class="help">Inset:</span> <strong>' . $caption . '</strong></figcaption>' : '') . '
</figure>';
}, $content);
return $content;
}
function copyimage($content) {
$content = preg_replace('#<img(.*?)src="(.*?)"(.*?)>#is', '[img]\\2[/img]', $content);
preg_match_all('#\[img( alt="(.+?)\")?( caption="(.+?)\")?](.+?)\[\/img\]#is', $content, $matches);
$images = $matches[5];
$i = 0;
$im = [];
foreach ($images as $image) {
array_push($im, $image);
$i++;
$encodeImageUrl = base64_encode($image);
$imageBasename = pathinfo($image, PATHINFO_BASENAME);
$imageLocalPath = "images/hsi/" . $encodeImageUrl . "/images";
if ( !is_dir( $imageLocalPath ) ) {
mkdir($imageLocalPath, 0755, true );
}
copy($image, $imageLocalPath.'/'.$imageBasename);
}
}
the problem am having is that the function convertContentToHtml Does not return the downloaded image and set them to the return figure class..
example i have a string or content like this
$content = 'HELLO WORLD <p> [img]http://www.stackoverflow/images/newimage.jpg[/img] testing this content [img]http://www.stackoverflow.com/images/newimage2.jpg'[/img]';
the code function convertContentToHtml will download the the stackoverflow newimage.jpg and newimage2.jpg to my server and then replace with the stackoverflow/images/newimage.jpg and stackoverflow.com/images/newimage2.jpg to to my link to the image downloaded using the copyimage function.
please help. thanks.

returning json array with PHP not working

I am trying to return a json array after i parse an rss feed.
this is my code :
<?php
header('Content-Type: application/json');
$feed = new DOMDocument();
//http://www.espnfc.com/rss
//http://www.football365.com/topical-top-10/rss
$feed->load('http://www.espnfc.com/rss');
$json = array();
$items = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('item');
$json['item'] = array();
$i = 0;
foreach($items as $item) {
$i = $i+1;
$title = $item->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
$link = $item->getElementsByTagName('link')->item(0)->firstChild->nodeValue;
$img = $item->getElementsByTagName('enclosure')->item(0)->attributes->getNamedItem('url')->value;
//$img = $item;echo($url);
$json['item'][] = array("title"=>str_replace(array("\n", "\r", "\t","'"), ' ', $title),"link"=>str_replace(array("\n", "\r", "\t","'"), ' ', $link),"img"=>str_replace(array("\n", "\r", "\t","'"), ' ', $img));
}
print_r($json['item'][0]);
//echo json_encode($json['item']);
?>
after iterating all items i finally would like to echo them as a result:
echo json_encode($json['item']);
the problem that's not showing any thing in browser. but when i moved this line into the foreach bloc it show result (of course with redundancy).
Some of the items don't have an <enclosure> tag, so the script gets an error when it tries to access the url attribute. You need to check for this.
$enclosures = $item->getElementsByTagName('enclosure');
if ($enclosures->length) {
$img = $item->getElementsByTagName('enclosure')->item(0)->attributes->getNamedItem('url')->value;
} else {
$img = '';
}
Your code returns request status "Status Code:500 Internal Server Error"
You can easy see it by browsing the network tab of your browser's web tools.
This is because on the 3rd post there is no image.
<?php
// Json Header
header('Content-Type: application/json');
// Get Feed
$feed = new DOMDocument();
$feed->load('http://www.espnfc.com/rss');
// Get Items
$items = $feed->getElementsByTagName('channel')->item(0)->getElementsByTagName('item');
// My json object
$json = array();
$json['item'] = array();
// For each item
foreach($items as $item){
// Get title
$title = $item->getElementsByTagName('title')->item(0)->firstChild->nodeValue;
// Get link
$link = $item->getElementsByTagName('link')->item(0)->firstChild->nodeValue;
// Get image if it exist
$img = $item->getElementsByTagName('enclosure');
if($img->length>0){
$img = $img->item(0)->attributes->getNamedItem('url')->value;
} else {
$img = "";
}
array_push($json['item'], array(
"title" => preg_replace('/(\n|\r|\t|\')/', ' ', $title),
"link" => preg_replace('/(\n|\r|\t|\')/', ' ', $link),
"img" => preg_replace('/(\n|\r|\t|\')/', ' ', $img)
));
}
echo json_encode($json['item']);
?>

Flickr API returning duplicate images

I'm trying to get images from flickr using the Flickr API and I'm having trouble figuring out how to get only unique images. I've already reviewed the arguments for the specific method that I'm using and here's what I came up with:
<?php
class Flickr {
private $flickr_key;
private $flickr_secret;
private $format = 'json';
public function __construct( $flickr_key, $flickr_secret ) {
$this->flickr_key = $flickr_key;
$this->flickr_secret = $flickr_secret;
}
public function searchPhotos( $query = '', $tags = '' ) {
$urlencoded_tags = array();
$tags_r = explode(',', $tags);
foreach($tags_r as $tag){
$urlencoded_tags[] = urlencode($tag);
}
$url = 'http://api.flickr.com/services/rest/?';
$url .= 'method=flickr.photos.search';
$url .= '&text=' . urlencode($query);
$url .= '&tags=' . implode(',', $urlencoded_tags);
$url .= '&sort=relevance';
$url .= '&safe_search=1';
$url .= '&content_type=4';
$url .= '&api_key=' . $this->flickr_key;
$url .= '&format=' . $this->format;
$url .= '&per_page=10';
$url .= '&media=photos';
$url .= '&privacy_filter=1';
$result = #file_get_contents( $url );
$json = substr( $result, strlen( "jsonFlickrApi(" ), strlen( $result ) - strlen( "jsonFlickrApi(" ) - 1 );
$photos = array();
$data = json_decode( $json, true );
if($data['stat'] != 'fail'){
$photos = $data['photos']['photo'];
return $photos;
}else{
return false;
}
}
}
And I'll just call it in like:
$flickr = new Flickr($flickr_key, $flickr_secret);
$query = 'Kaspersky Internet Security 2013';
$tags = 'software';
$results = $flickr->searchPhotos($query, $tags);
foreach($results as $img){
$src = "http://farm" . $img['farm'] . ".static.flickr.com/" . $img['server'] . '/' . $img['id'] . '_' . $img['secret'] . '_m.jpg';
?>
<img src="<?php echo $src; ?>"/>
<?php
}
The problem here is that I'm getting duplicate images from time to time.
I also tried using the phpflickr library. But I'm still having the same issues:
$flickr = new phpFlickr($api_key);
$args = array(
'text' => 'Kaspersky Internet Security 2013',
'tags' => 'software',
'per_page' => '10',
'safe_search' => '1',
'content_type' => '4',
'media' => 'photos',
'sort' => 'relevance',
'privacy_filter' => '1'
);
$results = $flickr->photos_search($args);
$hashes = array();
$sources = array();
$images = $results['photo'];
foreach($images as $img){
$src = "http://farm" . $img['farm'] . ".static.flickr.com/" . $img['server'] . '/' . $img['id'] . '_' . $img['secret'] . '_m.jpg';
$current_hash = sha1_file($src);
if(!in_array($current_hash, $hashes)){
?>
<img src="<?php echo $src; ?>" alt="">
<?php
}
$hashes[] = $current_hash;
}
As you can see from the above code I've used sha1_file method to compare the hashes of each of the images returned from flickr. But that's a big performance hit:
without sha1_file: 0.81311082839966
with sha1_file: 6.8974900245667
Any ideas what else can I do to prevent flickr from returning duplicates? As you can see I'm only returning 10 images and that's all I need. I've also tried to add as many arguments that matches my needs but still no luck. Thanks in advance!
try on API explorer, will this give you the same result?
I tried using the param you specified, it returns 34 result in total..

using str_replace before simple_html_dom

I'm using the simple HTML dom to grab scraped data and it's been working well. However, one of the source I have doesn't have any unique fields so I'm trying to str_replace and then grab the elements that I've renamed and then use simple_html_dom.
However, it doesn't work. my code is:
require('simple_html_dom.php');
// Create DOM from URL or file
$html = file_get_html('http://www.url.com');
$html = str_replace('<strong>','',$html);
$html = str_replace('</strong>','',$html);
$html = str_replace('<span class="pound">£</span>','',$html);
$html = str_replace('<td>','<td class="myclass">',$html);
foreach($html->find('td.myclass') as $element)
$price = $element->innertext;
$price = preg_replace('/[^(\x20-\x7F)]*/','', $price);
echo $price;
try
<?php
require('simple_html_dom.php');
// Create DOM from URL or file
$html = file_get_html( 'http://www.url.com' );
foreach( $html->find( 'td' ) as $element ) {
$price = trim( str_replace( "£", "", $element->plaintext ) );
}
$price = preg_replace('/[^(\x20-\x7F)]*/','', $price);
echo $price;
?>

Categories