Calculate Remote Image File Size Using PHP - php

How can I find the file size of an image on a remote server? On the local machine, I can use filesize(), but I want to find the size without downloading the image.

// Similar solution seen in another stackoverflow post:
// By default get_headers uses a GET request to fetch the headers. If you
// want to send a HEAD request instead, you can do so using a stream context:
stream_context_set_default(
array(
'http' => array(
'method' => 'HEAD'
)
)
);
$headers = get_headers($source_file,1);
$source_file_size = null;
if (is_array($headers) && array_key_exists('Content-Length',$headers)) {
$source_file_size = intval($headers['Content-Length']);
}
if ($source_file_size === null){ //we didn't get a Content-Length header
/** Grab file to local disk and use filesize() to set $size **/
}
stream_context_set_default(
array(
'http' => array(
'method' => 'GET'
)
)
);

Related

php post file using file_get_contents does not work for some file types

The following code works fine, however if I change the files to use myFile.pdf or myFile.xlsx the file gets created with 0 bytes. only thing that changes for the working version and the non working version is the file type. Why am I getting 0 bytes with excel files and pdfs?
$file = file_get_contents('myFile.xml');
$url = 'destination.php';
$post_data = array(
"file" => $file,
"fileName" => "myFile.xml"
);
$stream_options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: application/x-www-form-urlencoded',
'content' => http_build_query($post_data),
),
);
$context = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);
echo $response;
then my destination file saves the file like this:
file_put_contents($_POST["fileName"], $_POST["file"]);
?>
In My instance the problem was actually with file size restrictions on the server and the file types were just coincidental. check post_max_size and upload_max_filesize.

Uploading Videos to Twitter using API

I'm using the library tmhOAuth to post to Twitter in an app and I've already implemented uploading pictures but am having trouble implementing video upload.
This is the call I use to upload pictures and works perfectly with images.
$temp = '#upload/'.$name.';type='.$_FILES['img']['type'].';filename='.$name;
$media = $tmhOAuth->request('POST', 'https://upload.twitter.com/1.1/media/upload.json', array('media' => $temp), true, true);
So I thought it might be the same for videos but I got the error
stdClass Object ( [request] => /1.1/media/upload.json [error] => media type unrecognized. )
I believe I have to make 3 separate calls, as per the Twitter API, so I tried this
$media = $tmhOAuth->request('POST', 'https://upload.twitter.com/1.1/media/upload.json?command=INIT&media_type=video/mp4&total_bytes='.$_FILES['img']['size'], array('media' => $temp), true, true);
$media_id = json_decode($tmhOAuth->response['response'])->media_id_string;
$media = $tmhOAuth->request('POST', 'https://upload.twitter.com/1.1/media/upload.json?command=APPEND&media_id='.$media_id.'&segment_index=0', array('media' => $temp), true, true);
$media = $tmhOAuth->request('POST', 'https://upload.twitter.com/1.1/media/upload.json?command=FINALIZE&media_id='.$media_id, array('media' => $temp), true, true);
but I kept getting the same error for all 3 calls
stdClass Object ( [request] => /1.1/media/upload.json [error] => media type unrecognized. )
Can anyone provide an example as to how to upload videos to twitter? I could find no examples online and it might just not be possible.
I had the same problem. Here's how I managed to solve it.
First you set up a var containing the filesystem full path to the media you want to upload.
$media_path = '/PATH/TO/THE/file.mp4';
Then instantiate $tmhOAuth and do the 3 steps :
$tmhOAuthUpload = new tmhOAuth();
INIT:
$code = $tmhOAuthUpload->request(
'POST',
$tmhOAuthUpload->url('/1.1/media/upload.json'),
array(
"command" => "INIT",
"total_bytes" => (int)filesize($media_path),
'media_type' => 'video/mp4',
)
);
Retrieve media id returned by Twitter
$results = json_decode($tmhOAuthUpload->response['response']);
$media_id = $results->media_id_string;
APPEND: Handle video/media upload with the Append loop
$fp = fopen($media_path, 'r');
$segment_id = 0;
while (! feof($fp)) {
$chunk = fread($fp, 1048576); // 1MB per chunk for this sample
$tmhOAuthUpload->request(
'POST',
$tmhOAuthUpload->url('/1.1/media/upload.json'),
array(
"command" => "APPEND",
"media_id" => $media_id,
'media_data' => base64_encode($chunk),
"segment_index" => $segment_id
)
);
$segment_id++;
}
FINALIZE:
$tmhOAuthUpload->request(
'POST',
$tmhOAuthUpload->url('/1.1/media/upload.json'),
array(
"command" => "FINALIZE",
"media_id" => $media_id,
)
);
By then I was able to to send my tweet:
$code = $tmhOAuth->request(
'POST',
$tmhOAuthUpload->url('1.1/statuses/update'),
array(
'media_ids' => $media_id,
'status' => $text,
),
true // use auth
);
Hope that helps
I've only been able to get video uploading working with CodeBird - a different PHP library.
The Twitter API calls for video are quite different from uploading images, as you've discovered.
Uploading videos to Twitter (≤ 15MB, MP4) requires you to send them in chunks. You need to perform at least 3 calls to obtain your media_id for the video:
Send an INIT event to get a media_id draft.
Upload your chunks with APPEND events, each one up to 5MB in size.
Send a FINALIZE event to convert the draft to a ready-to-tweet media_id.
Post your tweet with video attached.
Remember, each APPEND must be 5MB or under.
If you are consistently getting "Media Type Unrecognised" errors, it might be that the video you are using is incompatible with Twitter. Can you test uploading the video via another service?
Thank you very much for that answer Pierre! I was however getting a “Not valid video” error if I tried to create the tweet too soon. The video wasn't done being processed by Twitter. In addition to Pierre's code, I needed something like this to check STATUS, after FINALIZE:
$videoCount = 0;
do
{
$tmhOAuth->request(
'GET',
$tmhOAuth->url('/1.1/media/upload.json'),
array(
"command" => "STATUS",
"media_id" => $mediaID,
)
);
$twitterResult = json_decode($tmhOAuth->response['response']);
if ($twitterResult->processing_info->state != 'succeeded')
{ sleep(5); }
$videoCount++;
}
while ($twitterResult->processing_info->state != 'succeeded' && $videoCount < 5);
Note: my variable names are different

Is there a way to have a php script execute with a specific ip address

Is there way to have a php script that uses file_get_contents to utilize an ip address different than what the server's ip address is? We have 5 ip addresses and want to utilize a specific one for this purpose.
Yes, it's possible. You have to configure the stream context you want to use though.
<?php
// context options
$ctxopts = array(
'socket' => array(
'bindto' => '192.168.0.100:0',
),
);
// create the context...
$context = stream_context_create($ctxopts);
// ...and use it to fetch the data
echo file_get_contents('http://www.example.com', false, $context);
You can get more info on http://php.net/manual/en/context.socket.php
Per the documentation that is easily accessible on php.net
context
A valid context resource created with stream_context_create(). If you don't need to use a custom context, you can skip this parameter by NULL.
stream_context_create()'s documentation explains the rest
$opts = array(
'socket' => array(
'bindto' => '123.123.123.123:0', // 0 for automatically determine port
)
);
final code:
$opts = array(
'socket' => array(
'bindto' => '123.123.123.123:0', // 0 for automatically determine port
)
);
$stream = stream_context_create($ctxopts);
echo file_get_contents('http://www.website', false, $stream);

GET Request from PHP using file_get_contents with parameters

I want to send a GET request to an external site, but also want to send some parameters
for example i've to send a get request to example.com
i want to execute www.example.com/send.php?uid=1&pwd=2&msg=3&phone=3&provider=xyz
My code is :
$getdata = http_build_query(
array(
'uid' => '1',
'pwd' => '2',
'msg'=>'3',
'phone'=>'9999',
'provider'=>'xyz'
)
);
$opts = array('http' =>
array(
'method' => 'GET',
'content' => $getdata
)
);
$context = stream_context_create($opts);
$result = file_get_contents('http://example.com/send.php', false, $context);
I get a server error .
The content option is used with POST and PUT requests. For GET you can just append it as a query string:
file_get_contents('http://example.com/send.php?'.$getdata, false, $context);
Furthermore, the method defaults to GET so you don't even need to set options, nor create a stream context. So, for this particular situation, you could simply call file_get_contents with the first parameter if you wish.

How to receive values which are sent by file_get_contents() function?

I sent values through file_get_contents.
My question is i am unable receive(print) GET method values in work.php.
I am using stream_context_create() this will create a resource id.
page name sendvalues.php
// Create a stream
$opts = array(
'http'=>array(
'method'=>"GET",
'phone' => "9848509317",
'msg' => "hi naveen"
)
);
echo $context = stream_context_create($opts);
$file = file_get_contents('http://www.aakrutisolutions.com/projects/testingsite/smstest/sms_http_curl/work.php', false, $context);
echo $file;
page name work.php
echo "";
print_r($_GET); /// i am unable to get my query string values
echo "";
Just append your parameters url encoded to your url:
$file = file_get_contents('http://www.aakrutisolutions.com/projects/testingsite/smstest/sms_http_curl/work.php?phone=123&msg=hi%20naveen');
The context options you used... are context options. Here is specified which you can user for http: http://www.php.net/manual/de/context.http.php
It's not to be transmitted if you put random stuff in there.
Your array is incorrect. Look at the examples at http://php.net/manual/en/function.file-get-contents.php.
You cannot simply add POST arguments to the context array.
The correct context array for a POST request would look like this:
$opts = array(
'http' => array(
'method' => 'POST',
'content' => http_build_query(array(
'phone' => 9848509317,
'msg' => 'hi naveen'
))
)
);
Or simply use GET (as you expect in your other script), so put the arguments in the URL (build the query string with http_build_query()).

Categories