In my application users creating articles and adding images to it if user wont add a image, that application must search for it in google images. I'm googling it quite long but still can't find which tools do I need to achieve this.
EDIT
I tried Mimos approach but now something going wrong and now I get:
NotReadableException in AbstractDecoder.php line 302:
Image source not readable
When i tried to save the image from url
ArticlesController store method:
public function store(ArticleRequest $request)
{
if ($request->hasFile('file')) {
$file = Input::file('file');
$imgTitle = $request->title;
$imagePath = 'uploads/' . $imgTitle . '.jpg';
$request->image_path = $imagePath;
Article::create(array('title' => $request->title,
'body' => $request->body,
'image_path' => $imagePath));
Image::make($file)->resize(300, 200)->save($imagePath);
} else {
// $file = Input::file('file');
$imgTitle = $request->title;
$query = $imgTitle;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=" . urlencode($query));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = json_decode(curl_exec($ch));
// $file = file_get_contents($output);
curl_close($ch);
$imagePath = 'uploads/' . $imgTitle . '.jpg';
$request->image_path = $imagePath;
Article::create(array('title' => $request->title,
'body' => $request->body,
'image_path' => $imagePath));
Image::make($output)->resize(300, 200)->save($imagePath);
}
}
<?php
$query = 'Foobar';
$ch = curl_init();
// set url
curl_setopt($ch, CURLOPT_URL, "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=".urlencode($query));
//return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// $output contains the output string as json
$output = json_deocde(curl_exec($ch));
// close curl resource to free up system resources
curl_close($ch);
But I don't recommend to let a program decide what image it should take. You will maybe get a problem with copyright. Better set a default pic.
Related
I don't know why this is not working. I am trying to download a image from a URL then sent it via CURL. POST request the path with var_dump is working, but with CURL it doesn't work
The error is
Warning: curl_file_create() expects parameter 1 to be a valid path, string given
// define('TMP', __DIR__ . DIRECTORY_SEPARATOR . 'tmp');
/**
* #param $url
* #return string
*/
function dlImage($url) {
$save_dir = TMP . DIRECTORY_SEPARATOR;
$filename = basename($url);
$save = $save_dir.$filename;
file_put_contents($save,file_get_contents($url));
return $save;
}
function upload( $body, $title, $type, $type_real, $subCat, $poster = null, $imdbUrl = null)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'xxxx');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
$data = [
'key' => 'xxxx',
'type' => $type,
'subtype' => $subCat,
'type_real' => $type_real,
'title' => $title,
'posterUpload' => curl_file_create(realpath(dlImage($poster)),'image/jpeg'),
'imdbUrl' => $imdbUrl,
];
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$result = curl_exec($ch);
curl_close($ch);
var_dump($result);
}
// path is working fine
dlimage output (var_dump) : string(113)
"C:\laragon\www\api\tmp\MV5BNDliY2E1MjUtNzZkOS00MzJlLTgyOGEtZDg4MTI1NzZkMTBhXkEyXkFqcGdeQXVyNjMwMzc3MjE#.jpg"
add more error checking, replace
file_put_contents($save,file_get_contents($url));
with
$content=file_get_contents($url);
if(!is_string($content)){
throw new \RuntimeException("failed to fetch url {$url}");
}
if(($len=strlen($content))!==($written=file_put_contents($save,$content))){
throw new \RuntimeException("could only write {$written}/{$len} bytes to file {$save}");
}
then you should probably get an errorlog explaining where things went wrong, and my best guess is that things went wrong with file_get_contents() and/or file_put_contents().
I have uploaded file to google drive with curl API. But I want to upload file to specific folder. I have also tried with folder id in API url like: https://www.googleapis.com/upload/drive/v3/files/folder_id?uploadType=media
add_action('wpcf7_before_send_mail', 'save_application_form');
function save_application_form($WPCF7_ContactForm) {
$wpcf7 = WPCF7_ContactForm :: get_current();
$submission = WPCF7_Submission :: get_instance();
if ($WPCF7_ContactForm->id == 8578) {
if ($submission) {
$submited = array();
//$submited['title'] = $wpcf7->title();
$submited['posted_data'] = $submission->get_posted_data();
$uploaded_files = $submission->uploaded_files();
$name = $submited['posted_data']["Name"];
$position_test = $submited['posted_data']["Position"];
$email = $submited['posted_data']["Email"];
$phone = $submited['posted_data']["phone"];
$message = $submited['posted_data']["Message"];
$position = $submited['posted_data']["AttachYourCV"];
// $test2 = $_FILES['AttachYourCV']['name'];
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$cf7_file_field_name = 'AttachYourCV';
$image_location = $uploaded_files[$cf7_file_field_name];
$mime_type = finfo_file($finfo, $image_location);
$token = GetRefreshedAccessToken('client_id', 'refresh_token', 'client_secret');
$ch = curl_init();
curl_setopt_array($ch, array(
CURLOPT_URL => 'https://www.googleapis.com/upload/drive/v3/files?uploadType=media',
CURLOPT_HTTPHEADER => array(
'Content-Type:' . $mime_type, // todo: runtime detection?
'Authorization: Bearer ' . $token
),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => file_get_contents($image_location),
CURLOPT_RETURNTRANSFER => 1
));
$response = curl_exec($ch);
$id = json_decode($response, TRUE);
$get_id = $id['id'];
curl_close($ch);
if (isset($id['id'])) {
$get_id = $id['id'];
$post_fields = array();
$folder_id = '1-9r8oVsAfV_iJmYh1cZYPMvE9Qhv8RLA';
// remove extension
$this_file_name = explode('.', $position);
// submit name field
$post_fields['name'] .= $this_file_name[0];
$post_fields['parents'] = $folder_id[1];
$ch2 = curl_init();
curl_setopt_array($ch2, array(
CURLOPT_URL => 'https://www.googleapis.com/drive/v3/files/' . $get_id,
CURLOPT_HTTPHEADER => array(
'Content-Type:application/json', // todo: runtime detection?
'Authorization: Bearer ' . $token
),
CURLOPT_POST => 1,
CURLOPT_CUSTOMREQUEST => 'PATCH',
CURLOPT_POSTFIELDS => json_encode($post_fields),
CURLOPT_RETURNTRANSFER => 1
));
$response = curl_exec($ch2);
if ($response === false) {
$output = 'ERROR: ' . curl_error($ch2);
} else {
$output = $response;
}
// close second request handler
curl_close($ch2);
}
}
I have added another curl call but still didn't get file in folder. My file untitled issue solved with this way.
Uploading files to google drive is a two part thing. (note it can be done as a single call but if you want to add the corect data its best to do it as two)
create Adds the initial meta data for the file. Name, media type, and location that being its parent directory.
Second the actual upload of the file itself.
Note: a file uploaded without first sending the metadata will create a dummy metadata most often with a title of the file being "unknown."
Create
When you do your create of the inertial metadata. You need to add the parents in this inital call the field is called parents[] you need to add the file id there. I cant help you do this as your not adding the code for it.
Upload
By default the file is uploaded into the root folder unless you add a parent folder id for the file.
If you check the documentation you will find the optional query parms
Try using &addParents=[folderId]
Example:
https://www.googleapis.com/upload/drive/v3/files?uploadType=media&addParents=1bpHmln41UI-CRe5idKvxrkIpGKh57T32
If you originally created the metadata for the file in the root directory and then try to upload the file to a different directory i suspect that the upload will create new metadata. These two calls need to be done the same. Your create should have parents set.
post body
$data = array("name" => "test.jpg", "parents" => array("123456"));
$data_string = json_encode($data);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
In my Controller I have a function called get which sends the client a file. When a user clicks a link which calls the get function it works properly.
I have another function called get_veeva which first downloads the file from veeva to the server, then calls the get function to send the file to the user. This does not work properly. get_veeva downloads the file correctly, calls get, but the user doesn't receive the file, instead I just get a blank page. I know the file permissions and ownership are not the problem as I've tested by hardcoding the veeva files to the media class params in get and hitting get directly using the first method. Neither function has a View. Here are the two functions:
function get($name, $ext, $original_name, $mime)
{
$this->viewClass = 'Media';
$params = array(
'id' => sprintf("%s.%s", $name, $ext),
'name' => basename($original_name, '.' . $ext),
'download' => true,
'ext' => $ext,
'mimeType' => $mime,
'path' => APP . "webroot/uploads" . DS
);
$this->set($params);
}
public function get_veeva($id = null)
{
$this->autoRender = false;
$asset = $this->Asset->findById($id);
$vault = $asset['VeevaVault'];
App::import('Vendor', 'phpVeeva', array('file' => 'veeva' . DS . 'veeva.php'));
$veeva = new phpVeeva();
$file = $veeva->getVeevaAsset($vault['veeva_id'], $vault['title']);
$filename = $file['filename'];
$ext = $filename['ext'];
$mime = $filename['mime'];
$this->get($filename, $ext, $filename, $mime);
}
Here is the getVeevaAsset function which downloads the file:
public function getVeevaAsset($id, $filename)
{
$this->Auth();
$url = self::VVURL . "/objects/documents/" . $id . "/file";
set_time_limit(0);
$path = APP . 'webroot/uploads/';
$info = $this->getInfo($id);
$mime = $info['format__v'];
$ext = $this->extensions[$mime];
$fullFilename = $filename . "." . $ext;
$uri = $path . $fullFilename;
$fp = fopen($uri, 'w+');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($ch, CURLOPT_TIMEOUT, 50);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: application/json;charset=UTF-8", "Authorization: ".$this->sessID));
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$json_response = curl_exec($ch);
$status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($status != 200)
{
die('Error: call to URL $url failed with status "' . $status .'", response "' . $json_response. '", curl_error "' . curl_error($curl) . '", curl_errno "' . curl_errno($curl). '"');
}
curl_close($ch);
fclose($fp);
chmod($uri, 0777);
$file['path'] = $path;
$file['filename'] = $filename;
$file['ext'] = $ext;
$file['mime'] = $mime;
return $file;
}
I'm thinking either there's something happening in the getVeevaAsset function which doesn't let the get run properly (The download script is interfering with the mediaclass transfer?). Or the get function only runs properly if it is called directly by a user and not by another function. But these are just guesses. I can't use CakeResponse because I'm running Cake version 2.2.5.
I need to get this working for my client really soon so if anybody can help I'd really appreciate it.
When disabling auto-rendering ($this->autoRender = false;) you have to call Controller::render() at some point.
public function get_veeva($id = null)
{
$this->autoRender = false;
// ...
$this->get($filename, $ext, $filename, $mime);
$this->render();
}
I am completely new to the Box environment. I am using the current code to display all images in a web directory on a site with the newest files listed first:
<?php
$path = 'images/';
$files = scandir($path);
$ignore = array( 'cgi-bin', '.', '..');
# remove ignored files
$files = array_filter($files, function($file) use ($ignore) {return !in_array($file, $ignore);});
# get the modification time for each file
$times = array_map(function($file) use ($path) {return filemtime("$path/$file");}, $files);
# sort the times array while sorting the files array as well
array_multisort($times, SORT_DESC, SORT_NUMERIC, $files);
foreach ($files as $file) {
echo '<div class="item">';
echo '<a title="©2013" rel="gallery" class="fancybox" href="images/'.$file.'"><img src="images/'.$file.'" alt="'.$image.'" /></a>';
echo '</div>';
}
?>
I would like to integrate the Box API to get the files from my Box folder instead of a web folder. Is this possible with the current API? I have attempted to display the contents of an Open Access folder with the following:
<?php
$params = array();
$params['shared_link'] = array("access"=> "Open");
$params = json_encode($params);
echo $params;
$key = "[my api key]";
$token = "[token]";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.box.com/2.0/folders/kvpemb6rgohhr448r935"); //my box folder
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json', "-H Authorization: Bearer $key",'Content-Length: ' . strlen($params), 'X-HTTP-Method-Override: GET'));
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
?>
But receive only the array values "{"shared_link":{"access":"Open"}}" on the page.
I've exhausted my search ability on Google and Stackoverflow and have not come across a thread attempting to accomplish this task. Thank you for any guidance/assistance.
If you want to retrieve the items from an 'Open' folder in Box, I recommend you check out this endpoint. http://developers.box.com/docs/#shared-items
Here, maybe this will help you:
function getPictures($folderid, $access_token){
//===================== Default cUrl options =================
$options = array(
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_VERBOSE => true,
CURLOPT_HEADER => false,
CURLINFO_HEADER_OUT => false,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => false,
);
$options[CURLOPT_HTTPHEADER] = array ("Authorization: Bearer ".$access_token);
//======================= Proper url ==========================
$url = "https://api.box.com/2.0/folders/{$folderid}/items";
//======================= cUrl call ===========================
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$result = curl_exec($ch);
curl_close($ch);
$result = json_decode($result, true);
// =============== Loop over items to search for photos =================
$rez = array();
if (isset($result['total_count']) && $result['total_count'] > 0){
foreach ($result['entries'] as $elements){
if (isPic($elements['name'])) $rez[] = $elements['name'];
}
}
return $rez;
}
function isPic($value){
$value = explode('.', $value);
if (count($value) < 2) return false;
$extensions = array ('jpg', 'bmp', 'png', 'gif');
return in_array($value[1], $extensions);
}
Useful links from Box.com api:
http://developers.box.com/docs/#folders-retrieve-a-folders-items
or
http://developers.box.com/docs/#search
Hey guys i'm trying to build a little app that pulls in the users profile picture, allows them to manipulate the image and then publish the modified image to their profile pictures album (ideally set as their profile pic, but i don't think this is possible???).
The problem I'm having is that the javascript i'm using to alter the image will not work unless the image is local
i.e. <img src="http://profile.ak.fbcdn.net/hprofile-ak-snc4/[some_user_id].jpg" /> will not work, but <img src="img/image.jpg" /> will...
Is there any way of achieving this?
The method I am using to get hold of the user picture is this:
To connect to facebook:
<?php
require_once 'library/facebook.php';
$app_id = "###";
$app_secret = "###";
$facebook = new Facebook(array(
'appId' => $app_id,
'secret' => $app_secret,
'cookie' => true
));
if(is_null($facebook->getUser()))
{
header("Location:{$facebook->getLoginUrl(array('req_perms' => 'user_status,publish_stream,user_photos'))}");
exit;
}
Then to display the image:
<?php
$aResponse = $facebook->api('/me', array(
'fields' => 'picture',
'type' => 'large'
));
echo "<img src='".$aResponse["picture"]."' />";
?>
Many thanks!
Write yourself a proxy image server which which takes the the image you want to manipulate as a query parameter and just outputs the image content. It's a little slower than directly accessing the user's picture, but if you get creative you could cache that image locally to make subsequent loads faster.
a simple way to do this would be something like this:
front end:
<img src="image_server.php?img=<?= urlencode($aResponse['picture']); ?>">
back end:
<?php
if (!empty($_GET['img']))
{
//make sure this is a file on the facebook content delivery network
//and not our /etc/passwd or database connection config, or something
//else completely malicious.
if (preg_match("#^https?://profile\.ak\.fbcdn\.net/#i", $_GET['img']))
{
$img_path = $_GET['img'];
}
else
{
//do something with someone that entered a bad image, probably just
//display a "no image" image.
die('bad user. bad.');
}
readfile($img_path);
exit;
}
else
{
//no image was specified. output an anonymous/no image image.
die('an image file must be specified.');
}
You might want to get a little more complex than that...but that's the basic gist.
note: The php code assumes you have fopen wrappers enabled in your php.ini (so you can include web urls).
Thanks Jim for your response, I had seen someone doing something very similar to that, but again (just my luck) I was having problems with it. Anyway the way I managed to solve it was:
function save_image($inPath,$outPath)
{ //Download images from remote server
$in= fopen($inPath, "rb");
$out= fopen($outPath, "wb");
while ($chunk = fread($in,8192))
{
fwrite($out, $chunk, 8192);
}
fclose($in);
fclose($out);
}
// This is just pulling the user id to use for the filename
$id = $get_id['id'];
save_image($aResponse['picture'],'tmp/'.$id.'.jpg');
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
function curl_redir_exec($ch)
{
static $curl_loops = 0;
static $curl_max_loops = 20;
if ($curl_loops++ >= $curl_max_loops)
{
$curl_loops = 0;
return FALSE;
}
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
#list($header, $data) = #explode("\n\n", $data, 2);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code == 301 || $http_code == 302)
{
$matches = array();
preg_match('/Location:(.*?)\n/', $header, $matches);
$url = #parse_url(trim(array_pop($matches)));
if (!$url)
{
//couldn't process the url to redirect to
$curl_loops = 0;
return $data;
}
$last_url = parse_url(curl_getinfo($ch, CURLINFO_EFFECTIVE_URL));
if (!$url['scheme'])
$url['scheme'] = $last_url['scheme'];
if (!$url['host'])
$url['host'] = $last_url['host'];
if (!$url['path'])
$url['path'] = $last_url['path'];
$new_url = $url['scheme'] . '://' . $url['host'] . $url['path'] . (#$url['query']?'?'.$url['query']:'');
return $new_url;
} else {
$curl_loops=0;
return $data;
}
}
function get_right_url($url) {
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
return curl_redir_exec($curl);
}
$url = 'http://graph.facebook.com/' . $fbid . '/picture?type=large';
$file_handler = fopen('/img/avatar/'.$fbid.'.jpg', 'w');
$curl = curl_init(get_right_url($url));
curl_setopt($curl, CURLOPT_FILE, $file_handler);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_exec($curl);
curl_close($curl);
fclose($file_handler);
// Happy Coding