Skip to content

Instantly share code, notes, and snippets.

@matysanchez
Last active September 2, 2016 08:28
Show Gist options
  • Save matysanchez/8607114 to your computer and use it in GitHub Desktop.
Save matysanchez/8607114 to your computer and use it in GitHub Desktop.
Upload remote image with Lithium #li3
<?php
namespace app\controllers;
use app\models\Uploads;
class UploadsController extends \lithium\action\Controller {
public function index() {
$upload = Uploads::first($this->request->id);
return compact('upload');
}
}
?>
<?=$this->html->image("/images/{$upload->_id}.{$upload->extension}"); ?>
<?php
// Add this lines to your media.php
use lithium\net\http\Media;
Media::type('jpg', 'image/jpeg', array('cast' => false, 'encode' => function($data) {
return $data['upload']->file->getBytes();
}));
// If you want, you can add more formats, like jpeg, png, gif, etc...
?>
<?php
namespace app\models;
class Uploads extends \lithium\data\Model {
// Let's use MongoDb GridFS.
protected $_meta = array('source' => 'fs.files');
}
?>
<?php
namespace app\models;
class Uploads extends \lithium\data\Model {
// Let's use MongoDb GridFS.
protected $_meta = array('source' => 'fs.files');
/**
* This function get all the information of the remote file.
* It's similar to $_FILES, have the same parameters.
*
*
* To work with https:// please use openssl extension (add it to php.ini)
*
*/
public static function getRemoteImage($url) {
// Put the file in the temp folder
$tempName = tempnam('/tmp', 'php_files');
// Get the original filename
$originalName = basename(parse_url($url, PHP_URL_PATH));
// Raw of the image
$imgRawData = file_get_contents($url);
// Get the extension of the file (jpg, jpeg, gif, png, ...)
$extension = pathinfo($originalName, PATHINFO_EXTENSION);
file_put_contents($tempName, $imgRawData);
$data['file'] = array(
'name' => $originalName,
'type' => "image/$extension", // please improve me :) TODO
'tmp_name' => $tempName,
'error' => 0,
'size' => strlen($imgRawData)
);
$data['extension'] = $extension;
return $data;
}
public static function uploadPicture($url) {
// Use getRemoteImage to get all the info
$data = self::getRemoteImage($url);
$save = self::create(array(
'type' => 'file', // Let lithium knows that you are working with a file
'file' => $data['file'], // All the information
'extension' => $data['extension']
));
$success = $save->save();
// I know... but... this is for debug.
if ($success) {
return $save;
} else {
return $save->errors(); // If you want you can use li3 flash message here
}
}
}
?>
<?php
// Add this line to your routes.php
Router::connect('/images/{:id:[0-9a-f]{24}}.{:type}', 'Uploads::index'); // Feel free to modify this line
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment