PHP cURL script adding a 'space' at end of filename - php

I'm calling a PHP script via AJAX that saves a remote image locally (via Mapbox API). Everything works great, except for the result includes a 'space' (filename.jpg[space]) at the end of the string.
Javascript:
var mapboxUrl = 'https://api.mapbox.com/v4/motioncrafter.96d11990/' + longitude + ',' + latitude + ',11/1280x720#2x.jpg80?access_token=pk.eyJ1IjoibW90aW9uY3JhZnRlciIsImEiOiJjaWg2dHJvM2YwNndudjJrdGI2amUzdnlyIn0.oN201-rjUC4DHhz7QhGJRA';
$.ajax({
type: "POST",
url: "../../php/map.php",
data: {
map: mapboxUrl,
},
success: function(result) {
$('.video_map').val(result);
}
});
PHP:
<?php
$mapboxUrl = $_POST["map"];
$path = "../images/user-maps/";
$imageFile = $path . "map_wide_" . rand(10000, 99999) . time() . ".jpg";
$ch = curl_init($mapboxUrl);
$fp = fopen($imageFile, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
echo $imageFile;
?>
Any idea why this space is showing up?

Get rid of this line:
?>
I suspect you have a space after that. Everything outside <?php ... ?> gets sent to the client, so if it's actually ?><space>, the space will be appended to the image filename.
There's no need to have ?> at the end of a script, the end of the file automatically tells PHP to stop processing the code.

Related

How PHP get the content from web service?

I have a problem in getting the content/array from web service to my php code. When I type in the url in browser like http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD, then the result in the browser is displayed like this: [ 1.20MYR , 0.39SGD ]. My PHP code looks like this:
$ch = curl_init('http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);
echo $content;
Unfortunately, I get nothing use the code above. Looking for help.
Thanks.
UPDATED
$data=array(
'amount'=>1.2,
'fromCurrency'=>'MYR',
'toCurrency'=>'SGD'
);
$data_string = json_encode($data);
$ch = curl_init('http://server1-xeon.asuscomm.com/currency/WebService.asmx/YaHOO_CurrencyEx');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array('Content-type: application/json'));
$content= curl_exec($ch);
curl_close($ch);
$obj = json_decode($content);
echo $obj;
This page contains dynamic content, loaded by JavaScript. You can see it in Google Chrome for example by access view-source:http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD.
If you look closer to the source code of the page (file http://server1-xeon.asuscomm.com/currency/JQuery/app_converter.js) you'll see, that it uses this code to get exchange data under the hood:
$.ajax({type: "POST",
url: "WebService.asmx/YaHOO_CurrencyEx", // important: it's a relative URL!
data: "{amount:" + amount + ",fromCurrency:'" + from + "',toCurrency:'" + to + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {},
success: function (data) {
$('#results').html(' [ ' + amount + from + ' , ' + data.d.toFixed(2) + to + ' ] ');
});
So, actually you can make such request in PHP to avoid access dynamic content on the http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD page.
UPD:
I've added a more complete explanation.
By the time the page on http://server1-xeon.asuscomm.com/currency/?amount=1.20,from=MYR,to=SGD is loaded, a JavaScript code on this page (it means that it's executed on the client side, in a browser, not on your server) parses URL parameters and makes AJAX POST request to the URL http://server1-xeon.asuscomm.com/currency/WebService.asmx/YaHOO_CurrencyEx. It passes a JSON payload {amount:1.20,fromCurrency:'MYR',toCurrency:'SGD'} and gets a response like this {"d":0.390360}. So, you can just make a direct POST request to the http://server1-xeon.asuscomm.com/currency/WebService.asmx/YaHOO_CurrencyEx via curl, passing an amount, fromCurrency and toCurrency in JSON body and then decode received JSON response using json_decode($content);.
How data should look? Add this to your code from "UPDATED" and run:
$array["MYR"] = 1.2;
$array["SGD"] = doubleval($obj->d)
// Print simple array (print source for example)
echo "<pre>";
print_r($array);
echo "</pre>";
// Print true JSON-array
print_r(json_encode($array));
In web browser you will see:
Array
(
[MYR] => 1.2
[SGD] => 0.39036
)
{"MYR":1.2,"SGD":0.39036}
Can't understand your problem at this moment.
If you want print only returned value (digits), do it: echo $obj->d;

jQuery send file chunks to PHP upload to Ooyala

I have been stuck on this for over a week and I think I am long overdue for asking on here.. I am trying to get my users to upload their video files using the jQuery File Upload Plugin. We do not want to save the file on our server. The final result is having the file saved in our Backlot using the Ooyala API. I have tried various approaches and I am successful in creating the asset in Backlot and getting my upload URLs, but I do not know how to upload the file chunks using the URLs into Backlot. I have tried FileReader(), FormData(), etc. I am pasting the last code I had that created the asset, and gave me the upload URLs, but did not save any chunks into Backlot. I assume I may be getting stuck in one of my AJAX calls, but I am not very sure.
I keep getting:
Uncaught InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable.
Here is my page with the JS for the jQuery File Upload widget by BlueImp:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="<?php print base_path() . path_to_theme() ?>/res/js/jQuery-File-Upload/js/vendor/jquery.ui.widget.js"></script>
<script type="text/javascript" src="<?php print base_path() . path_to_theme() ?>/res/js/jQuery-File-Upload/js/jquery.iframe-transport.js"></script>
<script type="text/javascript" src="<?php print base_path() . path_to_theme() ?>/res/js/jQuery-File-Upload/js/jquery.fileupload.js"></script>
</head>
<body>
<input id="fileupload" type="file" accept="video/*">
<script>
//var reader = FileReader();
var blob;
$('#fileupload').fileupload({
forceIframeTransport: true,
maxChunkSize: 500000,
type: 'POST',
add: function (e, data) {
var goUpload = true;
var ext = ['avi','flv','mkv','mov','mp4','mpg','ogm','ogv','rm','wma','wmv'];
var uploadFile = data.files[0];
var fileName = uploadFile.name;
var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
if ($.inArray( fileExtension, ext ) == -1) {
alert('You must upload a video file only');
goUpload = false;
}
if (goUpload == true) {
$.post('../sites/all/themes/episcopal/parseUploadJSON.php', 'json=' + JSON.stringify(data.files[0]), function (result) {
var returnJSON = $.parseJSON(result);
data.filechunk = data.files[0].slice(0, 500000);
data.url = returnJSON[0];
//reader.onloadend = function(e) {
//if (e.target.readyState == FileReader.DONE) { // DONE == 2
//data.url = returnJSON[0];
// }
//}
//$.each(returnJSON, function(i, item) {
//data.url = returnJSON[0];
//blob = data.files[0].slice(0, 500000);
//console.log(blob);
//reader.readAsArrayBuffer(blob);
//data.submit();
//});
data.submit();
});
}
},//end add
submit: function (e, data) {
console.log(data); //Seems fine
//console.log($.active);
$.post('../sites/all/themes/episcopal/curlTransfer.php', data, function (result) { //fails
console.log(result);
});
return false;
}
});
</script>
</body></html>
Then there is the parseUploadJSON.php code, please keep in mind that my real code has the right Backlot keys. I am sure of this:
<?php
if(isset($_POST['json'])){
include_once('OoyalaAPI.php');
$OoyalaObj = new OoyalaApi("key", "secret",array("baseUrl"=>"https://api.ooyala.com"));
$expires = time()+15*60; //Adding 15 minutes in seconds to the current time
$file = json_decode($_POST['json']);
$responseBody = array("name" => $file->name,"file_name"=> $file->name,"asset_type" => "video","file_size" => $file->size,"chunk_size" => 500000);
$response = $OoyalaObj->post("/v2/assets",$responseBody);
$upload_urls = $OoyalaObj->get("/v2/assets/".$response->embed_code."/uploading_urls");
$url_json_string = "{";
foreach($upload_urls as $key => $url){
if($key+1 != count($upload_urls)){
$url_json_string .= '"' . $key . '":"' . $url . '",';
}else {
$url_json_string .= '"' . $key . '":"' . $url . '"';
}
}
$url_json_string .= "}";
echo $url_json_string;
}
?>
Then I have the curlTransfer.php:
<?php
echo "starting curl transfer";
echo $_POST['filechunk'] . " is the blob";
if(isset($_FILES['filechunk']) && isset($_POST['url'])){
echo "first test passed";
$url = $_POST['url'];
//print_r(file_get_contents($_FILES['filechunk']));
$content = file_get_contents($_FILES['filechunk']);
print_r($content);
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt ($ch, CURLOPT_HTTPHEADER, Array("Content-Type: multipart/mixed"));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS, $content);
try {
//echo 'success';
return httpRequest($ch);
}catch (Exception $e){
throw $e;
}
}
/****Code from Ooyala****/
function httpRequest($ch){
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$response = curl_exec($ch);
if(curl_error($ch)){
curl_close($ch);
return curl_error($ch);
}
$head=curl_getinfo($ch);
$content = $head["content_type"];
$code = $head["http_code"];
curl_close($ch);
}
?>
And the OoyalaApi.php is here (I saved a copy on my server):
https://github.com/ooyala/php-v2-sdk/blob/master/OoyalaApi.php
I apologize in advance if the code is messy and there's a lot of parts commented out. I have changed this code so much and I cannot get it. I appreciate all of your time and effort.
EDIT
I went back to trying FileReader out as this post Send ArrayBuffer with other string in one Ajax call through jQuery kinda worked for me, but I think it would be safer to read it using readAsArrayBuffer and now I am having trouble saving the array buffer chunks in some sort of array...
We have implemented ooyala file chunk upload in Ruby On Rails by referring this.
We have used the entire JS file as it is from this link.
https://github.com/ooyala/backlot-ingestion-library

script not showing any alert

here i am supposed to call a web service in php and the return json of the web service is stored in a variable called $response,then i am passing that json to javascript ,here i am parsing the json and depending on the type of the employee and each type have differebt attributes i am alerting all ,when i have did the same function in another page for testing it was working where i have given value to var txt='' by hardcoding , when i have integrated the php web service with the one i havew tried nothing is having ,i am confused there is no error showing with javascript console.
<?php
session_start();
$regid=$_SESSION['product_registration_id'];
//echo $regid;
$details=array(
'product_registration_id'=> "$regid");
//coverting the vlaues collected from form into json
//calling the web service
$url='webservice url';
$data=$details;
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($details));
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
$response= curl_exec($ch);
echo ("The Server Response is:" .$response);
curl_close($ch);
json_decode($response);
$json_a=json_decode($response,true);
echo $json_a[expired];
echo $json_a[account_detail][0];
?>
</div>
<script>
var txt = '<?php echo $response ?>';
alert(txt);
//var jsonData = eval ("(" + txt + ")");
var jsonData = JSON.parse(txt);
for (var i = 0; i < jsonData.employees.length; i++) {
var counter = jsonData.employees[i];
//console.log(counter.counter_name);
alert(counter.type);
if(counter.type=="0")
{
alert(counter.building_name);
alert(counter.org_name);
alert(counter.user_name);
alert(counter.name);
alert(counter.loc_name);
alert(counter.email_id);
alert(counter.password);
}
if(counter.type=="1")
{
alert(counter.user_name);
alert(counter.name);
alert(counter.password);
alert(counter.email_id);
}
if(counter.type=="2")
{
alert(counter.building_name);
alert(counter.org_name);
alert(counter.user_name);
alert(counter.opr_code);
alert(counter.name);
alert(counter.loc_name);
alert(counter.email_id);
alert(counter.password);
}
if(counter.type=="3")
{
alert(counter.building_name);
alert(counter.org_name);
alert(counter.machine_type);
alert(counter.activate_status);
alert(counter.machine_name);
alert(counter.entrance_exit_name);
alert(counter.entrance_or_exit);
alert(counter.loc_name);
alert(counter.activation_code);
}
}
</script>
if you want the php array to be an array in javascript you must:
<?php echo json_encode($response) ?>
this does not need to be parsed in javascript, it will already be an array because the echo will return something in the likings of {'message': 'hellew world'} of ['value1','value2'] which in javascript is an array or an object definition.
So remove the parsing in javascript.
If response contains a quote you will get a js syntax error. Nothing from there on will be processed. So... no alerts. Check the response. Escape the quotes.

Get the filesize of a js file on another domain using php

How do I get the filesize of js file on another website. I am trying to create a monitor to check that a js file exists and that it is more the 0 bytes.
For example on bar.com I would have the following code:
$filename = 'http://www.foo.com/foo.js';
echo $filename . ': ' . filesize($filename) . ' bytes';
You can use a HTTP HEAD request.
<?php
$url = "http://www.neti.ee/img/neti-logo.gif";
$head = get_headers($url, 1);
echo $head['Content-Length'];
?>
Notice: this is not a real HEAD request, but a GET request that PHP parses for its Content-Length. Unfortunately the PHP function name is quite misleading. This might be sufficient for small js files, but use a real HTTP Head request with Curl for bigger file sizes because then the server won't have to upload the whole file and only send the headers.
For that case, use the code provided by Jakub.
Just use CURL, here is a perfectly good example listed:
Ref: http://www.php.net/manual/en/function.filesize.php#92462
<?php
$remoteFile = 'http://us.php.net/get/php-5.2.10.tar.bz2/from/this/mirror';
$ch = curl_init($remoteFile);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //not necessary unless the file redirects (like the PHP example we're using here)
$data = curl_exec($ch);
curl_close($ch);
if ($data === false) {
echo 'cURL failed';
exit;
}
$contentLength = 'unknown';
$status = 'unknown';
if (preg_match('/^HTTP\/1\.[01] (\d\d\d)/', $data, $matches)) {
$status = (int)$matches[1];
}
if (preg_match('/Content-Length: (\d+)/', $data, $matches)) {
$contentLength = (int)$matches[1];
}
echo 'HTTP Status: ' . $status . "\n";
echo 'Content-Length: ' . $contentLength;
?>
Result:
HTTP Status: 302
Content-Length: 8808759
Another solution. http://www.php.net/manual/en/function.filesize.php#90913
This is just a two step process:
Crawl the the js file and store it to a variable
Check if the length of the js file is greater than 0
thats it!!
Here is how you can do it in PHP
<?php
$data = file_get_contents('http://www.foo.com/foo.js');
if(strlen($data)>0):
echo "yay"
else:
echo "nay"
?>
Note: You can use HTTP Head as suggested by Uku but then if you are seeking for the page content if js file has content then you would have to crawl again :(

Using jQuery to parse XML returned from PHP script (imgur.com API)

Here's my jQuery:
var docname = $('#doc').val();
function parseXml(xml)
{
$(xml).find("rsp").each(function()
{
alert("success");
});
}
$('#submit').click(function() {
$.ajax({
type: "GET",
url: "img_upload.php",
data: "doc=" + docname,
dataType: "xml",
success: parseXml
});
return false;
});
Note that #doc is the id of a form text input box and #submit is the submit button's id. If successful, I'd like a simple "success" javascript popup to appear.
Here's img_upload.php with my API key omitted:
<?php
$filename = $_GET["doc"];
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
// $data is file data
$pvars = array('image' => base64_encode($data), 'key' => <MY API KEY>);
$timeout = 30;
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://imgur.com/api/upload.xml');
curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $pvars);
$xml = curl_exec($curl);
curl_close ($curl);
?>
When directly accessed with a GET argument for "doc", img_upload.php file returns the following XML format:
<?xml version="1.0" encoding="utf-8"?>
<rsp stat="ok">
<image_hash>cxmHM</image_hash>
<delete_hash>NNy6VNpiAA</delete_hash>
<original_image>http://imgur.com/cxmHM.png</original_image>
<large_thumbnail>http://imgur.com/cxmHMl.png</large_thumbnail>
<small_thumbnail>http://imgur.com/cxmHMs.png</small_thumbnail>
<imgur_page>http://imgur.com/cxmHM</imgur_page>
<delete_page>http://imgur.com/delete/NNy6VNpiAA</delete_page>
</rsp>
What's the problem here?
Here's the Imgur API page for reference.
var docname = $('#doc').val();
Exactly where is this in your code and when will it be evaluated?
My guess is that it's executed either when the <script> tag has been parsed or you've wrapped it in a $(document).ready() handler. Either way it get's evaluated before the user has actually typed something into the input/text control and docname will therefore be '' or even null all the time. You want the script to fetch the value not until the user has pressed the submit button.
Try it with
$('#submit').click(function() {
$.ajax({
type: "GET",
url: "img_upload.php",
data: "doc=" + $('#doc').val(),
dataType: "xml",
success: parseXml
});
return false;
});
edit: Even better, make the data property an object and let jquery handle the escaping of the value.
data: {doc: $('#doc').val()}
It could be that you have not set the header in the php script - this should be your first line.
header('Content-Type: text/xml');

Categories