Trying to copy images from remote server to use as thumbnails in my wordpress site. Some of this images become corrupted after copying.
Here's my code:
$url = 'http://media.cultserv.ru/i/1000x1000/'.$event->subevents[0]->image;
$timeout_seconds = 100;
$temp_file = download_url( $url, $timeout_seconds );
if(!is_wp_error( $temp_file )) {
$file = array(
'name' => basename($url),
'type' => wp_check_filetype(basename($url), null),
'tmp_name' => $temp_file,
'error' => 0,
'size' => filesize($temp_file),
);
$overrides = array(
'test_form' => false,
'test_size' => true,
'test_upload' => true,
);
$results = wp_handle_sideload( $file, $overrides );
if(empty($results['error'])) {
$filename = $results['file'];
$local_url = $results['url'];
$type = $results['type'];
$attachment = array(
'post_mime_type' => $results['type'],
'post_title' => preg_replace('/.[^.]+$/', '', basename( $results['file'] ) ),
'post_content' => '',
'post_status' => 'inherit',
'post_type' => 'attachment',
'post_parent' => $pID,
);
$attachment_id = wp_insert_attachment( $attachment, $filename );
if($attachment_id) {
set_post_thumbnail( $pID, $attachment_id );
}
}
}
Here's a screenshot that shows what I mean (Left - original image; Right - copy on my server):
I think that your download_url( $url, $timeout_seconds ) function is not working properly (you don't get to catch network/other errors, that's why you have corrupted images), also I don't think that the timeout parameter is really needed to download an url...
To fix this it's better to rewrite this function into something like this :
function download_url($url)
{
$saveto = 'temp.jpg'; // generate temp file
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
$raw = curl_exec($ch);
if (curl_errno($ch)) {
curl_close($ch);
return false;
// you probably have a network problem here.
// you need to handle it, for example retry or skip and reqeue the image url
}
curl_close($ch);
if (file_exists($saveto)) {
unlink($saveto);
}
$fp = fopen($saveto, 'x');
fwrite($fp, $raw);
fclose($fp);
return $saveto;
}
Related
Afternoon all,
Having some issues sending large files via curl, we can send the first one which is 5mb but the second test file is 34mb and is not sending. We have increased the post and max upload sizes on both the sending and receiving servers and still no joy.
This is the sending script:
function send_files($directory, $file, $dir_parts) {
$url = 'https://test.com/App_processing/transfer_videos';
$handle = fopen($directory."video.mp4", "r");
$stats = fstat($handle);
$data = stream_get_contents($handle);
$payload = array(
'file' => base64_encode($data),
'parts' => $dir_parts
);
$postfields = array( serialize( $payload ) );
$ssl = strstr($url, '://', true);
$port = ($ssl == 'https') ? 443 : 80;
$verify_ssl = false;
$ch = curl_init();
$curlConfig = array(
CURLOPT_PORT => $port,
CURLOPT_URL => $url,
CURLOPT_SSL_VERIFYPEER => $verify_ssl,
CURLOPT_FORBID_REUSE => true,
CURLOPT_FRESH_CONNECT => true,
CURLOPT_FAILONERROR => false,
CURLOPT_VERBOSE => true,
CURLOPT_POST => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_COOKIESESSION => true,
CURLOPT_POSTFIELDS => $postfields,
);
$headers = null;
$apikey = 'testAPIkey';
$headers = array(
"apikey: ".$apikey
);
$curlConfig[CURLOPT_HTTPHEADER] = $headers;
curl_setopt_array( $ch, $curlConfig );
$response = curl_exec( $ch );
}
Receiving script:
public function transfer_videos() {
$return_arr = array();
ini_set('max_execution_time', '999');
ini_set('memory_limit', '512M');
ini_set('post_max_size', '512M');
if(count($this->post_data) > 0) {
$image = $this->post_data['file'];
$file = base64_decode($image);
$filename = $this->post_data['parts'][2];
$return_arr = array();
$office_path = $this->config->item('_path') . '_videos/';
$path = $o_path.$this->post_data['parts'][0]."/".$this->post_data['parts'][1]."/";
$name = $filename;
if( !is_dir( $path ) ) {
mkdir( $path, 0750, true );
}
try {
$return_arr = file_put_contents($path.$name, $file);
} catch (Exception $e) {
$this->curl_helper->error($path.$name, "failed to upload file");
}
}
echo serialize($return_arr);
}
The current error we are getting is:
Recv failure: Connection reset by peer
What the hell are we doing wrong?
hi i use this code for upload image in wordpress with api
my code :
<?php
$file = $_FILES["RESULT_FileUpload-6"]["tmp_name"];
$url = 'http://tst.com/wp-json/wp/v2/media/';
$ch = curl_init();
$username = 'username';
$password = '123456';
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $file );
curl_setopt( $ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Disposition: form-data; filename="'.$_FILES["RESULT_FileUpload-6"]["name"].'"',
'Authorization: Basic ' . base64_encode( $username . ':' . $password ),
] );
$result = curl_exec( $ch );
curl_close( $ch );
print_r( json_decode( $result ) );
?>
but when i use this code show error 401 "rest_cannot_create"
i use username and password correct (username and password for wordpress admin panel)
Is there another way for Authorization rest api wordpress??
try to add this in the htaccess file:
RewriteRule ^index\.php$ - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization},L]
I have to upload pdf file. This will help you in any of you file uploading to custom directories
public function uploadFiles(WP_REST_Request $request)
{
if(checkloggedinuser()){
if ( ($request->get_file_params('file'))) {
$upload_dir = wp_upload_dir();
$user_id = checkloggedinuser();
$timestamp = time();
if ( ! empty( $upload_dir['basedir'] ) ) {
$user_dirname = $upload_dir['basedir'].'/customize-files';
if ( ! file_exists( $user_dirname ) ) {
wp_mkdir_p( $user_dirname );
}
$filename_maker = $user_id.'_'.$timestamp.'_'.$_FILES['file']['name'];
$filename = wp_unique_filename( $user_dirname, $filename_maker );
// return $filename_maker;
$check = move_uploaded_file($_FILES['file']['tmp_name'], $user_dirname .'/'. $filename);
// save into database $upload_dir['baseurl'].'/product-images/'.$filename;
if($check){
$path = $upload_dir['baseurl'].'/customize-files/'.$filename_maker;
return array(
'success' => true,
'responsecode' => 200,
"message" => "File Uploaded Successfully",
"data" => [
"path" => $path,
],
);
}
}
}else{
return array(
'success' => false,
'responsecode' => 403,
"message" => "Please Provide File",
"data" => [],
);
}
}else{
return array(
'success' => false,
'responsecode' => 403,
"message" => "Please Logged In to get Data",
"data" => [],
);
}
}
I'm unable to upload file on box using php. I've tried all the contents which I've found on stackOverflow but never got success. Even I've tried https://github.com/golchha21/BoxPHPAPI/blob/master/README.md Client but still got failure. Can anyone help me how to upload file on box using php curl.
$access_token = 'xGjQY2XU0bmOEwVAdkqiZTsGuFyFuqzU';
$url = 'https://upload.box.com/api/2.0/files/content';
$headers = array("Authorization: Bearer $access_token"
. "Content-Type:multipart/form-data");
$filename = 'file.jpg';
$name = 'file.jpg';
$parent_id = '0';
$post = array('filename' => "#" . realpath($filename), 'name' => $name,
'parent_id' => $parent_id);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
var_dump($response);
Even I've used this request too...
$localFile = "file.jpg";
$fp = fopen($localFile, 'r');
$access_token = '00hsilvu9LrAsKQ8iDzXZAAieSLrjzX9';
$url = 'https://upload.box.com/api/2.0/files/content';
$curl = curl_init();
$cfile = new CURLFILE($localFile, 'jpg', 'Test-filename.jpg');
$data = array();
//$data["TITLE"] = "$noteTitle";
//$data["BODY"] = "$noteBody";
//$data["LINK_SUBJECT_ID"] = "$orgID";
//$data["LINK_SUBJECT_TYPE"] = "Organisation";
$data['filename'] = "file.jpg";
$data['parent_id'] = 0;
curl_setopt_array($curl, array(
CURLOPT_UPLOAD => 1,
CURLOPT_INFILE => $fp,
CURLOPT_NOPROGRESS => false,
CURLOPT_BUFFERSIZE => 128,
CURLOPT_INFILESIZE => filesize($localFile),
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $data,
CURLOPT_HTTPHEADER => array(
"Authorization: Bearer 00hsilvu9LrAsKQ8iDzXZAAieSLrjzX9",
"Content-Type:multipart/form-data"
),
));
$response = curl_exec($curl);
$info = curl_getinfo($curl);
$err = curl_error($curl);
curl_close($curl);
var_dump($info);
$req_dump = print_r($response, true);
file_put_contents('box.txt', $req_dump, FILE_APPEND);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
And in response I always got an empty string.
Please tell me what am I doing wrong?
I'm using Box PHP Client for creation of folders, uploading of files and then sharing of uploaded files using this client.
https://github.com/golchha21/BoxPHPAPI
But this client's uploading file wasn't working... then I dig into it and I found something missing into this method.
/* Uploads a file */
public function put_file($filename, $name ,$parent_id) {
$url = $this->build_url('/files/content', array(), $this->upload_url);
if(isset($name)){
$name = basename($filename);
}
$params = array('filename' => "#" . realpath($filename), 'name' => $name , 'parent_id' => $parent_id, 'access_token' => $this->access_token);
return json_decode($this->post($url, $params), true);
}
Just put forward slash after # sign. Like this, Then I'll start working
/* Uploads a file */
public function put_file($filename, $name ,$parent_id) {
$url = $this->build_url('/files/content', array(), $this->upload_url);
if(isset($name)){
$name = basename($filename);
}
$params = array('filename' => "#/" . realpath($filename), 'name' => $name , 'parent_id' => $parent_id, 'access_token' => $this->access_token);
return json_decode($this->post($url, $params), true);
}
Alright so in a script I have, I want to communicate with another server and retrieve a file from the server. Normally I would not have any cURL option specifying what IP address (interface) to use but the server will only let me download if it knows the connection established is between 188.138.110.125 (my IP address) and the server. So I edited my script to look like this:
<?php
$user = 'username';
$pass = 'password';
$cookie_file = './sessions/cookie.txt';
// exit if the script is called directly
if ( empty($url) )
die();
$url = "http://www.example.com/file.zip";
// checking if the login session is valid
$logged_in = 0;
if ( file_exists($cookie_file) )
{
$cookie = file_get_contents($cookie_file);
$ch = curl_init();
$options = array(
CURLOPT_URL => 'https://www.example.com/testfile.zip&'.$cookie_file,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_INTERFACE => '188.138.110.125',
CURLOPT_SSL_VERIFYPEER => 0
);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close($ch);
$logged_in = !preg_match('~ERROR~', $content);
}
// logging in and storing the cookie
if ( !$logged_in )
{
$ch = curl_init();
$options = array(
CURLOPT_URL => 'https://example.com/login.php?login='.urlencode($user).'&password='.urlencode($pass).'&withcookie=1',
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_INTERFACE => '188.138.110.125',
CURLOPT_SSL_VERIFYPEER => 0
);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close($ch);
preg_match('~cookie=([0-9A-F]+)~', $content, $match);
if ( empty($match[1]) )
die('Error: login failed');
$cookie = "enc={$match[1]}";
file_put_contents($cookie_file, $cookie);
}
//----------------------- THIS IS WHERE PROBLEM HAPPENS ---------------------------
// checking if the direct link to the file is available
$ch = curl_init();
$options = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => 1,
CURLOPT_INTERFACE => '188.138.110.125',
CURLOPT_RETURNTRANSFER => 1
);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close($ch);
preg_match('~Location: ([^\s]+)~', $content, $match);
// if the direct link to the file was not found
if ( empty($match[1]) )
// display any other errors
if ( preg_match('~(ERROR: [^\n]+)~', $content, $match) )
die("Error {$match[1]}");
else
die('Error: undefined error (1)');
$direct_link = $match[1];
// extracting filename
$pieces = explode('/', $direct_link);
$filename = end($pieces);
// extrating the size of the file
$ch = curl_init();
$options = array(
CURLOPT_URL => $direct_link,
CURLOPT_HEADER => 1,
CURLOPT_NOBODY => 1,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_INTERFACE => '188.138.110.125',
CURLOPT_SSL_VERIFYPEER => 0
);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close($ch);
preg_match('~Content-Length: (\d+)~', $content, $match);
$filesize = $match[1];
// setting headers for the user
header('Content-Type: application/octet-stream');
header("Content-Disposition: filename=$filename");
header("Content-Length: $filesize");
// printing the file
$ch = curl_init();
$options = array(
CURLOPT_URL => $direct_link,
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_BINARYTRANSFER => 1,
CURLOPT_INTERFACE => '188.138.110.125',
CURLOPT_COOKIE => $cookie
);
curl_setopt_array($ch, $options);
curl_exec($ch);
curl_close($ch);
?>
But now it when it downloads the file, it downloads a file that is 0 bytes. The file name is accurate and so is the extension of the file, it just has no size. This problem only started when I added CURLOPT_INTERFACE => '188.138.110.125', into the script. Any help is greatly appreciated and thank you in advance.
NOTE: If I keep on trying to download, at a completely random time it will actually find the right file size, but if I do it again I get no luck.
I have recently changed servers, and one of my scripts is not functioning on the new server, as fopen is not enabled?
Is it possible to change the following code to use the CURL function instead?
Hope someone can help!
<?php
$postToFileName = 'http://www.somesite.com/postfile.aspx';
$postArr = array(
'NM' => $row['Lead_Name'],
'EM' => $row['Lead_Email'],
'PH' => $row['Lead_Tel'],
);
$opts = array(
'http'=>array(
'method' => 'POST',
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'content' => http_build_query($postArr)
)
);
$context = stream_context_create($opts);
$fp = fopen($postToFileName, 'r', false, $context);
$returnedMessage = '';
while (!feof($fp)) {
$returnedMessage .= fgets($fp);
}
fclose($fp);
if ($returnedMessage == '') {
$returnedMessage = 'No Message';
} else if (strlen($returnedMessage) > 250) {
$returnedMessage = substr($returnedMessage,0,250);
}
$returnedMessage = preg_replace("/[\r\n]/", '', $returnedMessage);
$returnedMessage = mysql_real_escape_string($returnedMessage, $sql);
$q = "UPDATE leads SET Data_Sent = '$returnedMessage' WHERE Lead_ID = $id";
mysql_query($q, $sql);
array_push($leadsSent, $id);
}
}
mysql_close($sql);
return $leadsSent;
}
?>
Yes, it's quite possible. See the examples here:
http://us.php.net/manual/en/curl.examples-basic.php
Sure. It should probably look like this (not tested of course, might need some minor changes) :
$postToFileName = 'http://www.somesite.com/postfile.aspx';
$postArr = array(
'NM' => $row['Lead_Name'],
'EM' => $row['Lead_Email'],
'PH' => $row['Lead_Tel'],
);
$ch = curl_init($postToFileName);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postArr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$returnedMessage = curl_exec($ch);
curl_close($ch);