the function is for checking if an url is pointing to a valid image by checking the meta info in the head section of the given file.
the echo in the below code gives me the correct wrapper data but on my remote server it echoes "ArrayResource id #11" How this is possible?
local:PHP Version 5.3.4
remote server: PHP Version 5.2.9
function isImage($url)
{
$params = array('http' => array(
'method' => 'HEAD'
));
$ctx = stream_context_create($params);
$fp = #fopen($url, 'rb', false, $ctx);
if (!$fp)
return false; // Problem with url
$meta = stream_get_meta_data($fp);
if ($meta === false)
{
fclose($fp);
return false; // Problem reading data from url
}
$wrapper_data = $meta["wrapper_data"];
if(is_array($wrapper_data)){
foreach(array_keys($wrapper_data) as $hh){
echo substr($wrapper_data[$hh], 0, 19);//////////////ECHO////////////////////////
if (substr($wrapper_data[$hh], 0, 19) == "Content-Type: image") // strlen("Content-Type: image") == 19
{
fclose($fp);
return true;
}
}
}
fclose($fp);
return false;
}
EDIT: I adapted the function so it checks if 'Content-Type: image' is somewhere in the header of the file. this works cross server...
function isImage($url)
{
$params = array('http' => array(
'method' => 'HEAD'
));
$ctx = stream_context_create($params);
$fp = #fopen($url, 'rb', false, $ctx);
if (!$fp)
return false; // Problem with url
$meta = get_headers($url);
if ($meta === false)
{
fclose($fp);
return false; // Problem reading data from url
}
foreach ($meta as $key => $value) {
$pos = strpos($value, 'Content-Type: image');
if($pos!==false){
fclose($fp);
return true;
}
}
fclose($fp);
return false;
}
Refer to this. stream_get_meta_data can return values in several datatypes. On your remote server it is returning an array.
Related
This question already has answers here:
check if php file exists on server
(2 answers)
Closed 4 years ago.
how can I make sure that the file exists on the server and find out its size on the URL without first downloading the file
$url = 'http://site.zz/file.jpg';
file_exists($url); //always is false
filesize($url); //not working
Help eny one worked exemple pls
The function file_exists() only works on file that exists on the server locally.
Similarly; filesize() function returns the size of the file that exists on the server locally.
If you are trying to load the size of a file for a given url, you can try this approach:
function get_remote_file_info($url) {
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_NOBODY, TRUE);
$data = curl_exec($ch);
$fileSize = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
$httpResponseCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return [
'fileExists' => (int) $httpResponseCode == 200,
'fileSize' => (int) $fileSize
];
}
Usage:
$url = 'http://site.zz/file.jpg';
$result = get_remote_file_info($url);
var_dump($result);
Example output:
array(2) {
["fileExists"]=>
bool(true)
["fileSize"]=>
int(12345)
}
Without any libraries and file openning
$data = get_headers($url, true);
$size = isset($data['Content-Length'])?(int) $data['Content-Length']:0;
Open remote files:
function fsize($path) {
$fp = fopen($path,"r");
$inf = stream_get_meta_data($fp);
fclose($fp);
foreach($inf["wrapper_data"] as $v) {
if (stristr($v, "content-length")) {
$v = explode(":", $v);
return trim($v[1]);
}
}
return 0;
}
Usage:
$file = "https://zzz.org/file.jpg";
$inbytes = fsize($filesize);
Use sockets:
function getRemoteFileSize($url){
$parse = parse_url($url);
$host = $parse['host'];
$fp = #fsockopen ($host, 80, $errno, $errstr, 20);
if(!$fp){
$ret = 0;
}else{
$host = $parse['host'];
fputs($fp, "HEAD ".$url." HTTP/1.1\r\n");
fputs($fp, "HOST: ".$host."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
$headers = "";
while (!feof($fp)){
$headers .= fgets ($fp, 128);
}
fclose ($fp);
$headers = strtolower($headers);
$array = preg_split("|[\s,]+|",$headers);
$key = array_search('content-length:',$array);
$ret = $array[$key+1];
}
if($array[1]==200) return $ret;
else return -1*$array[1];
}
You can't access to filesize of a distant file.
You have to check with your local filepath.
I try to submit a form to remote server: http://openconvert.clarin.inl.nl/openconvert/tagger#text, as you can see the required fileds are input and format, and the action url is http://openconvert.clarin.inl.nl/openconvert/text/, so I try the following in php:
<?php
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;
}
$remoteurl="http://openconvert.clarin.inl.nl/openconvert/text";
$rawdata=array(
'input'=>'test',
'format'=>'text');
$data=http_build_query($rawdata, '', '&'); //flags_, myvar_
var_dump($data);
echo "<br />";
echo do_post_request($remoteurl,$data,'Content-Type: text/html');
?>
I don't know why the server can't find my data?
The output is:
string(26) "input=test&format=text"
<br /><?xml version="1.0" encoding="UTF-8"?>
<error>Insufficient parameters. Required parameters: input, format</error>
There might be other problems, but the & value in http_build_query is definitely wrong. You're not embedding your urlencoded data into an html document, so you should not html-escape the ampersand. Replacing that line with:
http_build_query($rawdata, '', '&');
should be better, but it might not be 100% of your solution.
P.S.: Don't use #, ever. You are suppressing real errors that you should see.
I'm trying to validate Facebook photos(public) image URL using fopen() and getimagesize() on cloud9 vm, fopen() function returns a null value and getimagesize() throws an error
"failed to open stream: HTTP request failed! HTTP/1.0 403 Forbidden"
, both functions works perfectly for other image URL's.
I've tried to use both functions to validate Facebook image URLs on my localhost wamp server and they seems to be working fine. allow_url_fopen is On in php.ini on c9 server, is it possible that c9 vm's are blocked by Facebook or am i doing something wrong?
Here's my Validation Function
function validateImage($url)
{
$params = array('http' => array(
'method' => 'HEAD'
));
$ctx = stream_context_create($params);
$fp = #fopen($url, 'rb', false, $ctx);
if (!$fp)
return false; // Problem with url
$meta = stream_get_meta_data($fp);
if ($meta === false)
{
fclose($fp);
return false; // Problem reading data from url
}
$wrapper_data = $meta["wrapper_data"];
if(is_array($wrapper_data)){
foreach(array_keys($wrapper_data) as $hh){
if (substr($wrapper_data[$hh], 0, 19) == "Content-Type: image") // strlen("Content-Type: image") == 19
{
fclose($fp);
return true;
}
}
}
fclose($fp);
return false;
}
I tested with a valid image url, but fopen get instead a reference to an image (in my case id #5), not the content. So my advice is to use:
$img = file_get_contents($url);
Now what can you do:
$img = file_get_contents($url);
if(strlen($img) !==0) {
echo "good";
if(substr($img,0,3) === "\xFF\xD8\xFF"){
echo "It's a jpg !\n";
}
else "other type\n";
}
Adding is_file($filename) condition before getimagesize($filename) worked for me
if(is_file($filename) && getimagesize($filename)) {
// your code here
}
Use this code, it works fine
try {
#ini_set('user_agent', 'Mozilla/5.0');
} catch (Exception $exc) {
echo $exc->getTraceAsString();
}
I have a small problem. When I fetch a page via file_get_contents, the unknown symbol is concantenated to output which destroys the XML structure.
How can I solve the problem?
code:
file_get_contents('https://emea2cps.adobeconnect.com/api/xml?action=login&login=EMAIL&password=PASSWORD');
$cookies = array();
foreach ($http_response_header as $hdr) {
if (preg_match('/^Set-Cookie:\s*([^;]+)/', $hdr, $matches)) {
parse_str($matches[1], $tmp);
$cookies += $tmp;
}
}
//print_r($cookies);
//echo "//////////////////";
$cook=$cookies['BREEZESESSION'];
echo $cook;
$opts = array(
'http'=>array(
'method'=>'GET',
'header'=>'Cookie: BREEZESESSION='.$cook.'\r\n',
)
);
$context = stream_context_create($opts);
echo "////////////////////////";
// Open the file using the HTTP headers set above
//$file = file_get_contents('http://www.example.com/', false, $context);
$file1 = file_get_contents('https://meet77842937.adobeconnect.com/api/xml?action=report-my-meetings', false, $context);
print_r($file1);
$xml = new SimpleXMLElement($file1);
output:
em2breezgwbhxopvpvknsux7////////////////////////sample1aksamaimeet77842937.adobeconnect.com/sample1/2014-02-28T06:15:00.000-08:002014-02-28T07:15:00.000-08:00true01:00:00.000sample2meet77842937.adobeconnect.com/sample2/2014-02-28T06:15:00.000-08:002014-02-28T07:15:00.000-08:00true01:00:00.000lastTtmeet77842937.adobeconnect.com/lastone/2014-02-28T15:30:00.000-08:002014-02-28T18:00:00.000-08:00false02:30:00.000�
Look at the last symbol. It must not exist ideally.
With regards
I am using the example function given in this post:
<?php
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 also tried a similar approach using file_get_contents(), like this:
$options = array(
'http'=>array(
'method'=>"POST",
'header'=>
"Accept-language: en\r\n".
"Content-type: application/x-www-form-urlencoded\r\n",
'content'=>http_build_query(
array(
'arg1'=>'arg_data_1',
'oper'=>'get_data',
'arg2'=>'arg_data_2',
'id_number'=>'7862'
),'','&'
)
));
$context = stream_context_create($options);
$refno = file_get_contents('/path/to/script/script.php',false,$context);
var_dump($refno);
With both these scripts, the response from the server script is the same, and it is the TEXT of the script.php. The code of the server script is never begin executed, and the text content (the PHP code) of the script is being returned to the original script.
A little strange that it doesn't return all the text, but just certain pieces... I tried making a test script (test.php) that just contains:
<?php
echo '{"a":1,"b":2,"c":3,"d":4,"e":5}';
?>
but that doesn't return anything from the POST request, so I didn't include that. The script.php is a must longer script that does a lot of logic and MySQL queries then returns a JSON object.
The desired output will be to have the PHP code execute and return a JSON object (the way it works with ajax).
What am I doing wrong?
You are trying access script localy.
You must call it like any other external script like
$refno = file_get_contents('http://yourhost/path/to/script/script.php',false,$context);