How do I insert this php code into my php file?

badwolfff
badwolfff used Ask the Experts™
on
I have a working version (modified) of the Sige plugin for Joomla 1.6
which can be downloaded from:
http://extensions.joomla.org/extensions/photos-a-images/photo-gallery/13762

Within this I have custom added a script which shortens long URLs manually.
The file sige.php is attached here:  sige.php
I shorten the long URLs that this plugin generates (for the facebook/twitter buttons) with the following code at the top of this file (lines 70-99):
function make_bitly_url($url,$login,$appkey,$format = 'xml',$version = '2.0.1') {
	$sql = "SELECT * FROM `url_cache` WHERE `before`='".mysql_real_escape_string($url)."' LIMIT 1";
	$check = mysql_query($sql) or die(mysql_error());
	if(mysql_num_rows($check)==1) {//we found it in cache
		$url = mysql_fetch_assoc($check);
		return $url['after'];
	}

	//create the URL
	$bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$appkey.'&format='.$format;

	//get the url
	//could also use cURL here
	$response = file_get_contents($bitly);

	//parse depending on desired format
	if(strtolower($format) == 'json') {
		$json = @json_decode($response,true);
		$sql = "INSERT INTO `url_cache` SET `before`='".mysql_real_escape_string($url)."', `after`='".mysql_real_escape_string($json['results'][$url]['shortUrl'])."'";
		mysql_query($sql) or die(mysql_error());
		return $json['results'][$url]['shortUrl'];
	}
	else //xml
	{
		$xml = simplexml_load_string($response);
		$sql = "INSERT INTO `url_cache` SET `before`='".mysql_real_escape_string($url)."', `after`='".mysql_real_escape_string('http://bit.ly/'.$xml->results->nodeKeyVal->hash)."'";
		mysql_query($sql) or die(mysql_error());
		return 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
	}
}

Open in new window


Later I call this code to shorten my URLs in real time with this code (lines 804-810):
$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 = make_bitly_url($url,'badwolfff','R_f650e553b78bb0569fc67dbc16a5de7c','json');

$html .= '<a href="http://www.facebook.com/sharer.php?u='.$u.'&t=Zuenelli - '.$imagename.'"  title="aggiungi a facebook" target="_blank"><img src="'.$mosConfig_live_site.'/plugins/content/sige/plugin_sige/facebook.png" /></a><a href="http://twitter.com/?status=Zuenelli propone - '.$imagename.' (cliccare sul seguente link per scoprire): '.$u.'"  title="pubblica su twitter" target="_blank"><img src="'.mosConfig_live_site.'/plugins/content/sige/plugin_sige/twitter.png" /></a>

Open in new window


The working versions can be tested on the following link (try clicking on the facebook/twitter links):
My test website

The problem is this:
at present I use the bit.ly service with my api login/key but I would like to use a custom url shortening service which runs from my own server.

I succeeded in doing this by following another web tutorial.
The code is as follows:
- short.php
<?php
$baseurl = 'http://localhost/'; //address to use as the first part of the short URLs (note trailing slash)
$sql_host = 'localhost'; //host of your mysql database (usually localhost)
$sql_user = 'root'; //mysql user with access to your database
$sql_pass = 'root'; //password for this user
$sql_db = 'turl'; //the name of your database
 
$db = mysql_connect($sql_host, $sql_user, $sql_pass);
mysql_select_db($sql_db, $db);
 
if(isset($_GET['k'])) {
   $k = mysql_real_escape_string($_GET['k'], $db);
   if($result = mysql_query("SELECT `url` FROM `turl` WHERE `key` = '" . $k . "'", $db)) {
      if(mysql_num_rows($result) > 0) {
         $row = mysql_fetch_row($result);
         header('HTTP/1.1 301 Moved Permanently');
         header('Location: ' . $row[0]);
         exit;
      }
   }
}
 
if(isset($_POST['submit'], $_POST['url'])) {
   if(filter_var($_POST['url'], FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED) !== false) {
      $url = mysql_real_escape_string($_POST['url'], $db);
      if($result = mysql_query("SELECT `key` FROM `turl` WHERE `url` = '" . $url . "'", $db)) {
         if(mysql_num_rows($result) > 0) {
            $row = mysql_fetch_row($result);
            $key = $row[0];
         }
      }
      if(!isset($key) && mysql_query("INSERT INTO `turl` (`url`) VALUES ('" . $url . "')", $db)) {
         $id = mysql_insert_id($db);
         $key = base_convert($id, 10, 36);
         mysql_query("UPDATE `turl` SET `key` = '" . $key . "' WHERE `id` = '" . $id . "'");
      }
      echo '<a href="' . $baseurl . $key . '" target="_blank">' . $baseurl . $key . '</a>';
   }
}
else {
?>
<form method="post" action="short.php">
<label>URL: <input type="text" name="url" id="url" /></label>
<br />
<input type="submit" name="submit" id="submit" value="Shorten" />
</form>
<?php
}
?>

Open in new window


.htaccess
RewriteEngine On
RewriteCond %{REQUEST_URI} \/([0-9a-z]+)$ [NC]
RewriteRule ^(.*) short.php?k=%1 [L]

Open in new window


sql code
CREATE TABLE `turl` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `key` VARCHAR(32) DEFAULT NULL,
  `url` text NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `key` (`key`)
);

Open in new window


A working example can be seen here:Working URL shortening example

**************************************************************************************************************

What I would like to do is to substitute the bit.ly short URL generation code in my sige.php with the working code from short.php. Sige.php generates URLs on the fly and I need my new code with the short.php script to generate all shortened URLs on the fly as my icons get created from my images folder and loaded on my page (same as how it works now with the bit.ly code).

How could I manage that? I am not a php expert so I would really appreciate the exact code that I need to modify/substitute in my sige.php document.

thanks in advance

p.s. I also assume that after I manage to do that I will have to leave the .htaccess file inside the
JoomlaSite/plugins/content/sige
folder - right?
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2011
Top Expert 2016

Commented:
Can you please ask us a question that we can answer?  This seems more like you need someone to write some custom code for you.  It that's the case, you would definitely want to hire a professional developer.  But if you are developing this yourself and you are stuck on something I am sure we can help with that.

Author

Commented:
Dear Ray,

I appreciate your point. However I am trying to learn myself and I am also trying at home to get a result. But, since I was not getting any results I thought I might ask someone for a suggestion.

The question may be long but in all truth all the code is working and what I really wanted to know is how to substitute or integrate about 15 lines of code with a similar kind of code. That is really all.

You have helped me in the past and I will definitely keep your point in mind but if you please read my question again all I want to do is substitute a working url shortener using bit.ly with another url shortener that uses my own domain to generate the shortened url.

thanks again

Author

Commented:
The simplified question is this:

How do I substitute this code:
 
function make_bitly_url($url,$login,$appkey,$format = 'xml',$version = '2.0.1') {
	$sql = "SELECT * FROM `url_cache` WHERE `before`='".mysql_real_escape_string($url)."' LIMIT 1";
	$check = mysql_query($sql) or die(mysql_error());
	if(mysql_num_rows($check)==1) {//we found it in cache
		$url = mysql_fetch_assoc($check);
		return $url['after'];
	}

	//create the URL
	$bitly = 'http://api.bit.ly/shorten?version='.$version.'&longUrl='.urlencode($url).'&login='.$login.'&apiKey='.$appkey.'&format='.$format;

	//get the url
	//could also use cURL here
	$response = file_get_contents($bitly);

	//parse depending on desired format
	if(strtolower($format) == 'json') {
		$json = @json_decode($response,true);
		$sql = "INSERT INTO `url_cache` SET `before`='".mysql_real_escape_string($url)."', `after`='".mysql_real_escape_string($json['results'][$url]['shortUrl'])."'";
		mysql_query($sql) or die(mysql_error());
		return $json['results'][$url]['shortUrl'];
	}
	else //xml
	{
		$xml = simplexml_load_string($response);
		$sql = "INSERT INTO `url_cache` SET `before`='".mysql_real_escape_string($url)."', `after`='".mysql_real_escape_string('http://bit.ly/'.$xml->results->nodeKeyVal->hash)."'";
		mysql_query($sql) or die(mysql_error());
		return 'http://bit.ly/'.$xml->results->nodeKeyVal->hash;
	}
}

Open in new window


with this?
 
<?php
$baseurl = 'http://localhost/'; //address to use as the first part of the short URLs (note trailing slash)
$sql_host = 'localhost'; //host of your mysql database (usually localhost)
$sql_user = 'root'; //mysql user with access to your database
$sql_pass = 'root'; //password for this user
$sql_db = 'turl'; //the name of your database
 
$db = mysql_connect($sql_host, $sql_user, $sql_pass);
mysql_select_db($sql_db, $db);
 
if(isset($_GET['k'])) {
   $k = mysql_real_escape_string($_GET['k'], $db);
   if($result = mysql_query("SELECT `url` FROM `turl` WHERE `key` = '" . $k . "'", $db)) {
      if(mysql_num_rows($result) > 0) {
         $row = mysql_fetch_row($result);
         header('HTTP/1.1 301 Moved Permanently');
         header('Location: ' . $row[0]);
         exit;
      }
   }
}
 
if(isset($_POST['submit'], $_POST['url'])) {
   if(filter_var($_POST['url'], FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED) !== false) {
      $url = mysql_real_escape_string($_POST['url'], $db);
      if($result = mysql_query("SELECT `key` FROM `turl` WHERE `url` = '" . $url . "'", $db)) {
         if(mysql_num_rows($result) > 0) {
            $row = mysql_fetch_row($result);
            $key = $row[0];
         }
      }
      if(!isset($key) && mysql_query("INSERT INTO `turl` (`url`) VALUES ('" . $url . "')", $db)) {
         $id = mysql_insert_id($db);
         $key = base_convert($id, 10, 36);
         mysql_query("UPDATE `turl` SET `key` = '" . $key . "' WHERE `id` = '" . $id . "'");
      }
      echo '<a href="' . $baseurl . $key . '" target="_blank">' . $baseurl . $key . '</a>';
   }
}
else {
?>
<form method="post" action="short.php">
<label>URL: <input type="text" name="url" id="url" /></label>
<br />
<input type="submit" name="submit" id="submit" value="Shorten" />
</form>
<?php
}
?>

Open in new window


Just for your information, with reference to the first code above (my current code using bit.ly) when I load my image gallery all the different urls for each image in the gallery are generated using this code:
 
$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 = make_bitly_url($url,'badwolfff','R_f650e553b78bb0569fc67dbc16a5de7c','json');

$html .= '&lt;a href=&quot;http://www.facebook.com/sharer.php?u='.$u.'&t=Zuenelli - '.$imagename.'&quot;  title=&quot;aggiungi a facebook&quot; target=&quot;_blank&quot;&gt;&lt;img src=&quot;'.$mosConfig_live_site.'/plugins/content/sige/plugin_sige/facebook.png&quot; /&gt;&lt;/a&gt;&lt;a href=&quot;http://twitter.com/?status=Zuenelli propone - '.$imagename.' (cliccare sul seguente link per scoprire): '.$u.'&quot;  title=&quot;pubblica su twitter&quot; target=&quot;_blank&quot;&gt;&lt;img src=&quot;'.mosConfig_live_site.'/plugins/content/sige/plugin_sige/twitter.png&quot; /&gt;&lt;/a&gt;

Open in new window


thanks
Acronis in Gartner 2019 MQ for datacenter backup

It is an honor to be featured in Gartner 2019 Magic Quadrant for Datacenter Backup and Recovery Solutions. Gartner’s MQ sets a high standard and earning a place on their grid is a great affirmation that Acronis is delivering on our mission to protect all data, apps, and systems.

Most Valuable Expert 2011
Top Expert 2016

Commented:
OK, let me see if I can paraphrase... Would I be on firm ground if I said it like this, "I want to write my own URL shortener."

Author

Commented:
Ho ray
In truth the custom url shortener exists and i have poster above a working code. All I asked is how I might integrate it into my existing working code with bit.ly shortener. So in truth I am not asking anyone to write me a personalized code but just want to know how I might substitute one working code with another. Please feel free to not participate but I don't understand why you are so irritated.
Most Valuable Expert 2011
Top Expert 2016

Commented:
Hey, badwolfff:  I'm not irritated at all.  It's a good question -- I just didn't understand the question.  A lot is lost when you can't communicate with voice and face.

Here is what I would suggest now.  Delete this question and repost it.  There are a lot of experts here who would assume that if I were engaged in the dialog that the question would get answered, so they might overlook it.  Let's not let that happen.  Obviously I will not object to deleting it, and when the question has zero responses beside it you will get some other eyes on the problem faster.  If I can figure it out I'll post a response.

Best regards, ~Ray

Author

Commented:
Thanks ray I will do as you suggest and tonight of course I myself will have another crack at it :)
Most Valuable Expert 2011
Top Expert 2016
Commented:
10-4.  Good luck with it, ~Ray

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial