Antworten auf deine Fragen:
Neues Thema erstellen

Links automatisch mittel tinyurl.com generieren

MyBad

localhorst

AW: Links automatisch mittel tinyurl.com generieren

Ich hab grad mal eben auf deren Seite geschaut. Scheint keine API zu geben. Mit bit.ly sollte es gehen. Da gibt es eine API, die du nutzen kannst um automatisch kurze URLs zu generieren.
 

MyBad

localhorst

AW: Links automatisch mittel tinyurl.com generieren

da würd wohl gehen...
ABER wozu und mit welchem sinn¿

gibt es einen grund aus seiner domain z. b. aus:
blafaselblubbblubb.tld eine
tinyurl.com/blafaselblubbblubb zu machen?¿?

Ich denke es macht Sinn, wenn man zum Beispiel seinen Usern die Möglichkeit bieten möchte eine Seite ber Twitter oder so zu verbreiten. Da sehe ich in jedem Falle ein Anwendungsgebiet.

Habe mal ein Plugin für xt:Commerce gesehen. Da kann der User Produkte direkt per Twitter-API weiter verbreiten. Damit die URLs dann eben nicht ewig lang sind, wird vorher über die bit.ly-API eine kurze URL generiert.
 
Zuletzt bearbeitet:

Christian

verpeilt & verschallert

AW: Links automatisch mittel tinyurl.com generieren

Hatte da mal was geschrieben:
PHP:
<?php


/**
 * @version $Id: class.httpconnection.php 200 2009-11-06 08:54:05Z Christian $
 */
/*
httpconnection.class.php
Version 1.1

Part of the PHP class collection
http://www.sourceforge.net/projects/php-classes/

Written by: Dennis Wronka
License: LGPL
*/
class httpconnection
{
    private $host;
    private $port;
    private $ssl;
    private $useragent;
    public function __construct ($host, $port = 80, $ssl = false, $useragent = 'Mozilla/5.0 (Windows; U; Windows NT 5.0; de; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4')
    {
        $this->host = $host;
        $this->port = $port;
        $this->ssl = $ssl;
        $this->useragent = $useragent;
    }
    private function decodereply ($reply)
    {
        $headend = strpos($reply, "\r\n\r\n") + 2;
        $head = substr($reply, 0, $headend);
        $httpversion = substr($head, 5, 3);
        $contentlength = '';
        $contentlengthstart = strpos($head, 'Content-Length:');
        if ($contentlengthstart != false) {
            $contentlengthstart += 16;
            $contentlengthend = strpos($head, "\r\n", $contentlengthstart);
            $contentlength = substr($head, $contentlengthstart, $contentlengthend - $contentlengthstart);
        }
        if ($httpversion == '1.0') {
            $datastart = $headend + 2;
            $body = substr($reply, $datastart, strlen($reply) - $datastart);
        } elseif ($httpversion == '1.1') {
            $encoding = '';
            $encodingstart = strpos($head, 'Transfer-Encoding:');
            if ($encodingstart != false) {
                $encodingstart += 19;
                $encodingend = strpos($head, "\r\n", $encodingstart);
                $encoding = substr($head, $encodingstart, $encodingend - $encodingstart);
            }
            if ($encoding == 'chunked') {
                $datasizestart = $headend + 2;
                $datasizeend = strpos($reply, "\r\n", $datasizestart);
                $datasize = hexdec(trim(substr($reply, $datasizestart, $datasizeend - $datasizestart)));
                $body = '';
                while ($datasize > 0) {
                    $chunkstart = $datasizeend + 2;
                    $body .= substr($reply, $chunkstart, $datasize);
                    $datasizestart = $chunkstart + $datasize + 2;
                    $datasizeend = strpos($reply, "\r\n", $datasizestart);
                    $datasize = hexdec(trim(substr($reply, $datasizestart, $datasizeend - $datasizestart)));
                }
            } else {
                $datastart = $headend + 2;
                $datasize = $contentlength;
                $body = substr($reply, $datastart, $datasize);
            }
        }
        $code = substr($head, 9, 3);
        $serverstart = strpos($head, 'Server:') + 8;
        $serverend = strpos($head, "\r\n", $serverstart);
        $server = substr($head, $serverstart, $serverend - $serverstart);
        $contenttype = '';
        $contenttypestart = strpos($head, 'Content-Type:');
        if ($contenttypestart != false) {
            $contenttypestart += 14;
            $contenttypeend = strpos($head, "\r\n", $contenttypestart);
            $contenttype = substr($head, $contenttypestart, $contenttypeend - $contenttypestart);
        }
        $location = '';
        $locationstart = strpos($head, 'Location:');
        if ($locationstart != false) {
            $locationstart += 10;
            $locationend = strpos($head, "\r\n", $locationstart);
            $location = substr($head, $locationstart, $locationend - $locationstart);
            $location_array = explode('?', $location);
            $parameters = '';
            if (isset($location_array[1])) {
                $parameters = $location_array[1];
            }
            $location = array('uri' => $location_array[0] , 'parameters' => $parameters);
            if (empty($parameters)) {
                unset($location['parameters']);
            }
        }
        $cookies = array();
        $cookiestart = stripos($head, 'Set-Cookie:');
        while ($cookiestart != false) {
            $cookiestart += 12;
            $cookieend = strpos($head, "\r\n", $cookiestart);
            $cookie = substr($head, $cookiestart, $cookieend - $cookiestart);
            $cookie_array = explode(';', $cookie);
            $expirydate = '';
            $path = '';
            for ($x = 0; $x < count($cookie_array); $x ++) {
                $cookie_array[$x] = explode("=", $cookie_array[$x]);
                if ($x == 0) {
                    $name = $cookie_array[$x][0];
                    $value = $cookie_array[$x][1];
                } else {
                    if (trim($cookie_array[$x][0]) == 'expires') {
                        $expirydate = array('string' => $cookie_array[$x][1] , 'timestamp' => strtotime($cookie_array[$x][1]));
                    } elseif (trim($cookie_array[$x][0]) == 'path') {
                        $path = $cookie_array[$x][1];
                    }
                }
            }
            $cookie = array('name' => $name , 'value' => $value , 'path' => $path , 'expirydate' => $expirydate);
            if (empty($path)) {
                unset($cookie['path']);
            }
            if (empty($expirydate)) {
                unset($cookie['expirydate']);
            }
            $cookies[] = $cookie;
            $cookiestart = stripos($head, 'Set-Cookie:', $cookieend);
        }
        $headdata = array('raw' => $head , 'httpversion' => $httpversion , 'code' => $code , 'server' => $server , 'contentlength' => $contentlength , 'contenttype' => $contenttype , 'location' => $location , 'cookies' => $cookies);
        if ((empty($contentlength)) && ($contentlength != 0)) {
            unset($headdata['contentlength']);
        }
        if (empty($contenttype)) {
            unset($headdata['contenttype']);
        }
        if (empty($location)) {
            unset($headdata['location']);
        }
        if (empty($cookies)) {
            unset($headdata['cookies']);
        }
        $data = array('head' => $headdata , 'body' => $body);
        return $data;
    }
    public function head ($uri = '/', $parameters = false, $cookies = false, $authuser = '', $authpassword = '')
    {
        if ($this->ssl == true) {
            $connection = @fsockopen('ssl://' . $this->host, $this->port);
        } else {
            $connection = @fsockopen($this->host, $this->port);
        }
        if ($connection == false) {
            return false;
        }
        if ((empty($uri)) || ($uri{0} != '/')) {
            $uri = '/' . $uri;
        }
        if (($parameters != false) && (! empty($parameters))) {
            $paramstring = '?' . $parameters;
        } else {
            $paramstring = '';
        }
        if (($cookies != false) && (! empty($cookies))) {
            $cookiestring = 'Cookie: ' . $cookies . "\r\n";
        } else {
            $cookiestring = '';
        }
        if (! empty($authuser)) {
            $authstring = 'Authorization: Basic ' . base64_encode($authuser . ':' . $authpassword) . "\r\n";
        } else {
            $authstring = '';
        }
        $host = $this->host;
        if ($this->port != 80) {
            $host .= ':' . $this->port;
        }
        fwrite($connection, 'HEAD ' . $uri . $paramstring . " HTTP/1.1\r\nHost: " . $host . "\r\nUser-Agent: " . $this->useragent . "\r\n" . $cookiestring . $authstring . "Connection: close\r\n\r\n");
        $reply = '';
        while (! feof($connection)) {
            $reply .= @fread($connection, 128);
        }
        fclose($connection);
        $data = $this->decodereply($reply);
        return $data;
    }
    public function get ($uri = '/', $parameters = false, $cookies = false, $authuser = '', $authpassword = '')
    {
        if ($this->ssl == true) {
            $connection = @fsockopen('ssl://' . $this->host, $this->port);
        } else {
            $connection = @fsockopen($this->host, $this->port);
        }
        if ($connection == false) {
            return false;
        }
        if ((empty($uri)) || ($uri{0} != '/')) {
            $uri = '/' . $uri;
        }
        if (($parameters != false) && (! empty($parameters))) {
            $paramstring = '?' . $parameters;
        } else {
            $paramstring = '';
        }
        if (($cookies != false) && (! empty($cookies))) {
            $cookiestring = 'Cookie: ' . $cookies . "\r\n";
        } else {
            $cookiestring = '';
        }
        if (! empty($authuser)) {
            $authstring = 'Authorization: Basic ' . base64_encode($authuser . ':' . $authpassword) . "\r\n";
        } else {
            $authstring = '';
        }
        $host = $this->host;
        if ($this->port != 80) {
            $host .= ':' . $this->port;
        }
        fwrite($connection, 'GET ' . $uri . $paramstring . " HTTP/1.1\r\nHost: " . $host . "\r\nUser-Agent: " . $this->useragent . "\r\n" . $cookiestring . $authstring . "Connection: close\r\n\r\n");
        $reply = '';
        while (! feof($connection)) {
            $reply .= @fread($connection, 128);
        }
        fclose($connection);
        $data = $this->decodereply($reply);
        return $data;
    }
    public function post ($uri = '/', $parameters = false, $cookies = false, $fileparameters = false, $mimetypes = false, $authuser = '', $authpassword = '')
    {
        if ($this->ssl == true) {
            $connection = @fsockopen('ssl://' . $this->host, $this->port);
        } else {
            $connection = @fsockopen($this->host, $this->port);
        }
        if ($connection == false) {
            return false;
        }
        if ((empty($uri)) || ($uri{0} != '/')) {
            $uri = '/' . $uri;
        }
        if (($cookies != false) && (! empty($cookies))) {
            $cookiestring = 'Cookie: ' . $cookies . "\r\n";
        } else {
            $cookiestring = '';
        }
        if (! empty($authuser)) {
            $authstring = 'Authorization: Basic ' . base64_encode($authuser . ':' . $authpassword) . "\r\n";
        } else {
            $authstring = '';
        }
        $host = $this->host;
        if ($this->port != 80) {
            $host .= ':' . $this->port;
        }
        if (($fileparameters == false) || (empty($fileparameters))) {
            if (($parameters != false) && (! empty($parameters))) {
                $contentlength = strlen($parameters);
                fwrite($connection, 'POST ' . $uri . " HTTP/1.1\r\nHost: " . $host . "\r\nUser-Agent: " . $this->useragent . "\r\n" . $cookiestring . $authstring . "Connection: close\r\n");
                fwrite($connection, "Content-Type: application/x-www-form-urlencoded\r\nContent-Length: " . $contentlength . "\r\n\r\n" . $parameters);
            } else {
                fwrite($connection, 'POST ' . $uri . " HTTP/1.1\r\nHost: " . $host . "\r\nUser-Agent: " . $this->useragent . "\r\n" . $cookiestring . $authstring . "Connection: close\r\n\r\n");
            }
        } else {
            $params = explode('&', $parameters);
            for ($x = 0; $x < count($params); $x ++) {
                $params[$x] = explode('=', $params[$x]);
            }
            $fileparams = explode('&', $fileparameters);
            for ($x = 0; $x < count($fileparams); $x ++) {
                $fileparams[$x] = explode('=', $fileparams[$x]);
            }
            if (($mimetypes != false) && (! empty($mimetypes))) {
                $mimetypeparams = explode(',', $mimetypes);
            }
            if (! isset($mimetypeparams)) {
                $mimetypeparams = array();
            }
            while (count($mimetypeparams) < count($fileparams)) {
                $mimetypeparams[] = 'application/octet-stream';
            }
            $boundary = '-------------------------' . substr(md5(uniqid()), 0, 15);
            $content = '';
            for ($x = 0; $x < count($fileparams); $x ++) {
                $postfile = fopen($fileparams[$x][1], 'r');
                $filecontent = fread($postfile, filesize($fileparams[$x][1]));
                fclose($postfile);
                $content .= '--' . $boundary . "\r\n";
                $content .= 'Content-Disposition: form-data; name="' . $fileparams[$x][0] . '"; filename="' . $fileparams[$x][1] . '"' . "\r\n";
                $content .= 'Content-Type: ' . $mimetypeparams[$x] . "\r\n\r\n";
                $content .= $filecontent . "\r\n";
            }
            for ($x = 0; $x < count($params); $x ++) {
                $content .= '--' . $boundary . "\r\n";
                $content .= 'Content-Disposition: form-data; name="' . $params[$x][0] . '"' . "\r\n\r\n";
                if (! empty($params[$x][1])) {
                    $content .= $params[$x][1] . "\r\n";
                }
            }
            $content .= '--' . $boundary . "--\r\n";
            $contentlength = strlen($content);
            fwrite($connection, 'POST ' . $uri . " HTTP/1.1\r\nHost: " . $host . "\r\nUser-Agent: " . $this->useragent . "\r\n" . $cookiestring . $authstring . "Connection: close\r\n");
            fwrite($connection, 'Content-Type: multipart/form-data; boundary=' . $boundary . "\r\nContent-Length: " . $contentlength . "\r\n\r\n");
            fwrite($connection, $content, $contentlength);
        }
        $reply = '';
        while (! feof($connection)) {
            $reply .= @fread($connection, 128);
        }
        fclose($connection);
        $data = $this->decodereply($reply);
        return $data;
    }
}


/**
 * is.gd API
 * 
 * @version $Id: ISGD.php 217 2010-01-21 17:05:24Z Christian $
 * @package Link
 * @requires httpconnection
 */
define('PARSE_HTML_TIDY_DOM', 1);
define('PARSE_HTML_RAW', 2);
class Link_ISGD extends httpconnection
{
    /**
     * @var string API host
     */
    private static $apiHost = 'is.gd';
    /**
     * @var string API URL
     */
    private static $apiPath = '/api.php?longurl=';
    /**
     * @var string encoding method
     */
    private static $encMethod = 'urlencode';
    /**
     * @var string table for localcache
     */
    public static $localCacheTable = 'isgd_links';
    /**
     * @var object Link_ISGD
     */
    public static $instance;
    /**
     * @var object sql2
     */
    private static $db;
    /**
     * @var boolean use local cache
     */
    public static $localCache = false;
    /**
     * @var string to encode
     */
    public $toEncode;
    /**
     * @var string result
     */
    public $result;
    /**
     * @var int errorlevel
     */
    public static $errorLevel = E_USER_WARNING;
    /**
     * constructor
     */
    public function __construct ()
    {
        parent::__construct(self::$apiHost);
    }
    /**
     * return instance
     * @return object Link_ISGD
     */
    public static function getInstance ()
    {
        if (! self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    /**
     * shorten a signle link
     * @return result link
     */
    public function shortenLink ($strLink)
    {
        $this->setToEncode($strLink);
        $this->setResult($this->fetch());
        return $this->getResult();
    }
    /**
     * scan $strHTML for href-links and shorten them
     * @return string html
     */
    public function shortenHTML ($strHTML, $method = PARSE_HTML_RAW)
    {
        switch ($method) {
            case PARSE_HTML_RAW:
            default:
                return preg_replace_callback("/href=[\"|']([^\"]*)[\"|']/i", array($this , 'xparse'), $strHTML);
                break;
            case PARSE_HTML_TIDY_DOM:
                //tidy up html
                $tidy = tidy_parse_string(stripslashes($strHTML));
                $tidy->cleanRepair();
                //load as domdocument
                $dom = new DOMDocument();
                $dom->loadHTML($tidy);
                $l = $dom->getElementsByTagName('a');
                for ($i = 0; $i < $l->length; $i ++) {
                    foreach ($l->item($i)->attributes as $attr) {
                        if($attr->name=='href')
                        {
                            $l->item($i)->setAttribute('href',$this->shortenLink(urlencode($attr->value)));
                        }
                    }
                }
                return $dom->saveHTML();
                break;
        }
    }
    /**
     * for internal purpose only
     * callback function for shortenHTML's preg_replace
     * @return string
     */
    public static function xparse ($hits)
    {
        if (isset($hits[1])) {
            if (strtolower(substr($hits[1], 0, 4)) == 'http') {
                $short = self::getInstance()->shortenLink($hits[1]);
                return str_replace($hits[1], $short, $hits[0]);
            }
        }
        return $hits[0];
    }
    /**
     * fire request
     * 
     * @return string response body
     * @see httpconnection::get()
     * @link http://is.gd/api_info.php
     */
    private function fetch ()
    {
        $s = $this->getToEncode();
        $url = self::$apiPath . $s;
        $result = parent::get($url);
        if ($result['head']['code'] == "200") {
            return $result['body'];
        } else {
            trigger_error('Fehler beim Linkkuerzen! ' . strip_tags($result['body']), self::getErrorLevel());
            /**
             * since at this point $s is already
             * URLENCODED, we reverse this step to
             * have no unforeseen results
             */
            return urldecode($s);
        }
    }
    /**
     * set error level to be triggered once an error appears 
     * default: E_USER_WARNING
     */
    public static function setErrorLevel ($level = E_USER_WARNING)
    {
        self::$errorLevel = $level;
    }
    /**
     * @return int errorlevel
     */
    public static function getErrorLevel ()
    {
        return self::$errorLevel;
    }
    /**
     * @return string
     */
    public function getResult ()
    {
        return $this->result;
    }
    /**
     * @return string
     */
    public function getToEncode ()
    {
        return $this->toEncode;
    }
    /**
     * @param string $result
     */
    public function setResult ($result)
    {
        $this->result = $result;
    }
    /**
     * @param string $toEncode
     */
    public function setToEncode ($toEncode)
    {
        $this->toEncode = $toEncode;
    }
    /**
     * @return boolean
     */
    public function getLocalCache ()
    {
        return self::$localCache;
    }
    /**
     * @param boolean $localCache
     */
    public function setLocalCache ($localCache)
    {
        self::$localCache = $localCache;
    }
    /**
     * @return object
     */
    public function getDb ()
    {
        return self::$db;
    }
    /**
     * @param object $db
     */
    public function setDb ($db)
    {
        self::$db = $db;
    }
}


//Beispiel:
$isgd = new Link_ISGD();

//Einfachen Link kuerzen:
$shortURL = $isgd->shortenLink('http://google.de');

//Komplettes HTML kuerzen:
$shortenedHTML = $isgd->shortenHTML('....',PARSE_HTML_RAW); //Oder: PARSE_HTML_TIDY_DOM benötigt Tidy und DOMDocument
?>

Benutzt allerdings die is.gd API
 
Zuletzt bearbeitet:

AlexanderBo

Gesperrt

AW: Links automatisch mittel tinyurl.com generieren

der aufruf würde ja immer mit tinyurl.com/x beginnen...

ich warte mal auf den TE ;-)
 

koma05

Aktives Mitglied

Ich denke es macht Sinn, wenn man zum Beispiel seinen Usern die Möglichkeit bieten möchte eine Seite ber Twitter oder so zu verbreiten. Da sehe ich in jedem Falle ein Anwendungsgebiet.
genau so ist es... es geht auch um twitter ;)


es gibt doch eine api-schnittstelle. und zwar lautet diese mittels folgender funktion wird eine tinyurl generiert und an das skript übermittelt:
PHP:
function gettinyurl( $url ) {
 
  // get tiny url via api-create.php
  $fp = fopen( 'http://tinyurl.com/api-create.php?url='.$url, 'r' ); // open (read) api-create.php with long url as get parameter
  if( $fp ) { // check if open was ok
    $tinyurl = fgets( $fp ); // read response
    if( $tinyurl && !empty($tinyurl) ) // check if response is ok
      $url = $tinyurl; // set response as url
    fclose( $fp ); // close connection
  }
 
  // return
  return $url; // return (tiny) url
}
hab hier noch ne zweite lösung gefunden:

PHP:
function TinyURL($u){

return file_get_contents('http://tinyurl.com/api-create.php?url='.$u);
}

      $url = 'http://www.google.de/';
      $tiny = TinyURL($url);
      echo('The TinyURL of "'.$url.'" is "'.$tiny.'"');
ist diese oder die vorher genannte lösung vorzuziehen - und warum?
dank
 
Zuletzt bearbeitet von einem Moderator:

Christian

verpeilt & verschallert

AW: Links automatisch mittel tinyurl.com generieren

Im Grunde besteht zwischen beiden Versionen kein Unterschied, mit der Ausname, dass sich eventuelle HTTP Fehler mit der ersten Version besser kontrollieren lassen, während file_get_contents einfach nur einen PHP Fehler auslösen würde, wenn Du bspw. eine fehlerhafte Anfrage sendest.
Dieses Fehlerabfangen wird aber auch in der ersten Version nicht umgesetzt, von daher ist im Vergleich die 2. Version wohl einfacher zu handlen (I herz Anglizismen!).
 
Bilder bitte hier hochladen und danach über das Bild-Icon (Direktlink vorher kopieren) platzieren.
Antworten auf deine Fragen:
Neues Thema erstellen

Willkommen auf PSD-Tutorials.de

In unseren Foren vernetzt du dich mit anderen Personen, um dich rund um die Themen Fotografie, Grafik, Gestaltung, Bildbearbeitung und 3D auszutauschen. Außerdem schalten wir für dich regelmäßig kostenlose Inhalte frei. Liebe Grüße senden dir die PSD-Gründer Stefan und Matthias Petri aus Waren an der Müritz. Hier erfährst du mehr über uns.

Stefan und Matthias Petri von PSD-Tutorials.de

Nächster neuer Gratisinhalt

03
Stunden
:
:
25
Minuten
:
:
19
Sekunden

Flatrate für Tutorials, Assets, Vorlagen

Zurzeit aktive Besucher

Keine Mitglieder online.

Statistik des Forums

Themen
118.565
Beiträge
1.538.067
Mitglieder
67.488
Neuestes Mitglied
Andrew56524
Oben