I am using PHP Github API to list my releases. Now I need to copy an asset file to my server from the latest release.
The PHP Github API does not provide download functionality so I decided to make a cURL request directly.
This is my code atm:
<pre>
<?php
// This file is generated by Composer
require_once '../vendor/autoload.php';
$client = new \Github\Client();
$client->authenticate(':mytoken', null, Github\Client::AUTH_ACCESS_TOKEN);
$release = $client->api('repo')->releases()->latest('arminetsw', 'webstore');
$nombre_fichero = $release['assets'][0]['name'];
$download_url = $release['assets'][0]['browser_download_url'];
$download_url = 'https://api.github.com/repos/arminetsw/webstore/releases/assets/:myAssetId?access_token=:mytoken';
$cliente = curl_init();
$file = fopen("webstore.zip", 'w');
curl_setopt($cliente, CURLOPT_URL, "https://api.github.com/repos/arminetsw/webstore/releases/assets/32188729?access_token=:mytoken");
curl_setopt($cliente, CURLOPT_HEADER, 'Accept: application/octet-stream');
curl_setopt($cliente, CURLOPT_USERAGENT, 'Webstore');
curl_exec($cliente);
curl_close($cliente);
fclose($file);
//$nuevo_fichero = ''
/*if (!copy($download_url, $nombre_fichero)) {
echo "Error al copiar $nombre_fichero...\n";
}*/
var_dump($release);
?>
</pre>
I only get a webstore.zip 0 bytes file with no errors.
*The repo is private.
Final working code:
<pre>
<?php
set_time_limit(0);
require_once '../vendor/autoload.php';
$client = new \Github\Client();
$client->authenticate('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', null, Github\Client::AUTH_ACCESS_TOKEN);
$release = $client->api('repo')->releases()->latest('user', 'repo');
$nombre_fichero = $release['assets'][0]['name'];
$download_url = $release['assets'][0]['url'];
$authorization = "access_token=XXXXXXXXXXXXXXXXXXXXXXXXXXXX";
$download_url .= "?" . $authorization;
$file = fopen($nombre_fichero, 'w');
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => $download_url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => "",
CURLOPT_USERAGENT => "Webstore",
CURLOPT_FILE => $file,
CURLOPT_HTTPHEADER => [
"Accept: application/octet-stream",
"Content-Type: application/octet-stream"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
fputs($file, $response);
fclose($file);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
?>
</pre>
Related
I'm currently working on copying a file from localhost to a remote server using PHP cURL.
I have two separate files, one for the localhost which sends the file, and another for the remote server to receive the file and save it to the server. The codes are as follows :
send.php
<?PHP
$web_page_to_send = "http://admin123.unaux.com/receive.php";
$file_name_with_full_path = "test.jpg";
$post_request = array
(
"sender" => "tmp",
"file" => curl_file_create($file_name_with_full_path)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $web_page_to_send);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_request);
$result = curl_exec($ch);
curl_close($ch);
echo "<br>Result: ".$result;
?>
receive.php
<?PHP
if(isset($_POST['sender']))
{
echo "got it !";
$file_name = "tmp/".$_POST['sender']."-".$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $file_name);
echo "Successful Attempt! <br><br>Filename: ".$file_name;
echo '<br><br> <img src="'.$file_name.'" width="300px"></img>';
}
else
{
echo 'Unauthorized Access!';
}
?>
The codes are working fine on localhost, but after placing the receive.php to the remote server, the file is no more sent and displayed. "http://admin123.unaux.com/receive.php" is where the file is on the remote server. I'm using profreehost free server as the remote server.
Remote server folder structure : Remote Server File and Folder Structure
Can anyone please help me with this problem?
Thank you.
Please get all received data in the receive.php file as below:
$post_data = trim(file_get_contents("php://input"));
after this, try to print $post_data. If you will get null value then response is not hitting at your file.
Try to send above data with below code:
$web_page_to_send = "http://admin123.unaux.com/receive.php";
$file_name_with_full_path = "test.jpg"; // Please write here full file path in the system
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $web_page_to_send,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 20,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => array('sender' => 'tmp','file'=>new CURLFILE($file_name_with_full_path)),
CURLOPT_HTTPHEADER => array(
"Content-Type: image/jpg"
),
CURLOPT_UPLOAD=>true,
));
$response = curl_exec($curl);
$http_response = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
Using CURL here we retrieve data and print then save to file after that insert it into database.
$curl = curl_init();
$options=array(
CURLOPT_URL=>"http://api.abc.com/v1/products/search.json?q=ball",
CURLOPT_RETURNTRANSFER =>true,
CURLOPT_ENCODING =>"",
CURLOPT_FOLLOWLOCATION =>true,
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT=>30,
CURLOPT_HTTP_VERSION=>CURL_HTTP_VERSION_1_0,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS=>"",
CURLOPT_HTTPHEADER=> array(
"authorization: AsiMemberAuth client_id=50041351&client_secret=55700485cc39f1",
"cache-control: no-cache"
),
CURLOPT_HEADER=> true
);
curl_setopt_array($curl, $options);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err){
echo "cURL Error #:" . $err;
} else {
echo $response;
}
The Result json is fine. now i want to save it in json file?
to save a string to a file in php, you can use file_put_contents()
file_put_contents doc
file_put_contents ( string $filename , mixed $data [, int $flags = 0 [, resource $context ]] ) : int
You can update your code as follows:
if ($err){
echo "cURL Error #:" . $err;
} else {
echo $response;
//Write response to file
file_put_contents("my_file.json", $response)
}
I'm trying to work with an API using Postman. In Postman the image displays fine. I am using Postman to generate the following code
$curl = curl_init();
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.com/v2/tier1/XXXXX/photos/photo/MYPHOTOIDISHERE/download?api_key=MYAPIKEYISHERE",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
"postman-token: 74f19da6-d4ba-fe02-4ad3-2a313b472ca2"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
The only modification I have made to the code from Postman is the CURLOPT_SSL_VERIFYPEER as I was getting an error.
The image displays perfectly in Postman but when I try to use the code myself I get a long string that looks like UTF. A small sample (it's very long) of this is as follows;
����JFIF``��C #!!!$'$ & ! ��C ����"�� ���}!1AQa"q2���#B��R��$3br� %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������� ���w!1AQaq"2�B���� #3R�br� $4�
How do I convert this into an image?
The result you are seeing is the actual bytes of the image.
You need to save that to a file or process it as image bytes. To save it, dump it to a file using file_put_contents($filename, $data)
// Instead of 'echo $response';
file_put_contents('image.jpg', $response);
You will see a new file image.jpg in your script's directory.
This assumes the image is a jpeg, you could do some checks to determine the type before saving it.
I am able to save image in folder, but problem is that Its showing error - window photo viewer can't open this picture because the file appears to be damaged, corrupted or is too large
here is my code
$oAuthToken = $token->access_token;
$getUrl = 'https://www.googleapis.com/drive/v2/files/' . $googlefileid . '?alt=media';
$authHeader = 'Authorization: Bearer ' . $oAuthToken ;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $getUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
$authHeader ,
]);
$data = curl_exec($ch);
curl_close($ch);
Storage::put($googlfilename,$data);
Please tell me what i am doing wrong.
Having quite a bit of trouble PUT-ting a PDF. I've managed to get it working fine in Postman, using the code below (large code block) and appending the PDF via the body as form-data. I'm trying to replicate this in PHP now. I'm having trouble attaching the PDF though.
I've tried numerous techniques trying to attach the PDF via "CURLOPT_INFILE", "CURLOPT_POSTFIELDS" to no avail.
I create the file via:
$pdf = $_SERVER['DOCUMENT_ROOT'] . '/pdf/temp/temp.pdf';
$file = curl_file_create($pdf, 'application/pdf', 'receipt');`
or
$file = new CURLFile($pdf, 'application/pdf', 'receipt');
I've tried using:
$file = fopen($pdf, 'rb');
$file = array('file' => $file);
CURLOPT_POSTFIELDS => $file,
CURLOPT_INFILESIZE => $fileSize,
CURLOPT_INFILE => $file
No luck though.
<?php
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://staging-tallie.com/v2/enterprise/ENTERPRISEID/MyReceipt/",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => "-----011000010111000001101001\r\nContent-Disposition: form-data; name=\"file\"\r\n\r\n\r\n-----011000010111000001101001--",
CURLOPT_HTTPHEADER => array(
"accept: application/json; charset=utf-8",
"cache-control: no-cache",
"content-type: multipart/form-data; boundary=---011000010111000001101001",
"token: TOKEN",
"upload-filename: receipt.pdf"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
Error reads:
<?xml version="1.0" encoding="utf-8"?>
<ErrorResponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ResponseCode>400</ResponseCode>
<Message>Unable to Save the file to the Storage Service.</Message>
</ErrorResponse>
400 is an HTTP response code indicating that the request was impossible to satisfy. That, along with the accompanying message text, suggest that the PHP process does not have write access to the destination directory.
This code worked for me in order to upload a file to bluemix Cloud Object Storage. File is uploaded from temporary folder after form submit using PUT method. Don't forget to validate file mime and extension before upload.
if (is_uploaded_file($_FILES['my_file']['tmp_name'])){
$ch = curl_init();
$url = IBM_BLUEMIX_BUCKET_END_POINT.$bucket_name."/".$file_name; // give the file a unique name
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_PUT, true); //PUT REQUEST
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'x-amz-acl: public-read', //header required for bluemix
'Authorization: Bearer '.$access_token, // authorization for bluemix iam
'Content-Type: '.$conten_type, //application/pdf or image/jpg
'Expect: '
));
$image_or_file = fopen($_FILES['my_file']['tmp_name'], "rb");
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_INFILE, $image_or_file);
curl_setopt($ch, CURLOPT_INFILESIZE, $_FILES[$fieldName]['size']);
curl_setopt(
$ch,
CURLOPT_POSTFIELDS,
array(
'file' =>
'#' . $_FILES['my_file']['tmp_name']
. ';filename=' . $_FILES['my_file']['name']
. ';type=' . $conten_type //application/pdf or image/jpg
));
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,16);
curl_setopt($ch,CURLOPT_TIMEOUT, 20);
curl_setopt($ch, CURLINFO_HEADER_OUT, true); // enable tracking
$response = curl_exec($ch);
$headerSent = curl_getinfo($ch ); // request headers from response (check if something wrong)
curl_close ($ch);
fclose($image_or_file);
if(!$response){ // or response
// do something...
}
}else{
//File did not upload, do something ...
}
I'm trying to POST to a Web Service (not RESTful) and get response through PHP. However, that web service requires Digest Authentication.
I've been searching online and found most of the discussions and articles are about the other way around (Requesting Digest Authentications to users), instead of responding it, using PHP.
I'm able to generate the Digest response using the code this thread provide:HTTP Digest authenticating in PHP, but the problem is to sending it along with(or not?) the POST data.
Here's the code I'm using:
$domain = "https://api.example.com";
$uri = "/ws.asmx/do";
// get headers
$response1_array = get_headers($web_service_url);
// get request part of digest auth
$response1 = $response1_array[5];
// get things behind "WWW-Authenticate:"
$response1 = substr($response1, 18);
// response() is a invented function to calculate the response according to the RFC2617
$response2 = response($response1, "username", "password", "GET", $uri);
// manually add some headers for POST, and fill out the parts that the calculation function missed
// for auth
$header =
"Host: api.example.com\r\n" .
"Content-Type: application/x-www-form-urlencoded\r\n" .
"Authorization: " . $response2 . ", nc=\"00000001\", opaque=\"0000000000000000\"" . "\r\nContent-Length: 0\r\n\r\n";
// echo the response from server
echo do_post_request($web_service_url, "", $header);
function do_post_request($url, $data, $optional_headers = null)
{
$params = array('http' => array(
'method' => 'POST',
'content' => $data
));
if ($optional_headers !== null) {
$params['http']['header'] = $optional_headers;
}
$ctx = stream_context_create($params);
$fp = fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $url");
}
$response = stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url");
}
return $response;
}
In the response:
$response1(from web service):
Digest realm="example.com", nonce="OS82LzIwMTMgMTI6MDI6NDYgUE0", opaque="0000000000000000", stale=false, algorithm=MD5, qop="auth"
$response2(I calculated given the server response):
Digest username="username", realm="example.com", nonce="OS82LzIwMTMgMTI6MDI6NDYgUE0", uri="/ws.asmx/do", cnonce="1378494106", nc="1", response="0f96788854cf2098ba22c6121529d7de", qop="auth"
the final (2nd) response from server:
Warning: fopen(https://api.example.com/ws.asmx/do): failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error in ...
I don't understand why server responded 500 error in this case. Is there anything wrong in the code? Or has anyone met this problem before and solved it and can help me with a solution?
Regards,
Mylo
Eventually solved it with cURL after 2 days' fumbling. I guess this is the first time a piece of ready-made PHP code for digest auth is posted, hopefully it can help someone who are in the same ditch as I was in.
Code:
<?php
error_reporting(E_ALL);
ini_set( 'display_errors','1');
$url = "https://api.example.com/ws.asmx/do";
$username = "username";
$password = "pwd";
$post_data = array(
'fieldname1' => 'value1',
'fieldname2' => 'value2'
);
$options = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => true,
CURLOPT_VERBOSE => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSL_VERIFYPEER => false, // for https
CURLOPT_USERPWD => $username . ":" . $password,
CURLOPT_HTTPAUTH => CURLAUTH_DIGEST,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => http_build_query($post_data)
);
$ch = curl_init();
curl_setopt_array( $ch, $options );
try {
$raw_response = curl_exec( $ch );
// validate CURL status
if(curl_errno($ch))
throw new Exception(curl_error($ch), 500);
// validate HTTP status code (user/password credential issues)
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($status_code != 200)
throw new Exception("Response with Status Code [" . $status_code . "].", 500);
} catch(Exception $ex) {
if ($ch != null) curl_close($ch);
throw new Exception($ex);
}
if ($ch != null) curl_close($ch);
echo "raw response: " . $raw_response;
?>
If you want to send JSON data with PUT method:
<?php
error_reporting(E_ALL);
ini_set( 'display_errors','1');
$url = "https://api.example.com/ws.asmx/do";
$username = "username";
$password = "pwd";
$post_data = array(
'fieldname1' => 'value1',
'fieldname2' => 'value2'
);
$options = array(
CURLOPT_URL => $url,
CURLOPT_HEADER => true,
CURLOPT_VERBOSE => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSL_VERIFYPEER => false, // for https
CURLOPT_USERPWD => $username . ":" . $password,
CURLOPT_HTTPAUTH => CURLAUTH_DIGEST,
CURLOPT_CUSTOMREQUEST => "PUT",
CURLOPT_POSTFIELDS => json_encode($post_data) ,
);
$ch = curl_init();
curl_setopt_array( $ch, $options );
try {
$raw_response = curl_exec( $ch );
// validate CURL status
if(curl_errno($ch))
throw new Exception(curl_error($ch), 500);
// validate HTTP status code (user/password credential issues)
$status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($status_code != 200)
throw new Exception("Response with Status Code [" . $status_code . "].", 500);
} catch(Exception $ex) {
if ($ch != null) curl_close($ch);
throw new Exception($ex);
}
if ($ch != null) curl_close($ch);
echo "raw response: " . $raw_response;
?>