Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

How do I send a variable from one PHP file to another and get the result back?

Posted on 2011-04-29
16
Medium Priority
?
478 Views
Last Modified: 2012-05-11
I have a joomla plugin where I generate a URL on the fly by combining different elements as you can see below (this file sige.php is included):

$html .= '<a href="http://www.facebook.com/sharer.php?u='.$mosConfig_live_site.'/plugins/content/sige/plugin_sige/socialshare.php?img='.rawurlencode($mosConfig_live_site.$rootfolder.$_images_dir_.'/Midsize/'.$images[$a]['filename']).'&name='.rawurlencode($title_iptc).'&caption='.rawurlencode($caption_iptc).'"  title="aggiungi a facebook" target="_blank"><img src="'.$mosConfig_live_site.'/plugins/content/sige/plugin_sige/facebook.png" /></a>';

The first part which generates the URL on the fly is indicated in bold above.
The problem with this URL is that it is too long and a part of it is cut off by facebook share.php script and also it is too long to be added on to twitter.

I would like to send the URL result of the above code to an external class file called shortenURLonthefly.php which is attached here.
This external PHP class takes this URL and converts it into a shortened URL by processing it on the site is.gd

I need this resulting URL to go back to my original file where I would like to use it to add on facebook / twitter.

How do I send this URL out from sige.php to shortenURLonthefly.php and get the back to sige.php as a variable?

thanks in advance

sige.php
shortenURLonthefly.php
0
Comment
Question by:badwolfff
  • 11
  • 4
16 Comments
 
LVL 7

Expert Comment

by:Vimal DM
ID: 35490090
Hai,

The following function will help you lot. and more will give an idea of getting the querystring url and have them in a variable and return the vaules

      function formquerystring () {
            foreach($_REQUEST as $index=>$value) {
            //print_r($value);exit;
                  $querystring .= "&". $index ."=". $value;
            }
            return $querystring;
      }

       

                            or


All the requested values can be fetched and keep in  the array variable and return that array from the class function.
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 35492606
You can test this somewhat simplified and abbreviated code example on my server here:
http://www.laprbass.com/RAY_temp_shorten_url.php

I am not sure I understand what you mean by "send the URL result of the above code to an external class" -- is that to mean that the external class is part of a web service that you want to call?  If so, you would be calling a service to call a service.  Maybe a more efficient way of handling this is to just put the class definition and the call right into the code where you generate the long URL.  Just a thought. ~Ray
<?php // RAY_temp_shorten_url.php
error_reporting(E_ALL);

class ShortUrl
{
    public function __construct()
    {
        $this->url = 'http://is.gd/api.php?longurl=';
    }

    public function setURL($longURL)
    {
        $this->action_url = $this->url . urlencode($longURL);
    }

    public function getURL()
    {
        $u = file_get_contents($this->action_url);
        return $u;
    }
}

$s = new ShortURL;
$s->setUrl('http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_26984944.html');
$u = $s->getUrl();

echo
'Click Here: <a target="_blank" href="'
. $u
. '">'
. $u
. '</a>'
. PHP_EOL
;

Open in new window

0
 

Author Comment

by:badwolfff
ID: 35499938
Dear Ray,

thanks for shortening and optimizing the script. It works perfectly.
However my original question remains.
Allow me to explain it again more clearly.

I have a file called sige.php and updated version of which you can download from here.
Within this file I generate a URL on the fly (see line 815 through 819) with a code that looks like:

$mosConfig_live_site.'/plugins/content/sige/plugin_sige/socialshare.php?img='.rawurlencode($mosConfig_live_site.$rootfolder.$_images_dir_.'/Midsize/'.$images[$a]['filename']).'&amp;name='.rawurlencode($imagename)

This URL is then applied immediately to an icon (such as facebook or twitter).
Please see the pluginresult.jpg attached to see the output of the code.

Since this URL is too long* I also have the shortenURLonthefly.php in the same folder as the sige.php (which I am happy to use your updated version - thanks).
What I am trying to do is somehow from within the sige.php contact the shortenURLonthefly.php and get it to send the shortened URL that it generate back to my sige.php so that I may apply this new shortened URL to the icon. Could you show me how to do that?

Either this or please teach me how to integrate this shortenURLonthefly.php code into my sige.php and how to use it from within the same file.

thanks in advance.

sige.php

* The URL is too long so facebook's share.php trims a part of it and on twitter it cannot be added as it goes beyond their letter-count. Also the mailto: script does not work as it trims the URL.
pluginresult.jpg
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:badwolfff
ID: 35499940
Dear Vimalmaria,

thanks for your reply. My URLs are all generated on the fly. So I need to shorten them on the fly and cannot make and store any array for all combinations possible. (If I have correctly understood your suggestion.)

Please read the full explanation above as to what I am trying to do. Maybe you could suggest something that could lead me in the right direction?

thanks agian
0
 

Author Comment

by:badwolfff
ID: 35500047
Dear Ray,

Just to add to what you have suggested.
I took your file and put it in the following location (within the root of my site):
/libraries/joomla/sige/ShortUrl.php

Then at the top of the within the sige.php I added this line:
jimport( 'joomla.sige.ShortUrl' )

I am attaching here this new version of sige.php.
In line 815 when I try to start using the code
$s = new ShortURL;
my site stops loading at all.

Maybe this is closer to the solution you suggested? But I am obviously still doing something wrong here. Please help.

Thanks again
ShortUrl.php
sige.php
0
 
LVL 111

Accepted Solution

by:
Ray Paseur earned 2000 total points
ID: 35500905
I can't look at this again until much later today, but I can offer a suggestion that might help.  Think of the demonstration script I posted above as being your "sige" script.  Copy the class in line 4-21 into your sige script and call it as shown in line 23-25 of the code snippet at ID:35492606.  HTH, and if not, I can look at this again later.  Best, ~Ray
0
 

Author Comment

by:badwolfff
ID: 35501364
IT WORKS!
You are genius!
But I guess you already know that since your rank on this site is "Genius" :)

thanks so much for pointing me in the right direction and saving me hours of work!
0
 

Author Comment

by:badwolfff
ID: 35501612
Ray Help!
It works but there is some problem!
The first few times there is no problem - then all of a sudden my plugin stops loading the thumbnails.
Why do you think that might be happening?

I am sending you the entire plugin folder.
Please help as I need to finish this assignment by tomorrow!

thanks in advance
sige.zip
plugin-sige-v1.6-1-1.zip
0
 

Author Comment

by:badwolfff
ID: 35501623
These are images of how it works at first (the link that it generates everytime is perfect).
Then after I click a few images or change section (each section has a sige gallery) - it stops working (see second jpg attached).
This is very strange behaviour - as soon as I comment out your code it works again perfectly. Of course with your code commented out I can't generate the shortened URL! :(

 works at first then it stops working
0
 

Author Comment

by:badwolfff
ID: 35501625
You may test it's working on:

http://www.absolutproject.com/zuenelli/

The galleries are under the link
SOLUZIONI D'ARREDO

the site is still a work in progress but I need to finish coding by tomorrow!
0
 

Author Comment

by:badwolfff
ID: 35502626
Hmm... I've fixed the problem using my old shorten script.
Perhaps you could still tell me why your script gave problems?
I am curious
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 35504072
Well, since it is early morning here I have not had any time to look over the issues you've got with this set of scripts.  If you want to post code here at EE, please use the code snippet instead of posting ZIP files.  For a variety of reasons I am reluctant to open ZIP files from unfamiliar sources.  I am sure you can understand.

The image at ID:35501623 contains white text on a black background that starts "function file_get_contents" but there is more to the message (the reason for failure) and that is cut off.  To diagnose what might be wrong with the script we would need to see the rest of the message.  It might be found in the source of the HTML, but unfortunately it is obscured by the view we have on the screen shot.  I went to  the page at http://www.absolutproject.com/zuenelli/ and did not see any failure, so a detailed set of instructions telling how to get the failure would be helpful.

file_get_contents() returns either a string or FALSE.  You might want to add a test for the FALSE condition and print out the contents of the URL variable that was sent to file_get_contents().
http://us2.php.net/manual/en/function.file-get-contents.php

As with any web service, when you call a foreign site like the is.gd API you are at the mercy of the foreign site.  It is possible that the foreign site may have returned strange information or may have timed out (though I do not think that is likely in this case).  My guess about this particular failure is that something in the URL that was passed to file_get_contents() may have been unusable, thus triggering a notice or warning.  For example if you send file_get_contents() a bogus URL you will get something like this:

Warning: file_get_contents(XXX) [function.file-get-contents]: failed to open stream: No such file or directory in /home/{account}/public_html/RAY_temp_shorten_url.php
0
 

Author Comment

by:badwolfff
ID: 35504263
yes i get your point
the is.gd site allows only so many generates per minute then it goes into temp ban and does not allow any more output for another minute so after every minute of usage my gallery stops working as the input is not deciphrable by your code. So I guess your code is good after all but perhaps is.gd is sending back a warning instead of a url after every minute of usage. In fact with your code everything worked fine for the first minute. So basically I went back to my old code and using your suggestion to add the class at the top of my file I called bit.ly (which does not have any temp bans if you go and get their personalized API code) and now everything works fine.

thanks again
0
 
LVL 111

Expert Comment

by:Ray Paseur
ID: 35504284
You're welcome.  I am not sure of the rest of the design of this web site, but I know that if I found myself calling is.gd more than once for the same URL, I might consider storing the long URLs and the short URLs in my own data base and trying that before I called is.gd.  It would cut down on the need for outside services and it would make your web site run faster.  

Thanks for the points - it's an interesting question, ~Ray
0
 

Author Comment

by:badwolfff
ID: 35507531
Ray, sorry for the disturbance.
Just wanted to say that your code works faster than my original class (which I am using now). I am pasting both classes below. You originally edited my urlshortener class and converted it into a shortened smarter version which worked very fast (even though is.gd started banning me).
Could you kindly convert my actual class (I am using only the bit.ly part) using your slim syntax?

your class:
class ShortUrl
{
	public function __construct()
    {
        $this->url = 'http://is.gd/api.php?longurl=';
    }

    public function setURL($longURL)
    {
		$this->action_url = $this->url . urlencode($longURL);
    }

    public function getURL()
    {
		$u = file_get_contents($this->action_url);
        return $u;
    }
}

Open in new window


my current class which I would like you to modify:
class ShortUrl
{
	public function __construct()
    {
        $this->url = 'http://is.gd/api.php?longurl=';
    }

    public function setURL($longURL)
    {
		$this->action_url = $this->url . urlencode($longURL);
    }

    public function getURL()
    {
		$u = file_get_contents($this->action_url);
        return $u;
    }
}

Open in new window


I call this class using the following syntax:
$url = ($mosConfig_live_site."/plugins/content/sige/plugin_sige/socialshare.php?img=".$mosConfig_live_site.$rootfolder.$_images_dir_."/Midsize/".$images[$a]['filename']."&name=".$imagename);
$u = ShortUrl::create($url,'bitly','badwolfff','R_f650e553b78bb0569fc67dbc16a5de7c');

Open in new window


Could you please help?
class ShortUrl {

	public static function create($url,$provider='tinyurl',$user='',$key='') {
		$api_url = sprintf(self::api($provider),urlencode($url),$user,$key);
		return self::inspect($provider,self::execute($api_url));
	}

	private static function execute($url) {
		$ch = curl_init();
		curl_setopt ($ch, CURLOPT_URL, $url);
		curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
		$text = curl_exec($ch);
		curl_close($ch);
		return $text;
	}

	private static function inspect($provider,$xml) {
		if(!empty($xml)) {
			switch(strtolower(trim($provider))){
				case "bitly":
					$o = new SimpleXMLElement($xml);
					return (string)$o->results->nodeKeyVal->shortUrl;
					break;
				case "trim":
					$o = new SimpleXMLElement($xml);
					return (string)$o->url;
					break;
				case "isgd":
				case "hexio":
				default:
					return $xml;
			}
		}
		return false;
	}

	private static function api($provider) {
		switch(strtolower(trim($provider))){
			case "bitly":
				$return = "http://api.bit.ly/shorten?version=2.0.1&format=xml&longUrl=%s&login=%s&apiKey=%s";
				break;
			case "isgd":
				$return = "http://is.gd/api.php?longurl=%s";
				break;
			case "hexio":
				$return = "http://hex.io/api-create.php?url=%s";
				break;
			case "digg":
				$return = "http://services.digg.com/url/short/create?url=%s&appkey=%s&type=xml";
				break;
			case "trim":
				$return = "http://api.tr.im/v1/trim_url.xml?url=%s";
				break;
			default:
				$return = "http://tinyurl.com/api-create.php?url=%s";
		}
		return $return;
	}
}

Open in new window

0
 

Author Comment

by:badwolfff
ID: 35507557
sorry about the mess above.
the order of the code embed is:

your class (you can recognize it - for some reason it has been pasted twice)

my current code is at the end of my post (the long code)

and the syntax I use to call it is in the middle (2 lines)

thx again
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
Suggested Courses
Course of the Month21 days, 1 hour left to enroll

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question