Share Counter only works on one post? - php

I have some code of which only works on one post, however i want it to work on all posts not just the one that has been listed i get the following error:
(Fatal error: Cannot redeclare class shareCount in counter/share-count.php on line 3)
loop.php (this is from my loop code for per post)
<?
require("counter/share-count.php");
$obj=new shareCount("http://google.com");
echo "Tweets: ".$obj->get_tweets();
echo "<br>Facebook: ".$obj->get_fb();
echo "<br>Google+: ".$obj->get_plusones();
?>
share-count.php (this is the file thats executable on request)
<?
class shareCount {
private $url,$timeout;
function __construct($url,$timeout=10) {
$this->url=rawurlencode($url);
$this->timeout=$timeout;
}
function get_tweets() {
$json_string = $this->file_get_contents_curl('http://urls.api.twitter.com/1/urls/count.json?url=' . $this->url);
$json = json_decode($json_string, true);
return isset($json['count'])?intval($json['count']):0;
}
function get_fb() {
$json_string = $this->file_get_contents_curl('http://api.facebook.com/restserver.php?method=links.getStats&format=json&urls='.$this->url);
$json = json_decode($json_string, true);
return isset($json[0]['total_count'])?intval($json[0]['total_count']):0;
}
function get_plusones() {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, "https://clients6.google.com/rpc");
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_POSTFIELDS, '[{"method":"pos.plusones.get","id":"p","params":{"nolog":true,"id":"'.rawurldecode($this->url).'","source":"widget","userId":"#viewer","groupId":"#self"},"jsonrpc":"2.0","key":"p","apiVersion":"v1"}]');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
$curl_results = curl_exec ($curl);
curl_close ($curl);
$json = json_decode($curl_results, true);
return isset($json[0]['result']['metadata']['globalCounts']['count'])?intval( $json[0]['result']['metadata']['globalCounts']['count'] ):0;
}
private function file_get_contents_curl($url){
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
$cont = curl_exec($ch);
if(curl_error($ch))
{
die(curl_error($ch));
}
return $cont;
}
}
?>

Your included file counter/share-count.php defines the shareCount class every time it is included, which is why you are seeing the error. You can fix this by either using require_once() or check to see if the class is already defined using class_exists() and only defining it if the result is false.
Using require_once() to replace require():
require_once("counter/share-count.php");
// ... rest of your code
Using class_exists():
if ( ! class_exists( 'shareCount' ) ):
class shareCount{
// your class implementation
}
endif; // class_exists

Related

get data from URL using file_get_contents and cURL

I am using codeigniter framework.
I want to retrieve the data from the URL provided. I already tried this answers: tried.
Problem is that when i access the url that time it is printing the data. but when i try it with file_get_contents function, it is not going to print any data.
<?php
$url ='https://test.com/getSessionData';
$test = file_get_contents($url);
$t = json_decode($test);
var_dump($t);
?>
That url returns json data like:
{
"email": "test#t.com",
"LOGIN": true,
"name": "testing",
"logintype": "ca"
}
Also tried using cURL:
<?php
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
$curl_response = curl_exec($curl);
curl_close($curl);
$curl_jason = json_decode($curl_response, true);
print_r($curl_jason);
?>
But it is not working and it returns empty. i have checked that allow_url_fopen is on.
This might helpful
http://php.net/manual/en/migration56.openssl.php
So code looks like this:
<?php
$arrContextOptions=array(
"ssl"=>array(
"cafile" => "/path/to/bundle/ca-bundle.crt",
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
$response = file_get_contents("https://test.com/getSessionData", false, stream_context_create($arrContextOptions));
echo $response; ?>
This is the class I said:
/**
* Created by PhpStorm.
* User: rain
* Date: 15/11/2
* Time: 下午4:08
*/
class MyCurlLibrary{
public static function getRequest($url,Array $data=array(),$isNeedHeader=0){
$ch = curl_init();
if($data){
$bindQuery = http_build_query($data);
$url.="?".$bindQuery;
}
curl_setopt($ch, CURLOPT_URL, $url);
//if need return
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//this is for https
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_HEADER, $isNeedHeader);//if contains header
//this is for web redirect problem
//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
public static function postRequest($url,Array $data=array()){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// post Data
curl_setopt($ch, CURLOPT_POST, 1);
// post variable
if($data){
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
}
$output = curl_exec($ch);
curl_close($ch);
//return data
return $output;
}
}
/**
* sample
*
* //test Data
$url = "http://localhost:8080/test/test.php";//改文件有代码 print_r($_GET); print_r($_POST)
$data = array('a'=>'b','c'=>'d',8=>666,888);
//test get function
$result = MyCurl::getRequest($url,$data);
//test post function
$result = MyCurl::postRequest($url,$data);
//print result
var_dump($result);
*
*
*/

php cURL instantiate remote class

New to cURL and trying to load PHP file to instantiate a class with below code.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$n = new Test_cURL();
I have cross checked and cURL is enable. Also cross check with that file from remote url is loading by
if (curl_exec($ch) !== FALSE) {
return true;
}
else {
return false;
}
But when I am creating new instance it is giving me error.
Fatal error: Class 'Test_cURL' not found in
So how can I load a file allow to instantiate a class from remote?
UPDATE
All required details including sites URL and filename
<?php
/**
* Remote Class
* URL: http://localhost/php-lib/lib.php
* filename: lib.php
*/
class Test_cURL
{
public $msg;
function __construct($message)
{
$this->msg = $message;
}
public function f_msg($add)
{
return $this->msg . ' is the property and ' . $add . ' is the parameter!';
}
}
/**
* cURL file on other site (could be other server)
* URL: http://test-site/index.php
* Filename: index.php
*/
$url = "http://localhost/php-lib/lib.php";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_NOBODY, 0);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result=curl_exec($ch);
eval($result);
$n = new Test_cURL('loader message');
echo $n->f_msg('method message');
/**
* Error message
*/
Fatal error: Class 'Test_cURL' not found in /var/www/html/test-site/index.php on line 26
You can use file_get_contents then use file_put_contents to store file locally.
include the file and instantiate the class.
Reference: http://blog.kotowicz.net/2010/07/re-hardening-php-how-to-securely.html
Use eval() to run your class and CURLOPT_NOBODY should be false so that it can return string.
Curl code:
<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, '$url');
curl_setopt($ch, CURLOPT_NOBODY, 0);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$result=curl_exec($ch);
eval($result);
$n = new Test_cURL();
echo $n->name;
Class Code:
<?php
echo '
class Test_cURL{
public $name="rasmus lerdorf";
}';

Caching custom social share count in WordPress

I really like having a share counter on my blogposts. I noticed that it actually encourages visitors to share the content themselves. Because there are no WordPress sharecount plugins out there that I actually find satisfying (most of them make way to much calls), I wrote the code myself.
It works perfect, but still slows down my site. So I would rather it caches and refreshes once per hour or so. I don't know how to manage this though … Any ideas?
This is what I put in the themes function file:
class shareCount {
private $url,$timeout;
function __construct($url,$timeout=10) {
$this->url=rawurlencode($url);
$this->timeout=$timeout;
}
function get_tweets() {
$json_string = $this->file_get_contents_curl('http://urls.api.twitter.com/1/urls/count.json?url=' . $this->url);
$json = json_decode($json_string, true);
return isset($json['count'])?intval($json['count']):0;
}
function get_fb() {
$json_string = $this->file_get_contents_curl('http://api.facebook.com/restserver.php?method=links.getStats&format=json&urls='.$this->url);
$json = json_decode($json_string, true);
return isset($json[0]['total_count'])?intval($json[0]['total_count']):0;
}
private function file_get_contents_curl($url){
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
$cont = curl_exec($ch);
if(curl_error($ch))
{
die(curl_error($ch));
}
return $cont;
}
}
And this is what I use in single.php:
<!-- Begin mod: Add share counter -->
<span class="share-count">
<?php
$obj=new shareCount(get_permalink( $post->ID ));
echo $obj->get_tweets() + $obj->get_fb();
?>
</span>
<span class="share-text">
keer gedeeld
</span>
<!-- End mod: Add share counter -->
Then I also add some css.
Like vicente said, you should use the built in transient cache.
private function file_get_contents_curl($url){
// Create unique transient key
$transientKey = 'sc_' + md5($url);
// Check cache
$cache = get_transient($transientKey);
if($cache) {
return $cache;
}
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
$cont = curl_exec($ch);
if(curl_error($ch))
{
die(curl_error($ch));
}
// Cache results for 1 hour
set_transient($transientKey, $cont, 60*60);
return $cont;
}

simple curl wrapper using abstract class Methods?

im trying to have a good practice at abstract class Methods so i created a simple curl wrapper class but unfortunately it doesn't work .
abstract
<?php
abstract class curl{
private $url;
public function __construct($url){
$this->url = $url ;
}
public function curl_grab_page()
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
ob_start(); // prevent any output
return curl_exec ($ch); // execute the curl command
ob_end_clean(); // stop preventing output
curl_close ($ch);
}
public abstract function getHTML();
}
?>
child
<?php
class google extends curl{
private $url;
function __construct($url) {
parent::__construct($url);
}
function curl_grab_page(){
parent::curl_grab_page();
}
function getHTML(){
return $this->curl_grab_page();
}
}
and this is how i call in my front page .
<?php
include 'classes/class.curl.php';
include 'classes/class.google.php';
$google = new google('http://www.google.com/');
echo $google->getHTML();
?>
it didn't print out anything .
i tried the function separately and it goes fine
Looks like you are not localizing the results of the output buffer before calling return, try this:
public function curl_grab_page()
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, $this->url);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
// Don't need any output buffering b/c you set CURLOPT_RETURNTRANSFER to true, which means the results will be returned via curl_exec
//ob_start(); // prevent any output
//return curl_exec ($ch); // execute the curl command
//ob_end_clean(); // stop preventing output
$contents = curl_exec($ch);
curl_close ($ch);
return $contents;
}
And the child class:
<?php
class google extends curl{
// Don't need this, if you set the parent's scope to protected which means child class has access
// private $url;
function __construct($url) {
parent::__construct($url);
}
// Don't really need this method unless you plan on doing some custom logic
function curl_grab_page(){
// If you keep this method I added a return here so we can get the results of the call
return parent::curl_grab_page();
}
function getHTML(){
return $this->curl_grab_page();
}
}

PHP Curl How to extract header's

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://test.com");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, 'x=32423');
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
if(curl_exec($ch) === false)
{
echo 'Curl error: ' . curl_error($ch);
}
else
{
'OK';
}
This is what outputted,when i run this page
access_token=AAAdsfsdfds32432fadfcazdfadsfadsfdas
How do i extract this and pass it a variable?
There is a typo in your postfields. The postfields should be as follows:
curl_setopt($ch, CURLOPT_POSTFIELDS, array('x'=>'32423'));
instead of:
curl_setopt($ch, CURLOPT_POSTFIELDS, 'x=32423'');
First off, you need to change your CURLOPT_HEADERS to true, and you need
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
and
$result=curl_exec($ch)
if( $result=== false)
Then, according to an answer I saw elsewhere on SO, this should get you the headers:
list($headers,$content) = explode("\r\n\r\n",$result,2);
foreach (explode("\r\n",$headers) as $hdr)
print_r($hdr); //see what it gives you and then edit this accordingly.
echo $content;
Sounds like you just want
$token = end(explode('=', $access_token_string));

Categories