I have an old script that uploads PDF files via an API. I'm getting the error message:
Deprecated: curl_setopt(): The usage of the #filename API for file
uploading is deprecated. Please use the CURLFile class instead.
Here is the relevant code (I think this is all of it). The error points to the line: curl_setopt( $curl_handle, CURLOPT_POSTFIELDS, $postFields ).
//Upload the file
function uploadPdf( $api, $lead_id, $rev, $existing_files = array() ) {
if ( ! file_exists( SERVERPATH . "quotes/quote-". $this->id .".pdf" ) )
$this->createQuotePdf();
$files_array = array( array( 'entityType'=>'files', 'name'=>"quote-". $this->id .".pdf" ) );
// if ( $this->upfile && ! file_exists( SERVERPATH . "uploads/" . $upfile ) )
// $files_array[] = array( array( 'entityType'=>'files', 'name'=> $upfile ) );
foreach ( $existing_files as $file ) {
$files_array[] = (array) $file;
}
//this request gives us the URLs to upload to
$result = $api->editLead( array( 'leadId' => $lead_id, 'rev'=>'REV_IGNORE', 'lead'=> array( 'file' => $files_array ) ) );
//Upload the Quote file
$postFields = array();
$postFields['file'] = "#" . SERVERPATH . "quotes/quote-". $this->id .".pdf";
$postFields['type'] = "application/pdf";
$curl_handle = curl_init();
$file = array_pop( $result->file );
curl_setopt( $curl_handle, CURLOPT_URL, $file->uri );
curl_setopt( $curl_handle, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl_handle, CURLOPT_POST, true );
curl_setopt( $curl_handle, CURLOPT_USERPWD, USERNAME . ":" . API_KEY );
curl_setopt( $curl_handle, CURLOPT_POSTFIELDS, $postFields );
//execute the API Call
$return = curl_exec( $curl_handle ) ;
$this->uploadUpfile($api, $lead_id);
return $return;
}
My knowledge is pretty basic. But I've tried to replace:
$postFields['file'] = "#" . SERVERPATH . "quotes/quote-". $this->id .".pdf";
$postFields['type'] = "application/pdf";
with
$postFields['file'] = curl_file_create(SERVERPATH . "quotes/quote-". $this->id .".pdf", 'application/pdf', SERVERPATH . "quotes/quote-". $this->id .".pdf");
Doing the above has got rid of the error, but the underlying problem where I can't actually open the uploaded file is still happening. So I'm wondering if I've done something wrong?
From PHP 5.5 and above you should use CURLFile to upload file, I have already posted a complete answer describing CURLFile and normal file upload, you can check that answer here.
You can use CURLFile as below, feel free to adjust the code as per your need:
//Upload file using CURLFile
function upload($target, $postFields){
$file = $postFields['file'];
$cFile = new CURLFile($file,$postFields['type'], $file);
$data = array(
'file' => $cFile,
'type' => $postFields['type'],
);
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $target);
curl_setopt($curl, CURLOPT_HEADER , true); //we need header
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // stop verifying certificate
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true); // enable posting
curl_setopt($curl, CURLOPT_POSTFIELDS, $data); // post images
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); // if any redirection after upload
curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
$r = curl_exec($curl);
if (curl_errno($curl)) {
$error = curl_error($curl);
print_r($error);
} else {
// check the HTTP status code of the request
$resultStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($resultStatus != 200) {
print_r($resultStatus);
}else{
//successfull
print_r($r);
}
}
curl_close($curl);
}
As your file and filetype are in an array named $postFields, so you can call the above function as below:
upload($target, $postFields);
where $target is the link which you are calling to upload the file.
Related
I'm using CURL in PHP to download images from URLs from CSV file but if there are more than one images in a single line than some of the images downloaded corrupted and the size of that image is 0 byte.
Example:-
If the CSV file is like this then the second file always corrupted.
Image 1, "https://d2qx4k6xgs9iri.cloudfront.net/ProductImages/ce363947-f23a-46d6-b106-1201cdca37f0.jpg, https://homepages.cae.wisc.edu/~ece533/images/airplane.png"
But If I removed first or second image than the image successfully saved. Example:
Image 2, https://homepages.cae.wisc.edu/~ece533/images/arctichare.png
Here is my code that reads a CSV File
$file = fopen($file, "r");
while (!feof($file)) {
$data = fgetcsv($file);
$images = $data[1];
$images = explode(',', $images); //exploding images by ,
foreach ($images as $image) {
$milliseconds = md5(round(microtime(true) * 1000)) . '.jpg';
$imagename = saveImage($image, $milliseconds);
}
}
Below saveImage function
function saveImage($url,$image_name){
echo $url.'<br/>'; //URL is correct and have image. I have checked it manually
$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);
curl_close ($ch);
$fp = fopen('assets/products/large/' . $image_name,'x');
fwrite($fp, $raw);
fclose($fp);
}
The Exact Sample for CSV File which I'm Using
Images 1, "https://d2qx4k6xgs9iri.cloudfront.net/ProductImages/ce363947-f23a-46d6-b106-1201cdca37f0.jpg, https://homepages.cae.wisc.edu/~ece533/images/airplane.png"
Images 2, https://homepages.cae.wisc.edu/~ece533/images/arctichare.png
Images 3, "https://homepages.cae.wisc.edu/~ece533/images/fruits.png, https://homepages.cae.wisc.edu/~ece533/images/girl.png"
Images 4, "https://homepages.cae.wisc.edu/~ece533/images/goldhill.bmp, https://homepages.cae.wisc.edu/~ece533/images/tulips.png"
I think the issue may well be that there is space in the url before the protocol - using trim to remove the space would help. Rather than use curl for testing I simply used file_get_contents and it downloaded all the files OK.
$dir = 'c:/temp/downloads/';
$file=__DIR__ . DIRECTORY_SEPARATOR . 'img.csv';
$file=fopen( $file, 'r' );
while( !feof( $file ) ){
$line = fgetcsv( $file );
if( !empty( $line[1] ) ){
$urls = explode( ',', $line[1] );
foreach( $urls as $url ){
$url=trim( $url );
$bytes = file_put_contents( $dir . basename( $url ), file_get_contents( $url ) );
printf('Saved %s - size: %sKb<br />',basename( $url ),$bytes / 1024 );
}
}
}
fclose( $file );
The curl function also needed a little tweak - as the urls are over SSL then you really should add additional parameters to the curl request. I modified the function like so:
function saveImage( $url, $image_path ){
global $cacert;
$fp = fopen( $image_path, 'w+' );
$ch = curl_init( $url );
curl_setopt($ch, CURLOPT_HEADER, 0 );
curl_setopt($ch, CURLOPT_TIMEOUT, 10 );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_BINARYTRANSFER, true );
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true );
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2 );
curl_setopt($ch, CURLOPT_CAINFO, $cacert );
curl_setopt($ch, CURLOPT_ENCODING, '' );
curl_setopt($ch, CURLOPT_FILE, $fp );
curl_exec($ch);
curl_close ($ch);
fclose($fp);
}
Where $cacert is defined elsewhere but essentially, on my system is c:\wwwroot\cacert.pem ~ you can download a copy from here - curl.haxx.se
I ran this code rather than the above like so:
while( !feof( $file ) ){
$line = fgetcsv( $file );
if( !empty( $line[1] ) ){
$urls = explode( ',', $line[1] );
foreach( $urls as $url ){
$url=trim( $url );
saveImage( $url, $dir . basename( $url ) );
}
}
}
fclose( $file );
I have website created in PHP. Basically it is a send document kind of project. It uses a document store in Azure I will call and send it into Azure. Now I want to send in email as well as store in Google drive.
So it should be stored to drive with public access. I have create following code. It works properly I don't want any input from user.
$client->setAccessToken($_SESSION['accessToken']);
$service = new Google_DriveService($client);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$file = new Google_DriveFile();
foreach ($files as $file_name) {
$file_path = 'files/'.$file_name;
$mime_type = finfo_file($finfo, $file_path);
$file->setTitle($file_name);
$file->setDescription('This is a '.$mime_type.' document');
$file->setMimeType($mime_type);
$service->files->insert(
$file,
array(
'data' => file_get_contents($file_path),
'mimeType' => $mime_type
)
);
}
finfo_close($finfo);
I want upload from Azure URL using cURL or using API. When mail send it is automatically uploaded to drive at the same time.
Question Update
I have function to send a mail this is work perfectly. I would like to store an attachment to google drive and retrieve path store that path in to database.
This all work will be based on API no user interaction required. That file is PDF in formate and not specific bytes its different as per data of file.
Issue :
When I upload a file to Drive original file name is rename to untitled. Here is code.
function uploadFile($credentials, $filename, $targetPath)
{
global $GAPIS;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $GAPIS . 'upload/drive/v2/files?uploadType=media');
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
//curl_setopt($ch, CURLOPT_POSTFIELDS, array("title" =>"newfile.txt"));
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filename));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-Type : text/plain', 'Content-Length:' . filesize($filename),
'Authorization: Bearer ' . getAccessToken($credentials))
);
$postResult = curl_exec($ch);
curl_close($ch);
return json_decode($postResult, true);
}
==========================================
Updated code (Issue with Added code but still getting issue with Untitle.pdf in drive)
==========================================
<?php
$GAPIS = 'https://www.googleapis.com/';
$GAPIS_AUTH = $GAPIS . 'auth/';
$GOAUTH = 'https://accounts.google.com/o/oauth2/';
$CLIENT_ID = '709846732498-xxxxxxxx';
$CLIENT_SECRET = 'XXXXXXXXXXXXXX';
$REDIRECT_URI = 'http' . ($_SERVER['SERVER_PORT'] == 80 ? '' : 's') . '://' . $_SERVER['SERVER_NAME'] . $_SERVER['SCRIPT_NAME'];
$SCOPES = array($GAPIS_AUTH . 'drive', $GAPIS_AUTH . 'drive.file', $GAPIS_AUTH . 'userinfo.email', $GAPIS_AUTH . 'userinfo.profile');
$STORE_PATH = 'credentials.json';
function uploadFile($credentials, $filename, $targetPath)
{
global $GAPIS;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $GAPIS . 'upload/drive/v2/files?uploadType=media');
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, file_get_contents($filename));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-Type : application/pdf', 'Content-Length:' . filesize($filename),
'Authorization: Bearer ' . getAccessToken($credentials))
);
$postResult = curl_exec($ch);
curl_close($ch);
return json_decode($postResult, true);
}
function getStoredCredentials($path)
{
$credentials = json_decode(file_get_contents($path), true);
if (isset($credentials['refresh_token']))
return $credentials;
$expire_date = new DateTime();
$expire_date->setTimestamp($credentials['created']);
$expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
$current_time = new DateTime();
if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
{
$credentials = null;
unlink($path);
}
return $credentials;
}
function storeCredentials($path, $credentials)
{
$credentials['created'] = (new DateTime())->getTimestamp();
file_put_contents($path, json_encode($credentials));
return $credentials;
}
function requestAuthCode()
{
global $GOAUTH, $CLIENT_ID, $REDIRECT_URI, $SCOPES;
$url = sprintf($GOAUTH . 'auth?scope=%s&redirect_uri=%s&response_type=code&client_id=%s&approval_prompt=force&access_type=offline',
urlencode(implode(' ', $SCOPES)), urlencode($REDIRECT_URI), urlencode($CLIENT_ID)
);
header('Location:' . $url);
}
function requestAccessToken($access_code)
{
global $GOAUTH, $CLIENT_ID, $CLIENT_SECRET, $REDIRECT_URI;
$url = $GOAUTH . 'token';
$post_fields = 'code=' . $access_code . '&client_id=' . urlencode($CLIENT_ID) . '&client_secret=' . urlencode($CLIENT_SECRET)
. '&redirect_uri=' . urlencode($REDIRECT_URI) . '&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
function getAccessToken($credentials)
{
$expire_date = new DateTime();
$expire_date->setTimestamp($credentials['created']);
$expire_date->add(new DateInterval('PT' . $credentials['expires_in'] . 'S'));
$current_time = new DateTime();
if ($current_time->getTimestamp() >= $expire_date->getTimestamp())
return $credentials['refresh_token'];
else
return $credentials['access_token'];
}
function authenticate()
{
global $STORE_PATH;
if (file_exists($STORE_PATH))
$credentials = getStoredCredentials($STORE_PATH);
else
$credentials = null;
if (!(isset($_GET['code']) || isset($credentials)))
requestAuthCode();
if (!isset($credentials))
$credentials = requestAccessToken($_GET['code']);
if (isset($credentials) && isset($credentials['access_token']) && !file_exists($STORE_PATH))
$credentials = storeCredentials($STORE_PATH, $credentials);
return $credentials;
}
$credentials = authenticate();
$result = uploadFile($credentials, 'example.pdf', '');
if (!isset($result['id']))
throw new Exception(print_r($result));
else
echo 'File copied successfuly (file Id: ' . $result['id'] . ')';
echo '<pre>'; print_r($result);
going by https://developers.google.com/drive/api/v3/simple-upload , this should work:
<?php
$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: application/pdf', // todo: runtime detection?
'Authorization: Bearer [YOUR_AUTH_TOKEN]'
),
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => file_get_contents ( '/path/to/file.pdf' ),
CURLOPT_RETURNTRANSFER => 1
) );
try {
if (false === ($resp = curl_exec ( $ch ))) {
throw new \RuntimeException ( 'curl error ' . curl_errno ( $ch ) . ": " . curl_error ( $ch ) );
}
$parsed = json_decode ( $resp, true );
if (! $parsed || $parsed ['code'] !== 200) {
throw new \RuntimeException ( 'google api error: ' . $resp );
}
} finally{
curl_close ( $ch );
}
var_dump($resp);
I am still not completely sure i understand your question. Assuming you just want to upload a file in php or curl here are two options.
Uploading to Google drive is in two parts the first part you create the meta data that being the file name and basic information about your fine. The second part is where you upload the actual data of your file.
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'My Report',
'mimeType' => 'application/vnd.google-apps.spreadsheet'));
$content = file_get_contents('files/report.csv');
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => 'text/csv',
'uploadType' => 'multipart',
'fields' => 'id'));
printf("File ID: %s\n", $file->id);
Code ripped from media upload
If you want to do this in curl inserting the meta data shouldnt be an issue your issue will be uploading the file itself. You will need to POST the metadata to create the empty file and capture its file-id. Then use the file-id for a content upload. You can find more information on the requests you will nee dot make here simple upload request.
The code will probably look something like this but again your going to have to pass the file id.
curl
--silent
--request POST
--data-binary "#c:\temp\myfile.jpg"
-OL MyFolder\myfile2.jpeg
-H "Slug: myfile3.jpg"
-H "Authorization: Bearer [your access token here]"
-H "Content-Type: image/jpeg {"fileid":"1234"}"
"https://www.googleapis.com/upload/drive/v3/files?uploadType=media"
Note i have not tested the upload in curl this is just a guess.
You can use Logic Apps to send the file from Azure Blob storage to Google Drive as well as an email attachment.
https://learn.microsoft.com/en-us/azure/connectors/connectors-create-api-azureblobstorage
Alternatively files stored in Azure Blobs can be addresses with a public URL assuming you have the right permissions set on the container and/or blob.
Say we have this array
$args = array('responseType' => 'Xml',
'serverName' => 'vl18278.dinaserver.com',
'command' => 'Vps_GetUsedSpace',
) ;
This array composes an URL to send through cURL. I need to replace vl18278.dinaserver.com with a variable $vps, but when I replace it, the URL show a %5B0%5D just before the = sign of the attribute serverName:
responseType=Xml&serverName%5B0%5D=vl18278.dinaserver.com&command=Vps_GetUsedSpace
If I dont replace the vl18278.dinaserver.com, the URL is correct.
What is wrong with my code? Why are those %5B0%5D getting into my URL? :(
Thanks in advance.
Complete code:
<?php
$listavps = simplexml_load_file('servers.xml');
foreach ($listavps->servers->server as $vps) {
$urlApi = 'url.php';
$username = 'user';
$password = 'pass';
$args = array('responseType' => 'Xml',
'serverName' => 'vl18278.dinaserver.com',
'command' => 'Vps_GetUsedSpace',
) ;
$args = ( is_array ( $args ) ? http_build_query ( $args, '', '&' ) : $args );
$headers = array();
$handle = curl_init($urlApi);
if( $handle === false ) // error starting curl
{
$error = '0 - Couldn\'t start curl';
}
else
{
curl_setopt ( $handle, CURLOPT_FOLLOWLOCATION, true );
curl_setopt ( $handle, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $handle, CURLOPT_URL, $urlApi );
curl_setopt( $handle, CURLOPT_USERPWD, $username.':'.$password );
curl_setopt( $handle, CURLOPT_HTTPAUTH, CURLAUTH_BASIC );
curl_setopt( $handle, CURLOPT_TIMEOUT, 60 );
curl_setopt( $handle, CURLOPT_CONNECTTIMEOUT, 4); // set higher if you get a "28 - SSL connection timeout" error
curl_setopt ( $handle, CURLOPT_HEADER, true );
curl_setopt ( $handle, CURLOPT_HTTPHEADER, $headers );
$curlversion = curl_version();
curl_setopt ( $handle, CURLOPT_USERAGENT, 'PHP '.phpversion().' + Curl '.$curlversion['version'] );
curl_setopt ( $handle, CURLOPT_REFERER, null );
curl_setopt ( $handle, CURLOPT_SSL_VERIFYPEER, false ); // set false if you get a "60 - SSL certificate problem" error
curl_setopt ( $handle, CURLOPT_POSTFIELDS, $args );
curl_setopt ( $handle, CURLOPT_POST, true );
$response = curl_exec ( $handle );
echo $args;
if ($response)
{
$response = substr( $response, strpos( $response, "\r\n\r\n" ) + 4 ); // remove http headers
// parse response
$responseSimpleXml = simplexml_load_string($response);
if( $responseSimpleXml === false )
{
// invalid xml response
}
else
{
// parse response
$errorCode = $responseSimpleXml->response->responseCode ;
echo $errorCode;
if( $errorCode == 1000 ) // success
{
$usado = $responseSimpleXml->response->data->total_space;
$capacidad = $responseSimpleXml->response->data->space_limit;
echo 'Usado: '.$usado.'</br>Total: '.$capacidad.'.';
}
else // normal errors
{
$errors = $responseSimpleXml->response->errors;
foreach( $errors->error as $error )
{
// process error
}
}
}
}
else // http response code != 200
{
$error = curl_errno ( $handle ) . ' - ' . curl_error ( $handle );
}
curl_close($handle);
}
}
?>
Your variable $server must be an array, because, once decoded, %5B0%5D is [0].
My guess is to use $server[0] instead of $server wherever you replace the value. Without the replacement code, it is hard to determine.
I solved this using rawurlencode in the $listavps variable before using it.
<?php
$listavps = simplexml_load_file('servers.xml');
foreach ($listavps->servers->server as $key => $tag) {
$vps = rawurlencode ($tag);
$urlApi = 'url.php';
$username = 'user';
$password = 'pass';
$args = array('responseType' => 'Xml',
'serverName' => $vps,
'command' => 'Vps_GetUsedSpace',
) ;
I'm using PHP to config a webhook for a BOT.
I'd like to send picture from another server.
I've tried this way
function bot1($chatID,$sentText) {
$botUrl = 'https://api.telegram.org/bot'.self::_BOT_TOKEN_;
$img = "https://www.server2.com/1.jpeg";
$this->sendPhoto($botUrl,$chatID,$img);
}
function sendPhoto($botUrl,$chatID, $img){
$this->sendMessage($botUrl,$chatID,'This is the pic'.$chatID);
$this->sendPost($botUrl,"sendPhoto",$chatID,"photo",$img);
}
function sendMessage($botUrl,$chatID, $text){
$inserimento = file_get_contents($botUrl."/sendMessage?chat_id=".$chatID."&text=".$text."&reply_markup=".json_encode(array("hide_keyboard"=>true)));
}
function sendPost($botUrl,$function,$chatID,$type,$doc){
$response = $botUrl. "/".$function;
$post_fields = array('chat_id' => $chatID,
$type => new CURLFile(realpath($doc))
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
"Content-Type:multipart/form-data"
));
curl_setopt($ch, CURLOPT_URL, $response);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
$output = curl_exec($ch);
}
But I receive only the message.
What is the problem?
I've tried to change in http but the problem persists
Well, I've done a workaround because my cUrl version seems to have a bug in uploading file.
Now I use Zend FW
$botUrl = 'https://api.telegram.org/bot'.self::_BOT_TOKEN_;
$realpath = realpath($doc);
$url = $botUrl . "/sendPhoto?chat_id=" . $chatID;
$client = new Zend_Http_Client();
$client->setUri($url);
$client->setFileUpload($realpath, "photo");
$client->setMethod('POST');
$response = $client->request();
You have to send a file, not a URL.
So:
function bot1( $chatID,$sentText )
{
$botUrl = 'https://api.telegram.org/bot'.self::_BOT_TOKEN_;
$img = "https://www.server2.com/1.jpeg";
$data = file_get_contents( $img ); # <---
$filePath = "/Your/Local/FilePath/Here"; # <---
file_put_contents( $data, $filePath ); # <---
$this->sendPhoto( $botUrl, $chatID, $filePath ); # <---
}
This is as raw example, without checking success of file_get_contents().
In my bot I use this schema, and it works fine.
I have an AWS setup with Apache/PHP server on Port 80 and a REST Tomcat server on 8080.
If I try to access REST Services using IP Address A.B.C.D:8080/restapp from outside it works.
However if I try invoking from PHP code on the same box, it throws an internal error. Need your expert help in debugging this:
Checklist:
Security Profile:
8080 and 80 opened for 0.0.0.0/0
URL to be invoked: http://ec2-A-B-C-D.us-west-1.compute.amazonaws.com/myapp/ba-simple-proxy1.php?url=http://ec2-A-B-C-D.us-west-1.compute.amazonaws.com:8080/restapp/rest/user
ERROR RESPONSE:
"NetworkError: 500 Internal Server Error - http://ec2-A-B-C-D.us-west-1.compute.amazonaws.com/myapp/ba-simple-proxy1.php?url=http://ec2-A-B-C-D.us-west-1.compute.amazonaws.com:8080/restapp/rest/user"
Code Snippet from PHP - ba-simple-proxy1.php:
//print $url;
if ( !$url ) {
// Passed url not specified.
$contents = 'ERROR: url not specified';
$status = array( 'http_code' => 'ERROR' );
} else if ( !preg_match( $valid_url_regex, $url ) ) {
// Passed url doesn't match $valid_url_regex.
$contents = 'ERROR: invalid url';
$status = array( 'http_code' => 'ERROR' );
} else {
$ch = curl_init( $url );
if ( strtolower($_SERVER['REQUEST_METHOD']) == 'post' ) {
curl_setopt( $ch, CURLOPT_POST, true );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $_POST );
}
if ( $_GET['send_cookies'] ) {
$cookie = array();
foreach ( $_COOKIE as $key => $value ) {
$cookie = array();
foreach ( $_COOKIE as $key => $value ) {
$cookie[] = $key . '=' . $value;
}
if ( $_GET['send_session'] ) {
$cookie[] = SID;
}
$cookie = implode( '; ', $cookie );
curl_setopt( $ch, CURLOPT_COOKIE, $cookie );
}
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_HEADER, true );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_USERAGENT, $_GET['user_agent'] ? $_GET['user_agent'] : $_SERVER['HTTP_USER_AGENT'] );
list( $header, $contents ) = preg_split( '/([\r\n][\r\n])\\1/', curl_exec( $ch ), 2 );
//print $ch;
$status = curl_getinfo( $ch );
curl_close( $ch );
}
Turns out the php_curl lib was not part of PHP5 installation. I installed it and everything works fine now.