PHP - Upload file to another server without curl - php

I have one question, can i upload file to another server without curl..
Because not every server have CURL ...
Thanks...

Yes it is possible using pure PHP fopen together with stream_context_create. The following example comes from the online PHP manual (http://php.net/manual/en/function.stream-context-create.php):
function do_post_request($url, $postdata, $files = null)
{
$data = "";
$boundary = "---------------------".substr(md5(rand(0,32000)), 0, 10);
//Collect Postdata
foreach($postdata as $key => $val)
{
$data .= "--$boundary\n";
$data .= "Content-Disposition: form-data; name=\"".$key."\"\n\n".$val."\n";
}
$data .= "--$boundary\n";
//Collect Filedata
foreach($files as $key => $file)
{
$fileContents = file_get_contents($file['tmp_name']);
$data .= "Content-Disposition: form-data; name=\"{$key}\"; filename=\"{$file['name']}\"\n";
$data .= "Content-Type: image/jpeg\n";
$data .= "Content-Transfer-Encoding: binary\n\n";
$data .= $fileContents."\n";
$data .= "--$boundary--\n";
}
$params = array('http' => array(
'method' => 'POST',
'header' => 'Content-Type: multipart/form-data; boundary='.$boundary,
'content' => $data
));
$ctx = stream_context_create($params);
$fp = fopen($url, 'rb', false, $ctx);
if (!$fp) {
throw new Exception("Problem with $url, $php_errormsg");
}
$response = #stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
return $response;
}
//set data (in this example from post)
//sample data
$postdata = array(
'name' => $_POST['name'],
'age' => $_POST['age'],
'sex' => $_POST['sex']
);
//sample image
$files['image'] = $_FILES['image'];
do_post_request("http://example.com", $postdata, $files);

It is possible to use ftp_put:
define("LOCAL_FILE","PATH_TO_LOCAL_FILE");
define("FTP_ADDRESS","ftp.domain.com");
define("FTP_FILE","PATH_TO_REMOTE_FILE");
define("FTP_USERNAME","USERNAME");
define("FTP_PASSWORD","PASWORD");
$conn = ftp_connect(FTP_ADDRESS);
$login = ftp_login($conn, FTP_USERNAME, FTP_PASSWORD);
ftp_put($conn, FTP_FILE, LOCAL_FILE, FTP_ASCII);
ftp_close($conn);
Whereas, the ftp domain would supply you with the location to the ftp file as well as the username and password.

Related

PHP - send content directly from extern server to client without changing url

I couldn't come up with a better title, well follow scenario:
The client sends an API request to serverA.com, based on the userid he needs to get a json file from a specific server, let's say serverC.com
So far I'm using this code on serverA.com:
function redirect_post($url, $data, $headers = null) {
$params = [
'http' => [
'method' => 'POST',
'content' => http_build_query($data)
]
];
if (!is_null($headers)) {
$params['http']['header'] = '';
foreach ($headers as $k => $v) {
$params['http']['header'] .= "$k: $v\n";
}
}
$ctx = stream_context_create($params);
$fp = #fopen($url, 'rb', false, $ctx);
if ($fp) {
echo #stream_get_contents($fp);
die();
} else {
// Error
throw new Exception("Error loading '$url', $php_errormsg");
}
}
redirect_post('https://serverC.com', $_POST);
it works but I guess serverC.com sends the file to serverA.com first which then sends it to the client? If it's not the case and the user get's the content directly from serverC.com then how could I test it/make sure that that's the case?
But if it's not the case then is what I need even possible?

Send SMS using BulkSMS.com

I tried to send an SMS from my PHP website to a mobile phone using the BulkSMS API. I used the code below, but I don't know what went wrong. I didn't receive the SMS and nothing is showing up in the browser, just a blank page .
<?php
$url = 'http://bulksms.vsms.net/eapi/submission/send_sms/2/2.0';
$to=some number;
$username = 'usernme';
$password = 'password';
$sender='BBMS';
$msisdn = '+968'.$to;
$content="Test";
function do_post_request($url, $data, $optional_headers = 'Content-type:application/x-www-form-urlencoded'){
$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, $php_errormsg");
}
$response = #stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
return $response;
var_dump($response);
}
?>

Google Tracks API "Bad Request" using PHP

I am using Google Tracks API to build a simple web based program to track a vehicle that has a tracking device sending latitude and longitude coordinates.
I am using PHP and the OAuth2 PHP library to make an authorized connection.
After authorizing and getting an access token I am making a request to create entities. Though I can't seem to get this working and keep getting a "400 Bad Request" response. Following all the steps shown in the documentation.
Here is my code:
$url = 'https://www.googleapis.com/tracks/v1/entities/create/?access_token='.$parsedAuth['access_token'];
$data = array('entities' => array( "name"=> "Chevrolet" ));
$json_data = json_encode($data);
$data_length = http_build_query($data);
$options = array(
'http' => array(
'header' => "Content-type: application/json\r\n". "Content-Length: " . strlen($data_length) . "\r\n",
'method' => 'POST',
'content' => $json_data
),
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
var_dump($response);
Exact Error is: "failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request"
Why am I getting a bad request? What would be a good request that will register these entities and return id's?
Thank you
The answer given here is wrong. The documentation states that it must be a POST see here My issue was not with the Auth but with the Tracks API itself. I ended up moving to create the request with CURL and it works just fine.
Please. This is PHP with CURL. It works 100%.
//Google maps tracks connection
//Get Files From PHP Library
require_once 'google-api-php-client/src/Google/autoload.php';
require_once 'google-api-php-client/src/Google/Service/MapsEngine.php';
//Set Client Credentials
$client_id = '*************.apps.googleusercontent.com'; //Client ID
$service_account_name = '************#developer.gserviceaccount.com'; //Email Address
$client_email = '*************#developer.gserviceaccount.com';
$private_key = file_get_contents('************.p12');
$scopes = array('https://www.googleapis.com/auth/tracks');
//Create Client
$client = new Google_Client();
$client->setApplicationName("Client_Library_Examples");
//Send Credentials
$credentials = new Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key
);
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion($credentials);
}
if (isset($_SESSION['service_token'])) {
$client->setAccessToken($_SESSION['service_token']);
}
$client->setAssertionCredentials($credentials);
$_SESSION['service_token'] = $client->getAccessToken();
foreach ($_SESSION as $key=> $value) {
$vars = json_decode($value);
}
$parsedAuth = (array) $vars;
$token = $parsedAuth['access_token'];
//all functions in the program use this auth token- It should be global for easy accesses.
global $token;
function createEntities(){
global $token;
$url = 'https://www.googleapis.com/tracks/v1/entities/create/?access_token='.$token;
//FIX ME: fields is temporarily hard coded- should be brought from DB
$fields = array(
'entities' => array(
'name' => "DemoTruck",
'type' => "AUTOMOBILE"
),
);
//json string the data for the POST
$query_string = '';
foreach($fields as $key => $array) {
$query_string .= '{"' . urlencode($key).'":[{';
foreach($array as $k => $v) {
$query_string .= '"' . urlencode($k) . '":"' . urlencode($v) . '",';
}
}
$str = rtrim($query_string , ',');
$fstr = $str.'}]}';
$length = strlen( $fstr );
//open connection
$ch = curl_init();
//test connection
if (FALSE === $ch)
throw new Exception('failed to initialize');
//set options
$header = array('Content-type: application/json');
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_HTTPHEADER, $header);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fstr);
$result = curl_exec($ch);
//dump in case of error
if (FALSE === $result){
var_dump( curl_error($ch) );
var_dump( curl_getinfo($ch) );
}
//close connection
curl_close($ch);
}

Add a cache to json_decode Twitter API

I'm trying to add a cache machanism to json_decode fetching Twitter API. The important part is the one regarding $cache and the if below it.
<?php
function buildBaseString($baseURI, $method, $params)
{
$r = array();
ksort($params);
foreach($params as $key=>$value){
$r[] = "$key=" . rawurlencode($value);
}
return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r)); //return complete base string
}
function buildAuthorizationHeader($oauth)
{
$r = 'Authorization: OAuth ';
$values = array();
foreach($oauth as $key=>$value)
$values[] = "$key=\"" . rawurlencode($value) . "\"";
$r .= implode(', ', $values);
return $r;
}
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
$oauth_access_token = "XXXXXXXXX";
$oauth_access_token_secret = "XXXXXXX";
$consumer_key = "XXXXXXX";
$consumer_secret = "XXXXXXX";
$oauth = array( 'oauth_consumer_key' => $consumer_key,
'oauth_nonce' => time(),
'oauth_signature_method' => 'HMAC-SHA1',
'oauth_token' => $oauth_access_token,
'oauth_timestamp' => time(),
'count' => 6,
'oauth_version' => '1.0');
$base_info = buildBaseString($url, 'GET', $oauth);
$composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
$oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
$oauth['oauth_signature'] = $oauth_signature;
$header = array(buildAuthorizationHeader($oauth), 'Expect:');
$options = array( CURLOPT_HTTPHEADER => $header,
CURLOPT_HEADER => false,
CURLOPT_URL => $url . '?count=6',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYPEER => false);
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$cache = './wp-content/themes/multiformeingegno/twitter_json/'.sha1($url).'.json';
if(file_exists($cache) && filemtime($cache) > time() - 1000){
// if a cache file newer than 1000 seconds exist, use it
$twitter_data = json_decode(file_get_contents($cache));
} else {
$twitter_data = json_decode((file_get_contents($url)));
file_put_contents($cache,json_encode($twitter_data));
}
echo "<ul style='color:#6E6E6E'>";
foreach ($twitter_data as $tweet)
{
if (!empty($tweet)) {
$text = $tweet->text;
$text_in_tooltip = str_replace('"', '', $text); // replace " to avoid conflicts with title="" opening tags
$id = $tweet->id;
$time = strftime('%d %B', strtotime($tweet->created_at));
$username = $tweet->user->name;
}
echo '<li><span title="'; echo $text_in_tooltip; echo '">'; echo $text . "</span><br>
<small>'; echo $time; echo '</small> -
<small>rispondi</small> -
<small>retweet</small> -
<small>preferito</small></li>';
}
echo '</ul>';
?>
Unfortunately I'm getting these errors:
FastCGI sent in stderr: "PHP message: PHP Warning: file_get_contents(https://api.twitter.com/1.1/statuses/user_timeline.json): failed to open stream: HTTP request failed! HTTP/1.0 400 Bad Request
in /wp-content/themes/multiformeingegno/homepage_copy.php on line 62
PHP message: PHP Warning: file_put_contents(./wp-content/themes/multiformeingegno/twitter_json/38f925d2889d7b60d4f18c448a90ab03419721c4.json): failed to open stream: No such file or directory in /wp-content/themes/multiformeingegno/homepage_copy.php on line 63
PHP message: PHP Warning: Invalid argument supplied for foreach() in /wp-content/themes/multiformeingegno/homepage_copy.php on line 68" while reading response header from upstream, client: 94.37.252.247, server: multiformeingegno.it, request: "GET /wp-content/themes/multiformeingegno/homepage_copy.php HTTP/1.1", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host: "multiformeingegno.it"
You're trying to open the twitter url using file_get_contents when you have a cache miss, which is totally unnecessary since you already got the json data via curl
See the ** commented ** line in the code below
$feed = curl_init();
curl_setopt_array($feed, $options);
$json = curl_exec($feed);
curl_close($feed);
$cache = './wp-content/themes/multiformeingegno/twitter_json/'.sha1($url).'.json';
if(file_exists($cache) && filemtime($cache) > time() - 1000){
// if a cache file newer than 1000 seconds exist, use it
$twitter_data = json_decode(file_get_contents($cache));
} else {
// ** decode the json you got from the curl request here **
$twitter_data = json_decode($json);
file_put_contents($cache,json_encode($twitter_data));
}

How to upload video files on cdn server?

I am trying to upload video on cdn server(hwcdn.net server) through api, but getting the following error .
" 0470 Invalid file name (A-Z,a-z,0-9,-,_,',.) "
//PHP example code for calling an action:
$action = "UF"; //get system info
$user = "xxxxxx"; //my StrikeTracker user name
$pass = "xxxxxx"; //my StrikeTracker password
$apiKey ="xxxxxxxxxxxxxxxxxxxx"; //my API Key
$md5pass = md5($pass);
$queryString = "action=$action&user=$user&key=$apiKey&password=$md5pass";
$token =md5($queryString);
$directory="/folder path/";
$Filedata="testingvideo.flv";
echo $apiQuery = "action=$action&user=$user&token=$token&directory=$directory&Filedata=$Filedata";
$host="http://st-api.hwcdn.net/index.php";
echo do_post_request($host,$apiQuery);
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, $php_errormsg");
}
$response = #stream_get_contents($fp);
if ($response === false) {
throw new Exception("Problem reading data from $url, $php_errormsg");
}
return $response;
}
I think this is wrong :
$directory="/folder path/";
The space is not allowed in hwcdn paths.
The answer is in the error: the filename contains illegal chars, you have to sanitize it removing everything that is not A-Z,a-z,0-9,-,_,',..
You can use preg_replace.

Categories