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
Related
I am trying to return data to my variable $item_id but the variable returns empty. Am i not returning the data the right way ??
item_id should return "Alert" which is coming from the index function in serverMonitor.php.
Please advice. Thank you
Items.php
function rest_state()
{
$id = 1;
$item_id = $this->pass_to_res($id);
return $item_id //this should return "Alert"
}
function pass_to_res($id)
{
$url = "https://example.com/serverMonitor?id=$id";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
$result = curl_exec($ch);
curl_close ($ch);
return $result;
}
serverMonitor.php
function index() {
$id = htmlentities($_GET['id']);
$word = "Alert";
return $word;
}
Return values from a function are not always visible to the visitor. You should use echo, print or print_r.
function index() {
$id = htmlentities($_GET['id']);
$word = "Alert";
echo $word;
return true;
}
You can also use JSON with json_encode to encoding
function index() {
$id = htmlentities($_GET['id']);
$word = "Alert";
echo json_encode(['word' => $word]);
return true;
}
And json_decode to decoding:
function pass_to_res($id)
{
$url = "https://example.com/serverMonitor?id=$id";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
$result = curl_exec($ch);
curl_close ($ch);
$result = json_decode($result);
return isset($result['word']) ? $result['word'] : false;
}
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;
}
I was using following code to decode the tinyurl from twitter:
function MyURLDecode($url)
{
$ch = #curl_init($url);
#curl_setopt($ch, CURLOPT_HEADER, TRUE);
#curl_setopt($ch, CURLOPT_NOBODY, TRUE);
#curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
#curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$url_resp = #curl_exec($ch);
preg_match('/Location:\s+(.*)\n/i', $url_resp, $i);
if (!isset($i[1]))
{
return $url;
}
return $i[1];
}
$url = MyURLDecode($url);
This using this result to get tweet count value:
function get_twitter_url_count($url) {
$encoded_url = urlencode($url);
$content = #file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' . $encoded_url);
return $content ? json_decode($content)->count : 0;
}
Above code works fine. But due to some issue I need to change the Url Decoding function which is as below:
function TextAfterTag($input, $tag)
{
$result = '';
$tagPos = strpos($input, $tag);
if (!($tagPos === false))
{
$length = strlen($input);
$substrLength = $length - $tagPos + 1;
$result = substr($input, $tagPos + 1, $substrLength);
}
return trim($result);
}
function expandUrlLongApi($url)
{
$format = 'json';
$api_query = "http://api.longurl.org/v2/expand?" .
"url={$url}&response-code=1&format={$format}";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $api_query );
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($ch, CURLOPT_HEADER, false);
$fileContents = curl_exec($ch);
curl_close($ch);
$s1=str_replace("{"," ","$fileContents");
$s2=str_replace("}"," ","$s1");
$s2=trim($s2);
$s3=array();
$s3=explode(",",$s2);
$s4=TextAfterTag($s3[0],(':'));
$s4=stripslashes($s4);
return $s4;
}
This code gives decoded url correctly, infact with better accuracy then previous one but now result of this does not works with this function:
function get_twitter_url_count($url) {
$encoded_url = urlencode($url);
$content = #file_get_contents('http://urls.api.twitter.com/1/urls/count.json?url=' . $encoded_url);
return $content ? json_decode($content)->count : 0;
}
Rather givig correct count value, it always gives 0.
Can someone tell me what is wrong here?
full code:
<?php
function TextAfterTag($input, $tag)
{
$result = '';
$tagPos = strpos($input, $tag);
if (!($tagPos === false))
{
$length = strlen($input);
$substrLength = $length - $tagPos + 1;
$result = substr($input, $tagPos + 1, $substrLength);
}
return trim($result);
}
function expandUrlLongApi($url)
{
$format = 'json';
$api_query = "http://api.longurl.org/v2/expand?" .
"url={$url}&response-code=1&format={$format}";
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, $api_query );
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($ch, CURLOPT_HEADER, false);
$fileContents = curl_exec($ch);
/* preg_match('/Location:\s+(.*)\n/i', $fileContents, $i);
if (!isset($i[1]))
{
return '';
}
else
$fileContents = $i[1]; */
curl_close($ch);
$s1=str_replace("{"," ","$fileContents");
$s2=str_replace("}"," ","$s1");
$s2=trim($s2);
$s3=array();
$s3=explode(",",$s2);
$s4=TextAfterTag($s3[0],(':'));
$s4=stripslashes($s4);
return $s4;
}
$url = expandUrlLongApi('http://t.co/SFdM0wjtGA');
echo "Url is : $url <br/>";
$url = get_twitter_url_count($url);
?>
I'm trying to code a redirect checker, to check if a URL is search engine friendly. It has to check if a URL is redirected or not, and if it's redirected it has to tell if it's SEO friendly (301 status code) or not (302/304).
Here's something similiar I've found: http://www.webconfs.com/redirect-check.php
It also should be able to follow multiple redirects (e.g. from A to B to C) and tell me that A redirects to C.
This is what I got so far, but it doesn't work quite right (example: when typing in www.example.com it doesnt find the redirect to www.example.com/page1)
<?php
// You can edit the messages of the respective code over here
$httpcode = array();
$httpcode["200"] = "Ok";
$httpcode["201"] = "Created";
$httpcode["302"] = "Found";
$httpcode["301"] = "Moved Permanently";
$httpcode["304"] = "Not Modified";
$httpcode["400"] = "Bad Request";
if(count($_POST)>0)
{
$url = $_POST["url"];
$curlurl = "http://".$url."/";
$ch = curl_init();
// Set URL to download
curl_setopt($ch, CURLOPT_URL, $curlurl);
// User agent
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
// Include header in result? (0 = yes, 1 = no)
curl_setopt($ch, CURLOPT_HEADER, 0);
// Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
// Download the given URL, and return output
$output = curl_exec($ch);
$curlinfo = curl_getinfo($ch);
if(($curlinfo["http_code"]=="301") || ($curlinfo["http_code"]=="302"))
{
$ch = curl_init();
// Set URL to download
curl_setopt($ch, CURLOPT_URL, $curlurl);
// User agent
curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"]);
// Include header in result? (0 = yes, 1 = no)
curl_setopt($ch, CURLOPT_HEADER, 0);
// Should cURL return or print out the data? (true = return, false = print)
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Timeout in seconds
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// Download the given URL, and return output
$output = curl_exec($ch);
$curlinfo = curl_getinfo($ch);
echo $url." is redirected to ".$curlinfo["url"];
}
else
{
echo $url." is not getting redirected";
}
// Close the cURL resource, and free system resources
curl_close($ch);
}
?>
<form action="" method="post">
http://<input type="text" name="url" size="30" />/ <b>e.g. www.google.com</b><br/>
<input type="submit" value="Submit" />
</form>
Well if you want to record every redirect you have to implement it yourself and turn off the automatic "location following":
function curl_trace_redirects($url, $timeout = 15) {
$result = array();
$ch = curl_init();
$trace = true;
$currentUrl = $url;
$urlHist = array();
while($trace && $timeout > 0 && !isset($urlHist[$currentUrl])) {
$urlHist[$currentUrl] = true;
curl_setopt($ch, CURLOPT_URL, $currentUrl);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
$output = curl_exec($ch);
if($output === false) {
$traceItem = array(
'errorno' => curl_errno($ch),
'error' => curl_error($ch),
);
$trace = false;
} else {
$curlinfo = curl_getinfo($ch);
if(isset($curlinfo['total_time'])) {
$timeout -= $curlinfo['total_time'];
}
if(!isset($curlinfo['redirect_url'])) {
$curlinfo['redirect_url'] = get_redirect_url($output);
}
if(!empty($curlinfo['redirect_url'])) {
$currentUrl = $curlinfo['redirect_url'];
} else {
$trace = false;
}
$traceItem = $curlinfo;
}
$result[] = $traceItem;
}
if($timeout < 0) {
$result[] = array('timeout' => $timeout);
}
curl_close($ch);
return $result;
}
// apparently 'redirect_url' is not available on all curl-versions
// so we fetch the location header ourselves
function get_redirect_url($header) {
if(preg_match('/^Location:\s+(.*)$/mi', $header, $m)) {
return trim($m[1]);
}
return "";
}
And you use it like that:
$res = curl_trace_redirects("http://www.example.com");
foreach($res as $item) {
if(isset($item['timeout'])) {
echo "Timeout reached!\n";
} else if(isset($item['error'])) {
echo "error: ", $item['error'], "\n";
} else {
echo $item['url'];
if(!empty($item['redirect_url'])) {
// redirection
echo " -> (", $item['http_code'], ")";
}
echo "\n";
}
}
It's possible that my code isn't fully thought out, but I guess it's a good start.
Edit
Here's some sample Output:
http://midas/~stefan/test/redirect/fritzli.html -> (302)
http://midas/~stefan/test/redirect/hansli.html -> (301)
http://midas/~stefan/test/redirect/heiri.html
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();