Examples » Upload Images to TinyPic and Retrieve the URLs
TinyPic is a photo and video sharing service, all for free. They allow users to upload images and videos, and they return the short URL for the uploaded files. This is useful to save our web hosting bandwidth and quota.
Here are the steps we do when uploading the image to TinyPic:
- Open tinypic.com.
- Browse the image.
- Click the submit button.
- Take a note of the returned URLs.
And automate the task above using a few lines of code:
/**
* Uploading image to tinypic.com and retrieve the image's URL
*/
include 'phpWebHacks.php';
$h = new phpWebHacks;
/* tinypic.com */
$h->get('http://tinypic.com');
/* get the hidden fields */
$form = $h->parseForm('uploadform', &$action);
/* filetype = image, resize = default */
$form['file_type'] = 'image';
$form['dimension'] = '1600';
/* 'browse' the image to upload */
$file = array('the_file' => '/home/nash/elvita.jpg');
/* submit */
$page = $h->post($action, $form, $file);
/* It will show a 'click here to view the image' page
and then redirects using javascript.
Since javascript is not supported, we need to manually
parse the URL */
preg_match('/<a\s+href\s*=\s*"(.+)".*>/iU', $page, $url);
/* get the result page */
$h->get($url[1]);
/* and here are the URLs */
$form = $h->parseForm('email_form');
echo "HTML Code : " . $form['html-code'] . "\n";
echo "Forums : " . $form['img-code'] . "\n";
echo "Email : " . $form['email-url'] . "\n";
echo "Direct link : " . $form['direct-url'] . "\n";
?>
You might wonder where did I get those names: uploadform, file_type, dimension, the_file, etc. From the HTML source, of course :))
Update on October 19, 2009:
As noted like some readers below, Tinypic has removed the form named 'email_form' so the script above won't work. You have to replace the code after the last preg_match with this:
$page = $h->get($url[1]);
/* here is your URL */
preg_match('/\[IMG\](.+)\[\/IMG\]/si', $page, $m);
echo 'Direct link: ' . $m[1];
Raja on Sep 11, 2009:
It throw me a error like this
kemadruma on Oct 9, 2009:
Tyrone on Oct 14, 2009:
Warning: Call-time pass-by-reference has been deprecated in uploadPicture.php on line 36
Nash on Oct 19, 2009:
@Tyrone:
Yes call-time pass by reference has been deprecated in PHP 5.3 and above. Note that it is a warning, not an error. Suppress the warning by adding these lines to your script:
error_reporting(E_NONE);
ini_set('display_errors', 0);Or you can fix the code by yourself. Replace this line in phpWebHacks.php:
public function parseForm($name_or_id, $action = '', $str = '')to this:
public function parseForm($name_or_id, &$action = '', $str = '')Then you call the function with:
$form = $h->parseForm('form_id', $action);---
@kemadruma:
Yes tinypic has removed email_form. Maybe they want to block people like us
See the update above to workaround this.
Mbah Ableh on Jul 14, 2009: