retrieve file information from url using php - php

i am trying to retrieve information of file from the url containing the file. but how can i get the information of file before downloading it to my server.
i need file information like file size,file type etc
i had found the code to validate and download file but how to get information from it before downloading file actually to server
<?php
function is_url_exist($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if($code == 200)
{
$status = "true";
}
curl_close($ch);
if ( $status == true)
{
$name = "abc.png";
if (file_put_contents("uploads/$name", file_get_contents($url)))
echo "file uploaded";
else
echo "error check upload link";
}
}
$url = "http://theonlytutorials.com/wp-content/uploads/2015/06/blog-logo1.png";
echo is_url_exist($url);
?>

you can get all information of remote file by get_headers function. Try following code to find out type, content length etc.
$url = "http://theonlytutorials.com/wp-content/uploads/2015/06/blog-logo1.png";
$headers = get_headers($url,1);
print_r($headers);
Know more about get_headers click http://php.net/manual/en/function.get-headers.php

Related

Check header response before download in single request with CURL

Is it possible to check the response headers (200=OK) and download a file in a single CURL request?
Here is my code. The problem with this is that it makes 2 requests, and hence the second request can be different and the saved file will be overwritten. This is a problem with rate limited API. I searched here on Stackoverflow but most solutions still make 2 requests.
// Check response first, we don't want to download the response error to the file
$urlCheck = checkRemoteFile($to_download);
if ($urlCheck) {
// Response is 200, continue
} else {
// Do not overwrite existing file
echo 'Download failed, response code header is not 200';
exit();
}
// File Handling
$new_file = fopen($downloaded, "w") or die("cannot open" . $downloaded);
// Setting the curl operations
$cd = curl_init();
curl_setopt($cd, CURLOPT_URL, $to_download);
curl_setopt($cd, CURLOPT_FILE, $new_file);
curl_setopt($cd, CURLOPT_TIMEOUT, 30); // timeout is 30 seconds, to download the large files you may need to increase the timeout limit.
// Running curl to download file
curl_exec($cd);
if (curl_errno($cd)) {
echo "the cURL error is : " . curl_error($cd);
} else {
$status = curl_getinfo($cd);
echo $status["http_code"] == 200 ? "File Downloaded" : "The error code is : " . $status["http_code"] ;
// the http status 200 means everything is going well. the error codes can be 401, 403 or 404.
}
// close and finalize the operations.
curl_close($cd);
fclose($new_file);
# FUNCTIONS
function checkRemoteFile($url) {
$curl = curl_init($url);
//don't fetch the actual page, you only want to check the connection is ok
curl_setopt($curl, CURLOPT_NOBODY, true);
//do request
$result = curl_exec($curl);
$ret = false;
//if request did not fail
if ($result !== false) {
//if request was ok, check response code
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($statusCode == 200) {
$ret = true;
}
}
curl_close($curl);
return $ret;
}

Check if page exist or 404 using php

Hi I have created a script using php to verify whether the page exist or its a 404 not found means invalid url the problem which I am facing at moment is weather the link exist or not in both case it is showing that the url is valid I am not sure if I am using a wrong approach or am I missing something below is the code which I am using
$file_headers = #get_headers('https://instagram.com/p/xyz');
echo "<pre>";
print_r($file_headers);
echo "</pre>";
if(!$file_headers || $file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = 0;
$error = '<div class="message">Provided url does not exists.</div>';
} else {
$error = '';
$exists = 1;
}
echo $exists;
I also tried to achieved this with curl but the problem is that with curl I am getting null response clean blank page nothing less nothing more below is how I am using with curl
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($handle);
$httpCode = curl_getinfo($handle, CURLINFO_HTTP_CODE);
print_r($httpCode);
curl_close($handle);

To read value from uploaded file and send it to url address

<? if(isset($_POST["submit"]))
{
$f_name = $_FILES["filetoupload"]["name"];
$f_tmp = $_FILES["filetoupload"]["tmp_name"];
$store = "uploads/".$f_name;
if(move_uploaded_file($f_tmp,$store))
echo "file uploaded successfully";
echo"<br>";
}
$line = fgets($f_open);
echo $line;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=";
$furl ="$url"."$line";
echo "$furl";
$ch = curl_init("$furl");
$fp = fopen("example4.txt","w");
curl_setopt($ch, CURLOPT_PROXY, '10.10.80.11:3128');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);
echo $json['results'][0]['address_components'][0]['types'][0];
echo $json['results'][0]['address_components'][0]['types'][1];
$data=json_decode($jsondata);
$address=$data->results[0]->address_components;
?>
bove mentioned program,
I'm trying to retrieve value line by line from uploaded file and concatenate the retrieving value with url,
But I got the error message..
Notice: Trying to get property of non-object in
C:\xampp\htdocs\phpprog\upload_file_add.php on line 50...
Where is my mistake with the description...
I guess you need to check that your $jsondata variable is valid before using json_decode. It's probably you're receiving null in $data so it's no longer an object when you try to access its properties.
Use var_dump($data) after json_decode($jsondata) to verify you're receiving what you expect.
you are giving us code that has variables that we don't know where they come from, like your $f_open and $json. You cannot use fgets() without opening the file with fopen().
$f_name = $_FILES["filetoupload"]["name"];
$f_tmp = $_FILES["filetoupload"]["tmp_name"];
$store = "uploads/".$f_name;
if(move_uploaded_file($f_tmp,$store)){
echo "file uploaded successfully";
echo"<br>";
}
$f_open = fopen($store,"r");
$line = fgets($f_open);
echo $line;
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=";
$furl ="$url"."$line";
echo "$furl";
reading a text file which contains reading_files_with_PHP
the above code displays
reading_files_with_PHP
http://maps.googleapis.com/maps/api/geocode/json?address=reading_files_with_PHP

Secured XML feed import

I am working on store products import from live XML feed.
Now I have one problem, with following code I imported several XML feeds, except this:
XML Live Feed
Code I used for all feeds is:
<?php
//dropshipper's feed URL
$myFeed = 'http://feedurl/feed.xml';
// specify the name of the file you want to save
$myFilename = 'some_feed.xml';
if ($myFeed != '') {
// Initialize the cURL session
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $myFeed);
//Create a new file
$fp = fopen($myFilename, 'w');
// Save to file
curl_setopt($ch, CURLOPT_FILE, $fp);
// Execute the cURL session
curl_exec ($ch);
//Close cURL session and file
curl_close ($ch);
fclose($fp);
echo "Some Feed Imported Successfully!";
}
?>
But mentoined feed CAN NOT BE READ from script, and I dont know how to create import. This feed can be opened in browser and everyone can see data, but it can not be imported on server through script.
Any help, please?
First, are you sure it is a good idea to post your username (tomicurc) and password to your XML-Feed?
And secondly, have you tried file_get_contents? It works for me and is an easy way to get remote data which then can be stored.
Edit:
Try something like
if ($myFeed != '') {
if($ch = curl_init()) {
if(curl_setopt($ch, CURLOPT_URL, $myFeed)) {
if($fp = fopen($myFilename, 'w')) {
if(curl_setopt($ch, CURLOPT_FILE, $fp)) {
if(curl_exec ($ch)) {
curl_close ($ch);
fclose($fp);
echo "close completed, finishing";
} else {
echo "curl_exec failed";
}
} else {
echo "curl_setopt CURLOPT_FILE failed";
}
} else {
echo "fopen failed";
}
} else {
echo "curl_setopt CURLOPT_URL failed";
}
} else {
echo "curl init failed";
}
}

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 :(

Categories