i am having a class in some functions in this class. all the functions have variables. the code is written below
<?php
class myclass{
public function getresults{
$url = 'http://www.slideshare.net/api/2/search_slideshows?q=google';
echo $url;
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Your application name');
$query = curl_exec($ch);
$errorCode = curl_errno($ch);
curl_close($ch);
$array = (array) simplexml_load_string($query);
//echo '<pre>';
//print_r($array);
public $TotalResults;
$TotalResults = $array['Meta']->TotalResults;
echo "function is correct";
}
}
when i call this fun
echo $obj1->TotalResults;
this gives error to me. please help me and modify my code.
You incorrectly used member variables:
class myclass{
public $TotalResults; // <-- added member variable
public function getresults{
$url = 'http://www.slideshare.net/api/2/search_slideshows?q=google';
echo $url;
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Your application name');
$query = curl_exec($ch);
$errorCode = curl_errno($ch);
curl_close($ch);
$array = (array) simplexml_load_string($query);
//echo '<pre>';
//print_r($array);
$this->TotalResults = $array['Meta']->TotalResults; // <-- corrected
echo "function is correct";
}
}
and after you do $obj->getresults() (where $obj must be instantiated by $obj = new myclass(); before), the $obj->TotalResults should contain what you wanted.
Did it help?
Something like this :
<?php
class myclass {
public function getresults()
{
$url = 'http://www.slideshare.net/api/2/search_slideshows?q=google';
echo $url;
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Your application name');
$query = curl_exec($ch);
$errorCode = curl_errno($ch);
curl_close($ch);
$array = (array) simplexml_load_string($query);
//echo '<pre>';
//print_r($array);
public $TotalResults;
$TotalResults = $array['Meta']->TotalResults;
echo "function is correct";
}
}
$obj = new myclass;
echo $obj1->getresults();
Related
I am new to OOP. I am just learning and I have to use it to find the actual/final URL of a link that redirects.
Class ABC {
public function getWebPage($url, $redirectcallback = null){
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1) Gecko/20061024 BonEcho/2.0");
$html = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code == 301 || $http_code == 302) {
list($httpheader) = explode("\r\n\r\n", $html, 2);
$matches = array();
preg_match('/(Location:|URI:)(.*?)\n/', $httpheader, $matches);
$nurl = trim(array_pop($matches));
$url_parsed = parse_url($nurl);
if (isset($url_parsed)) {
if($redirectcallback){ // callback
$redirectcallback($nurl, $url);
}
$html = $this->getWebPage($nurl, $redirectcallback);
}
}
return $html;
}
}
The above function inside class call the same function again and again to find the actual url. However I am already calling the class in some other file
$obj = new ABC;
$url = "http://www.anrdoezrs.net/asd/?ak=123";
$someurl = $obj->getWebPage($url);
But this does not work. Please suggest.
Class ABC {
public function xyz($url){
$html = $this->xyz($url);
return $html;
}
}
In another class call it with
$obj = new ABC;
$url = "Some value";
$someurl = $obj->xyz($url);
I have issues with codeigniter recursive function which returns blank value. below is my function.
function recursive_data($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
$instaArr = (array) json_decode($output);
// print_r($instaArr); // print value here
if( $instaArr['pagination'] == "" ) {
return $instaArr['data'];
} else {
return $this->recursive_data($instaArr['pagination']->next_url);
}
}
I am calling this above function in another function like this
$return_data = $this->recursive_data($url);
It is returning blank value. while it is printing the value in commented code print_r($instaArr)
please use it as bellow.
function recursive_data($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
$instaArr = json_decode($output,true);
// print_r($instaArr); // print value here
if( $instaArr['pagination'] == "" ) {
return $instaArr['data'];
} else {
return $this->recursive_data($instaArr['pagination']->next_url);
}
}
What about this ?
function recursive_data($url)
{
$objCurlData = new stdClass();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
$instaArr = (array) json_decode($output);
// print_r($instaArr); // print value here
if( $instaArr['pagination'] == "" ) {
$objCurlData->data = $instaArr['data'];
} else {
$objCurlData->objChild = $this->recursive_data($instaArr['pagination']->next_url);
}
return $objCurlData;
}
Why do I get this error:
Undefined variable key_2captcha
I run this code to pass a CAPTCHA to 2captcha server:
<?php
$id_Captcha=0;
$key_2captcha="key2captcha";
function send_captcha($base_file){
$ch = curl_init("http://2captcha.com/in.php");
curl_setopt($ch, CURLOPT_POSTFIELDS,
array('method'=>"base64",
'key'=>$key_2captcha,
'numeric'=>1,
'max_len'=>1,
'body'=>$base_file,
'submit'=>'download and get the ID'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$postResult = curl_exec($ch);
curl_close($ch);
return $postResult;
}
function getSolveCaptcha($id_captcha){
$c = curl_init("http://2captcha.com/res.php?key=".$key_2captcha."&action=get&id=".$id_captcha);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$postResult = curl_exec($c);
curl_close($c);
return $postResult;
}
?>
I run this code in XAMPP.
I thinks you have a variabile scope resolution problem.
If you want to use the variable into a generic function, you have to pass this variable as parameter in the signature of function.
Not use variable as global because is a bad practice, you have to make generic function so you have to use generic parameter.
Try this code:
<?php
$id_Captcha=0;
$key_2captcha="key2captcha";
function send_captcha($base_file, $key_2captcha){
$ch = curl_init("http://2captcha.com/in.php");
curl_setopt($ch, CURLOPT_POSTFIELDS,
array('method'=>"base64",
'key'=>$key_2captcha,
'numeric'=>1,
'max_len'=>1,
'body'=>$base_file,
'submit'=>'download and get the ID'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$postResult = curl_exec($ch);
curl_close($ch);
return $postResult;
}
function getSolveCaptcha($id_captcha, $key_2captcha){
$c = curl_init("http://2captcha.com/res.php?key=".$key_2captcha."&action=get&id=".$id_captcha);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$postResult = curl_exec($c);
curl_close($c);
return $postResult;
}
//Call Example
send_captcha($base_file, $key_2captcha);
?>
Use below code use $key_2captcha with global. in both function. read variable scope in PHP
function getSolveCaptcha($id_captcha){
global $key_2captcha;
$c = curl_init("http://2captcha.com/res.php?key=".$key_2captcha."&action=get&id=".$id_captcha);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$postResult = curl_exec($c);
curl_close($c);
return $postResult;
}
Use below code with $GLOBALS — References all variables available in global scope
<?php
$id_Captcha=0;
$key_2captcha="key2captcha";
function send_captcha($base_file){
$ch = curl_init("http://2captcha.com/in.php");
curl_setopt($ch, CURLOPT_POSTFIELDS,
array('method'=>"base64",
'key'=>$GLOBALS['key_2captcha'],
'numeric'=>1,
'max_len'=>1,
'body'=>$base_file,
'submit'=>'download and get the ID'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$postResult = curl_exec($ch);
curl_close($ch);
return $postResult;
}
function getSolveCaptcha($id_captcha){
$c = curl_init("http://2captcha.com/res.php?key=".$GLOBALS['key_2captcha']."&action=get&id=".$id_captcha);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
$postResult = curl_exec($c);
curl_close($c);
return $postResult;
}
?>
Ref PHP.net
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
I am having a hard time finding out how to get a function to return a variable that I can use outside of the function, I have tried
return $response
and I have tried
return $response = $anothervariable
But the only way I have been able to get it to work is to echo the response and just put the html in there, I know there is a better way to do this, the problem is I can't figure it out. Any help would be appreciated!
function OpenCNAM($ph) {
$opencnamSID = '*****';
$opencnamTOKEN = '*****';
$query = "https://api.opencnam.com/v2/phone/".$ph."?format=text";
if(isset($opencnamSID)) { $query = "https://".$opencnamSID.":".$opencnamTOKEN."#api.opencnam.com/v2/phone/".$ph."?format=text"; }
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $query);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt ($ch, CURLOPT_TIMEOUT, 3);
$response = curl_exec($ch);
curl_close($ch);
if($response != "") {
echo '<span title="'.$response.'"> 888-452-1505</span>';
} else {
echo 'Nada';
}
}
OpenCNAM('8884521505');
return $response;
is correct statement. It will return $response variable if program flow reaches at that point.
You can also pass parameters to function by reference like &$any_variable to set it with the desire value inside the function and play with it outside the function, after the function call.
Remodify your code like this.
function OpenCNAM($ph) {
$opencnamSID = '*****';
$opencnamTOKEN = '*****';
$query = "https://api.opencnam.com/v2/phone/".$ph."?format=text";
if(isset($opencnamSID)) { $query = "https://".$opencnamSID.":".$opencnamTOKEN."#api.opencnam.com/v2/phone/".$ph."?format=text"; }
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $query);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt ($ch, CURLOPT_TIMEOUT, 3);
$response = curl_exec($ch);
curl_close($ch);
$str="";
if($response != "") {
$str= '<span title="'.$response.'"> 888-452-1505</span>';
} else {
$str= 'Nada';
}
return $str; //<---------- We are returning here
}
echo OpenCNAM('8884521505'); //<--- If you want to output.. or just $response = OpenCNAM('43535'); if you want to store it in a variable.
Just return the texts then you can do like this
function OpenCNAM($ph) {
//...
//...
if($response != "") {
return '<span title="'.$response.'"> 888-452-1505</span>';
} else {
return 'Nada';
}
}
$foo = OpenCNAM('8884521505');
Then, you can do what you want with $foo
try this
function OpenCNAM($ph)
{
$opencnamSID = '*****';
$opencnamTOKEN = '*****';
$query = "https://api.opencnam.com/v2/phone/".$ph."?format=text";
if(isset($opencnamSID)) { $query = "https://".$opencnamSID.":".$opencnamTOKEN."#api.opencnam.com/v2/phone/".$ph."?format=text"; }
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $query);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt ($ch, CURLOPT_TIMEOUT, 3);
$response = curl_exec($ch);
curl_close($ch);
if($response != "")
{
$res = '<span title="'.$response.'"> 888-452-1505</span>';
}
else
{
$res = 'Nada';
}
return $res;
}
$return_res = OpenCNAM('8884521505');
echo $return_res;
If you aren't going to use the returned data anywhere, then echo will do just fine for you.
This was answered in PHP echo function return value vs echo inside function