convert file_put_contents to curl - php

I have a function to create cache data xml file on my server.
I've used file_get_contents and file_put_contents, but now my hosting provider is restricting usage of them. The single way to use same function is to convert it to CURL. Can anyone give some ideas?
function checkXmlCache($xmlQuery) {
$fibulabasexml="http://any url that give xml data/"; $cachedir="/tmp/"; $ageInSeconds = 36000;
$xmlQuery=str_replace(array("'",'"'),"",$xmlQuery);
$xmlQuery2=$xmlQuery;
$long=array("stars=","TURKEY","bestprice=","country=", "location=","hotelcode=","prices=yes","tara=","simple=yes","rand()","sort=","limit=","price ","hotelname"," desc","desc");
$short=array("ST-","TR","B-","C-", "L-", "H-", "PY-", "T-", "-S-", "-R-", "S-", "LT-", "PP-","HN","-D","-D");
$xmlQuery2=str_replace($long,$short,$xmlQuery2);
$xmlQuery2=str_replace(array("xmlhotels.php","xmllocations.php"),array("XH-","XL-"),$xmlQuery2);
$xmlQuery2=str_replace(array("&","?"),array(""),$xmlQuery2);
$xmlQuery2.="_.XML";
$xmlQuery2=strip_tags($xmlQuery2);
if(!file_exists($cachedir.$xmlQuery2) || (filemtime($cachedir.$xmlQuery2) + $ageInSeconds < (time() )) ) {
$contents = file_get_contents($fibulabasexml.str_replace(" ","%20",$xmlQuery));
if(strlen($contents)>200 ) { file_put_contents($cachedir.$xmlQuery2, $contents); }
}
return($cachedir.$xmlQuery2);
Thanks for helping!

Create a simple curl function that will return the response from the request and use it in place of file_get_contents. This is not tested but it should give you the general idea perhaps.
function checkXmlCache( $xml ) {
$url="http://any url that give xml data/";
$dir="/tmp/";
$age = 36000;
$xml=str_replace( array("'",'"'), "", $xml );
$query=$xml;
$long=array("stars=","TURKEY","bestprice=","country=", "location=","hotelcode=","prices=yes","tara=","simple=yes","rand()","sort=","limit=","price ","hotelname"," desc","desc");
$short=array("ST-","TR","B-","C-","L-","H-","PY-","T-","-S-","-R-","S-","LT-","PP-","HN","-D","-D");
$query=str_replace($long,$short,$query);
$query=str_replace(array("xmlhotels.php","xmllocations.php"),array("XH-","XL-"),$query);
$query=str_replace(array("&","?"),array(""),$query);
$query.="_.XML";
$query=strip_tags( $query );
if( !file_exists( $dir.$query ) || ( filemtime( $dir.$query ) + $age < ( time() ) ) ) {
$targeturl=$url . str_replace( " ", "%20", $xml );
/* call curl function rather than file_get_contents */
$contents = curl( $targeturl );
if( strlen( $contents ) > 200 ) { file_put_contents( $dir . $query, $contents ); }
}
return( $dir.$query );
}
function curl( $url ){
$ch=curl_init( $url );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER,true );
curl_setopt( $ch, CURLOPT_USERAGENT,$_SERVER['HTTP_USER_AGENT'] );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
$res=curl_exec( $ch );
curl_close( $ch );
return $res;
}

Related

How to fetch all issues from redmine application using curl PHP

here i am trying to fetch all issues from Redmine by using curl php below is the code which i used.
my CURL.php:
flie class file in redmine/redmine_curl.php
<?php # Redmine Api
class class_redmine{
function get_upload_token($filecontent){
global $redmine_url , $redmine_key;
$upload_url = $redmine_url.'uploads.json?key='.$redmine_key;
$request['type'] = 'post';
$request['content_type'] = 'application/octet-stream';
//$filecontent = file_get_contents('test.php');
return $token = $this->curl_redmine($upload_url,$request,$filecontent);
//$token->upload->token;
}
#Issue
function create_issue($post_data){
global $redmine_url , $redmine_key;
$issue_url = $redmine_url.'issues.json?key='.$redmine_key;
$request['type'] = 'post';
$request['content_type'] = 'application/json';
return $this->curl_redmine($issue_url,$request,$post_data);
}
function get_issue($issue_id='',$project_id=''){
global $redmine_url , $redmine_key;
if($project_id!=''){
$issue_url = $redmine_url.'issues.json?key='.$redmine_key.'&project_id='.$project_id;
}else{ $issue_url = ($issue_id=='')?$redmine_url.'issues.json?key='.$redmine_key : $redmine_url.'issues/'.$issue_id.'.json?key='.$redmine_key;
}
return $this->curl_redmine($issue_url,'','');
}
#Projects
function get_projects($project_id=''){
global $redmine_url , $redmine_key;
$proj_url = ($project_id=='')?$redmine_url.'projects.json?key='.$redmine_key : $redmine_url.'projects/'.$project_id.'.json?key='.$redmine_key;
return $this->curl_redmine($proj_url,'','');
}
#Curl
function curl_redmine($redmine_url,$request='',$post_data=''){
if(!isset($request['type'])){ $request['type']=null; }
if(!isset($request['content_type'])){ $request['content_type']=null; }
//Create a curl object
$ch = curl_init();
//Set the useragent
$agent = $_SERVER["HTTP_USER_AGENT"];
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
//Set the URL
curl_setopt($ch, CURLOPT_URL, $redmine_url );
if($request['type'] == 'post'){
//This is a POST query
curl_setopt($ch, CURLOPT_POST,1);
// curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
//Set the post data
curl_setopt($ch, CURLOPT_POSTFIELDS,$post_data);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: '.$request['content_type'],
'Content-Length: ' . strlen($post_data))
);
}
//We want the content after the query
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
//Follow Location redirects
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
/*
Set the cookie storing files
Cookie files are necessary since we are logging and session data needs to be saved
*/
//curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
//curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
//Execute the action to login
$postResult = curl_exec($ch);
//if($postResult == false){ return $info = curl_getinfo($ch);}
$response = json_decode($postResult);
//echo '<pre>'; print_r($response); echo '</pre>';
return $response;
}
}//class_redmine
?>
here is my example.php
<?php
function get_redmine($methodName='',$data=''){
global $redmine_url , $redmine_key;
$redmine_url = 'http://192.168.12.231:80/';
$redmine_key = 'API KEY';
include_once('curlcall.php');
$obj_redmine = new class_redmine();
#check Auth
$res = $obj_redmine->get_projects();
if(!isset($res->projects) || (isset($res->total_count) && ($res->total_count)==0)){ return -1; }
switch($methodName){
case 'check_status' : return $login_integrate;
##check redmine integration in vision break;
##Project
case 'projectAll' : return $obj_redmine->get_projects(); #used
break;
case 'projectById' : return $obj_redmine->get_projects($data['project_id']);
break;
##Issues
case 'issueAll' : return $obj_redmine->get_issue();
break;
case 'issueByProjectId' : return $obj_redmine->get_issue('',$data['project_id']);
break;
case 'uploadFileToIssue' : return $obj_redmine->get_upload_token($data);
break;
default: return 0;
}
}
#get all issue
$res = get_redmine('issueAll');
echo '<pre>';print_r($res);
?>
This code is giving only 25 records.at the end of my output it is saying like
total:201
offset:0
limit:25
I can't understand how to get all issues please help anybody, i am new for php.
the answer is all in the API docs, if you'd just bother to read it. use the limit parameter to get more results, and the offset parameter to load more
/issues.json?offset=0&limit=100 would fetch the first 100 issues
/issues.json?offset=100&limit=100 would fetch the next 100 issues, and so on.
... but the first thing you should do is get your code formatted, because that unformatted thing is very annoying to read. then get rid of this line 'Content-Length: ' . strlen ( $post_data ) because curl will add that header automatically if you don't, and curl won't make any typos, nor will it calculate the length incorrectly, unlike us the progammers (curl has automated tests ran on every commit to make sure content-length is correct, i bet that's not part of your test suite), then get rid of this
if (! isset ( $request ['content_type'] )) {
$request ['content_type'] = null;
}
because it should never be null. for future reference, if you literally have no idea what it's supposed to be, set it to application/octet-stream, but even that is wrong in this case, because the API docs says the only supported POST encodings are application/json and application/xml, so the correct thing to do here would be:
if (isset ( $request ['content_type'] ) && $request ['content_type'] !== 'application/json' && $request ['content_type'] !== 'application/xml') {
throw new \InvalidArgumentException ( 'invalid content-type specified. supported types are "application/json" and "application/xml"' );
}
if($request ['type'] === 'post' && !isset($request ['content_type'])){
throw new \LogicException('no content-type was specified for this POST request, which is required. supported types are "application/json" and "application/xml"');
}
as for fetching all the issues, make a request first to see how many issues there are, then make a second request with limit=number_of_issues, like this
if (! $issue_id) {
// first we check how many issues there are (OPTIMIZEME: there is probably a more efficient way to do this, for example limit=0 ?)
$issues_url .= '&limit=1';
$number_of_issues = $this->curl_redmine ( $issue_url, '', '' ) ['total_count'];
$issue_url = substr ( $issues_url, 0, - 1 ) . $number_of_issues;
}
putting it all together, and you get this
<?php
// Redmine Api
class class_redmine {
function get_upload_token($filecontent) {
global $redmine_url, $redmine_key;
$upload_url = $redmine_url . 'uploads.json?key=' . $redmine_key;
$request ['type'] = 'post';
$request ['content_type'] = 'application/octet-stream';
// $filecontent = file_get_contents('test.php');
return $token = $this->curl_redmine ( $upload_url, $request, $filecontent );
// $token->upload->token;
}
// Issue
function create_issue($post_data) {
global $redmine_url, $redmine_key;
$issue_url = $redmine_url . 'issues.json?key=' . $redmine_key;
$request ['type'] = 'post';
$request ['content_type'] = 'application/json';
return $this->curl_redmine ( $issue_url, $request, $post_data );
}
function get_issue($issue_id = '', $project_id = '') {
global $redmine_url, $redmine_key;
if ($project_id != '') {
$issue_url = $redmine_url . 'issues.json?key=' . $redmine_key . '&project_id=' . $project_id;
} else {
$issue_url = ($issue_id == '') ? $redmine_url . 'issues.json?key=' . $redmine_key : $redmine_url . 'issues/' . $issue_id . '.json?key=' . $redmine_key;
}
if (! $issue_id) {
// first we check how many issues there are (OPTIMIZEME: there is probably a more efficient way to do this, for example limit=0 ?)
$issues_url .= '&limit=1';
$number_of_issues = $this->curl_redmine ( $issue_url, '', '' ) ['total_count'];
$issue_url = substr ( $issues_url, 0, - 1 ) . $number_of_issues;
}
return $this->curl_redmine ( $issue_url, '', '' );
}
// Projects
function get_projects($project_id = '') {
global $redmine_url, $redmine_key;
$proj_url = ($project_id == '') ? $redmine_url . 'projects.json?key=' . $redmine_key : $redmine_url . 'projects/' . $project_id . '.json?key=' . $redmine_key;
return $this->curl_redmine ( $proj_url, '', '' );
}
// Curl
function curl_redmine($redmine_url, $request = '', $post_data = '') {
if (! isset ( $request ['type'] )) {
$request ['type'] = null;
}
if (isset ( $request ['content_type'] ) && $request ['content_type'] !== 'application/json' && $request ['content_type'] !== 'application/xml') {
throw new \InvalidArgumentException ( 'invalid content-type specified. supported types are "application/json" and "application/xml"' );
}
if ($request ['type'] === 'post' && ! isset ( $request ['content_type'] )) {
throw new \LogicException ( 'no content-type was specified for this POST request, which is required. supported types are "application/json" and "application/xml"' );
}
// Create a curl object
$ch = curl_init ();
// Set the useragent
$agent = $_SERVER ["HTTP_USER_AGENT"];
curl_setopt ( $ch, CURLOPT_USERAGENT, $agent );
// Set the URL
curl_setopt ( $ch, CURLOPT_URL, $redmine_url );
if ($request ['type'] == 'post') {
// This is a POST query
curl_setopt ( $ch, CURLOPT_POST, 1 );
// curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
// Set the post data
curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_data );
curl_setopt ( $ch, CURLOPT_HTTPHEADER, array (
'Content-Type: ' . $request ['content_type']
) );
}
// We want the content after the query
curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
// Follow Location redirects
curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, 1 );
/*
* Set the cookie storing files
* Cookie files are necessary since we are logging and session data needs to be saved
*/
// curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie.txt');
// curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookie.txt');
// Execute the action to login
$postResult = curl_exec ( $ch );
// if($postResult == false){ return $info = curl_getinfo($ch);}
$response = json_decode ( $postResult );
// echo '<pre>'; print_r($response); echo '</pre>';
return $response;
}
}//class_redmine
(which is completely untested on my part, by the way.)
another issue you should fix is that your curl code is executed completely without error detection. for example, curl_setopt returns bool(false) if there was a problem setting your option, and curl_exec() returns bool(false) if there was a problem with during the transfer, add error detection for that. these functions should make that rather easy:
function ecurl_setopt ( /*resource*/$ch , int $option , /*mixed*/ $value ):bool{
$ret=curl_setopt($ch,$option,$value);
if($ret!==true){
//option should be obvious by stack trace
throw new RuntimeException ( 'curl_setopt() failed. curl_errno: ' . return_var_dump ( curl_errno ($ch) ).'. curl_error: '.curl_error($ch) );
}
return true;
}
function ecurl_exec ( /*resource*/$ch):bool{
$ret=curl_exec($ch);
if($ret===false){
throw new RuntimeException ( 'curl_exec() failed. curl_errno: ' . return_var_dump ( curl_errno ($ch) ).'. curl_error: '.curl_error($ch) );
}
return $ret;
}
function return_var_dump(/*...*/){
$args = func_get_args ();
ob_start ();
call_user_func_array ( 'var_dump', $args );
return ob_get_clean ();
}
and to be sure you're not leaking any memory, you can wrap it all around a try{...curl...}finally{curl_close($ch);}, making sure curl_close would always be called, regardless of which curl function throws an exception. (this prevents memory leaks)

PHP Script Not Downloading A Zipped Product Feed From URL - Download works fine when visited on browser

I have a simple bit of PHP code which copies a zip file from a remote url to the server, and then extracts it into another folder.
function extract_remote_zip($new_file_loc, $tmp_file_loc, $zip_url) {
echo 'Copying Zip to local....<br>';
//copy file to local
if (!copy($zip_url, $tmp_file_loc)) {
echo "failed to copy zip from".$zip_url."...";
}
//unzip
$zip = new ZipArchive;
$res = $zip->open($tmp_file_loc);
if ($res === TRUE) {
echo 'Extracting Zip....<br>';
if(! $zip->extractTo($new_file_loc)){
echo 'Couldnt extract!<br>';
}
$zip->close();
echo 'Deleting local copy....<br>';
unlink($tmp_file_loc);
return 1;
} else {
echo 'Failed to open tmp zip!<br>';
return 0;
}
}
It works perfectly with one URL from Awin and downloads and extracts the correct 600kb zip, but with another from Webgains it just downloads a Zip file with size 0 bytes. I'm guessing the download is getting corrupted somewhere?
When I visit the URL on my browser it downloads the zip perfectly (the size is about 3mb). I just can't get it to download with PHP.
Please help!
Since you didn't provide the problem URL, I can't say for sure, but you are likely encountering an issue with the method copy uses to read the file. Doing a direct curl call should resolve this.
Try the below:
function file_get_contents_curl( $url ) {
$ch = curl_init();
curl_setopt( $ch, CURLOPT_AUTOREFERER, TRUE );
curl_setopt( $ch, CURLOPT_HEADER, 0 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, TRUE );
$data = curl_exec( $ch );
if ( curl_errno( $ch ) <> FALSE ) {
echo "ERROR at line " . __LINE__ . " in file_get_contents_curl: error number: " . curl_errno( $ch ) . ' error : ' . curl_error( $ch ) . " url: $url";
return FALSE;
}
curl_close( $ch );
return $data;
}
function extract_remote_zip($new_file_loc, $tmp_file_loc, $zip_url) {
echo 'Copying Zip to local....<br>';
// read the zip
if ( $zip_str = file_get_contents_curl( $zip_url ) ) {
// write the zip to local
if ( !file_put_contents( $tmp_file_loc, $zip_str ) ) {
echo "failed to write the zip to: " . $zip_url;
return FALSE;
}
} else {
echo "failed to read the zip from: " . $zip_url;
return FALSE;
}
//unzip
$zip = new ZipArchive;
$res = $zip->open($tmp_file_loc);
if ($res === TRUE) {
echo 'Extracting Zip....<br>';
if(! $zip->extractTo($new_file_loc)){
echo 'Couldnt extract!<br>';
}
$zip->close();
echo 'Deleting local copy....<br>';
unlink($tmp_file_loc);
return 1;
} else {
echo 'Failed to open tmp zip!<br>';
return 0;
}
}

PHP - Iterate over google results

I have a simple CURL script that searches Google for "Batman", then saves the result in a file...
Can someone tell me a good way of iterating through the file to find each of the search results title and URL, please?
This is my code:
function get_remote_file_to_cache()
{
$the_site = "https://www.google.se/webhp?sourceid=chrome-instant&rlz=1C5CHFA_enSE555SE556&ion=1&espv=2&ie=UTF-8#newwindow=1&q=batman";
$curl = curl_init ();
$fp = fopen ( "temp_file.txt", "w" );
curl_setopt ( $curl, CURLOPT_URL, $the_site );
curl_setopt ( $curl, CURLOPT_FILE, $fp );
curl_setopt ( $curl, CURLOPT_RETURNTRANSFER, TRUE );
curl_exec ( $curl );
$httpCode = curl_getinfo ( $curl, CURLINFO_HTTP_CODE );
if ($httpCode == 404)
{
touch ( 'cache/404_err.txt' );
} /*
* else { touch('cache/'.rand(0, 99999).'--all_good.txt'); }
*/
else
{
$contents = curl_exec ( $curl );
fwrite ( $fp, $contents );
}
curl_close ( $curl );
fclose ( $fp );
}
echo rand(1, 425).get_remote_file_to_cache();
You can search trough the HTML using DOMDocument and DOMXPath
// Temp:
$sPageHTML = '<html><head></head><body><div class="test">Text here</div></body></html>';
$oDomDocument = new DOMDocument ( );
$oDomDocument->loadHTML ( $sPageHTML );
// Now, search the DOM structure for all divs with class "test".
$oXPath = new DOMXPath ( $oDomDocument );
$results = $oXPath->query ( '//div[#class="test"]' );
// Loop through the results.
foreach ( $results as $result )
{
echo 'Innertext: ' . $result->nodeValue;
}
Good luck
If you are still searching, you can find an open source php google scraper here:
http://scraping.compunect.com/?scrape-google-search (scroll to bottom for the code)
You can just copy the DOM parsing routines from it, they work very well.

Twitter OAUTh and PHP

I'm trying to obtain a request token from Twitter API in order to log in user with his twitter account and I keep getting a 401 response with "Failed to validate oauth signature and token". I'm doing this over PHP. I looked for similar questions but apparently I'm the only one crazy enough to do it from scratch without a library.
In their API documentation they talk about "percent encode" the values sent in the authorization header, I'm doing so with the urlencode() function, not sure if it's right.
To calculate the signature I use hash_hmac( 'SHA1', $signParameters, $hashKey), also not sure if it is the right one to use.
This is the request that gets generated, through cURL:
POST /oauth/request_token HTTP/1.1
Host: api.twitter.com
Accept: */*
Authorization: OAuth oauth_callback="http%3A%2F%2Fwww.soytumascota.com%2Ftwitter%2Fuser.php", oauth_consumer_key="MY_APP_KEY", oauth_nonce="0dde25902bde5f3b280f58ea642047cf", oauth_signature_method="HMAC_SHA1", oauth_timestamp="1334697987", oauth_version="1.0", oauth_signature="8313277875f20cd8a8631966a2ba273a5d13aeda"
Content-Length: 0
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue
I would really appreciate any help you can give, thank you.
EDIT: Here's the code i've written so far.
<?php
DEFINE( 'CONSUMER_KEY', 'MY_APP_KEY' );
DEFINE( 'CONSUMER_SECRET', 'MY_APP_SECRET' );
$url = 'https://api.twitter.com/oauth/request_token';
//setting OAuth parameters
$Oauth = Array();
$Oauth['oauth_callback'] = 'http://www.soytumascota.com/twitter/user.php';
$Oauth['oauth_consumer_key'] = CONSUMER_KEY;
$Oauth['oauth_nonce'] = md5( $Oauth['oauth_callback'] . CONSUMER_KEY . time() );
$Oauth['oauth_signature_method'] = 'HMAC_SHA1';
$Oauth['oauth_timestamp'] = (string) time();
$Oauth['oauth_version'] = '1.0';
//signature and authorization header are calculated inside functions
$Oauth['oauth_signature'] = calculateSignature( 'POST', $url, $Oauth );
$authorization = getAuthorizationHeader( $Oauth );
ksort( $Oauth );
//setting and sending request using cURL
$curl_session = curl_init( $url );
curl_setopt( $curl_session, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $curl_session, CURLOPT_POST, true );
curl_setopt( $curl_session, CURLINFO_HEADER_OUT, true );
curl_setopt( $curl_session, CURLOPT_HTTPHEADER, Array( 'Authorization: ' . $authorization ) );
$result = curl_exec( $curl_session );
function getAuthorizationHeader( $parameters )
{
$authorization = 'OAuth ';
$j = count( $parameters );
foreach( $parameters as $key => $val )
{
$authorization .= $key . '="' . urlencode( $val ) . '"';
if( $j-- > 1 )
{
$authorization .= ', ';
}
}
return $authorization;
}
function calculateSignature( $method, $url, $parameters, $accessToken = '' )
{
foreach( $parameters as $key => $val )
{
$foo = urlencode( $key );
unset( $parameters[$key] );
$parameters[$foo] = urlencode( $val );
}
ksort( $parameters );
$signBase = '';
$j = count( $parameters );
foreach( $parameters as $key => $val )
{
$signBase .= "{$key}={$val}";
if( $j-- > 1 )
{
$signBase .= '&';
}
}
$signBase = strtoupper( $method ) . '&' . urlencode( $url ) . '&' . urlencode( $signBase );
$signKey = urlencode( CONSUMER_SECRET ) . '&' . urlencode( $accessToken );
$signature = hash_hmac( 'SHA1', $signParameters, $hashKey);
return $signature;
}
First, 'oauth_signature_method' must be 'HMAC-SHA1' (or nothing will work).
About "percent encode", they say in their API documentation https://dev.twitter.com/docs/auth/percent-encoding-parameters they require strings to be encoded according to RFC 3986 so you should use rawurlencode instead of urlencode.
To calculate the signature they say here https://dev.twitter.com/docs/auth/creating-signature that you have to use HMAC-SHA1 hashing algorithm and convert the raw output to base64, something like:
$signature = base64_encode(hash_hmac( 'SHA1', $signBase, $signKey, true));
And finally you may need to add
//no content
curl_setopt( $curl_session, CURLOPT_POSTFIELDS, '');
//no verify certs
curl_setopt( $curl_session, CURLOPT_SSL_VERIFYPEER, FALSE);
to the curl options to get the request working.

How does one check for remote file size and date?

Is there a way in php to check remote files size and date/time on the server ?
try for date
function GetRemoteLastModified( $uri )
{
// default
$unixtime = 0;
$fp = fopen( $uri, "r" );
if( !$fp ) {return;}
$MetaData = stream_get_meta_data( $fp );
foreach( $MetaData['wrapper_data'] as $response )
{
// case: redirection
if( substr( strtolower($response), 0, 10 ) == 'location: ' )
{
$newUri = substr( $response, 10 );
fclose( $fp );
return GetRemoteLastModified( $newUri );
}
// case: last-modified
elseif( substr( strtolower($response), 0, 15 ) == 'last-modified: ' )
{
$unixtime = strtotime( substr($response, 15) );
break;
}
}
fclose( $fp );
return $unixtime;
}
and for file size
function remotefilesize($remoteFile){
$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;
}
Please check for explaination. I have got above functions from these links.
http://php.net/manual/en/function.filemtime.php
http://php.net/manual/en/function.filesize.php
You could use filemtime() and filesize().
Be aware of this BTW:
As of PHP 5.0.0, this function can also be used with some URL wrappers.
Refer to List of Supported Protocols/Wrappers for a listing of which wrappers
support stat() family of functionality.

Categories