Save Remote Image to local server Codeigniter - php

I am trying to Save Remote Image to local server using Phils Curl srcipt in Codeigniter.
To ensure directory is there with proper permissions I have:
if (!is_dir('images')){
mkdir('./images', 0777, true);
}
Here is what I tried.. ( Source )
$this->load->library('curl');
$this->load->helper('file');
$remoteURL = 'http://fermeteogranada.com/camara.jpg';
$img = $this->curl->simple_get($remoteURL);
$localURL = './images/main.jpg';
if ( ! write_file($localURL, $img)){
$this->session->set_flashdata('err_message', 'Unable to write the file');
}
It is creating a file named as main.jpg but with 0 bytes.
I also tried to use copy and file_get_content
if ( ! copy($localURL, $img)){
$error = get_last_error();
$this->session->set_flashdata('err_message', $error['message']);
}
if ( ! file_put_content($localURL, file_get_content($img) )){
$error = get_last_error();
$this->session->set_flashdata('err_message', $error['message']);
}
But It is also not working as well, It is not giving any error message.

I would first debug $img data verify it has a bunch of binary junk in it. You may also want to check the http status. Perhaps the website is denying remote curls by user agent.

What about doing this ?
$remoteFile = 'http://fermeteogranada.com/camara.jpg';
$remoteResource = file_get_contents($remoteFile);
$saveTo = './images/main.jpg';
file_put_contents($saveTo, $remoteResource);
I tried in local and it works just fine.

Related

ftp_put(): Opening data channel for file upload to server of "/xxx.txt"

I am working on to upload the file to FTP using PHP FTP. while putting the file to the server, its throw error.
what I did:
$ftp_conn = ftp_connect(SAP_SERVER_HOST, SAP_SERVER_PORT, 60);
if (!ftp_login($ftp_conn, SAP_SERVER_USER, SAP_SERVER_PASSWORD)) {
echo 'not connected<br/>';
} else {
$localfile = '/abc/txt/15375127769260.txt';
$serverfile = '/folder/15375127769260.txt';
// echo ftp_pwd($ftp_conn);
if (ftp_put($ftp_conn, $serverfile, $localfile, FTP_BINARY)) {
echo "Successfully uploaded $localfile.";
} else {
echo "Error uploading $localfile.";
}
// close connection
ftp_close($ftp_conn);
}
Suggest Me, what I miss in this code.
For anyone stumbling upon this:
my file was sent correctly after adding ftp_pasv($conn_id, true);
Note that it must be added after ftp_login().
ftp-pasv on php.net
are you using right folders and ports ?
$ftp_conn = ftp_connect(SAP_SERVER_HOST, SAP_SERVER_PORT, 60);
it should be port 21
and in local file you must get get the realpath of the file whit realpath() function
and for remote server the path is based on ftp base folder
Take a look of realpath http://php.net/manual/pt_BR/function.realpath.php

file_exists returning false in all cases

I'm working on Wordpress at the moment and as simple as it's sounds i'm trying to check if the image is there in the directory if not then it will show a standard no-image.
My problem is that the file_exists is returning false although the url is correct inside it, and it's accessible via browser so it's not a permission issue, and maybe i'm doing it wrong, here's the code;
$img = 'no_img.jpg';
if($val->has_prop('user_image')){
$img_tmp = $val->get( 'user_image' );
if(file_exists($upload_dir['baseurl'].'/users/'.$img_tmp)){
$img = $val->get( 'user_image' );
}
}
if i do var_dump($upload_dir['baseurl'].'/users/'.$img_tmp); it will show the exact direct URL to the file, and it's correct one, but when it enters the file_exists it returns $img = 'no_img.jpg' although the file exists in the directory.... What am i doing wrong??
I tried also to add clearstatcache(); before the file_exists but didn't work also.
Any ideas?
Try to use:
if( getimagesize($upload_dir['baseurl'].'/users/'.$img_tmp) !== false ){
$img = $val->get( 'user_image' );
}
else {
$img = $val->get( 'no_image' );
}
Also refer to the doc getimagesize
you can use
$fullPath=$upload_dir['baseurl'].'/users/'.$img_tmp;
if(#fopen($fullPath,"r")){
........
}
Or as mentioned in comments, try sniff instead :
if (#file_get_contents($upload_dir['baseurl'].'/users/'.$img_tmp, null, null, 0, 1)) {
//ok
}
You need to use $upload_dir['basedir'] instead of baseurl if you used $upload_dir = wp_upload_dir(); to determine the upload path of your WP installation.
or you can use file_get_contents, cURL, or fopen to sniff if image exists for the url.

stream_copy_to_stream() always returns 0

I'm using Fine-Uploader with PHP and something wrong happened. When I use stream_copy_to_stream() in the backend, it always returns 0.
Here's my code in the backend:
private function upload_file($file_name, $tmp_name)
{
$result = array(
'is_successful' => true,
'extra_message' => ''
);
$target_path = $this->get_target_file_path($file_name, $tmp_name);
move_uploaded_file($tmp_name, $target_path);
$result['is_successful'] = $this->handle_upload_request($target_path);
if ( $result['is_successful'] ) {
$result['extra_message'] = $target_path;
} else {
$result['extra_message'] = 'Unknown error occured.<br />';
}
return $result;
}
private function handle_upload_request($path)
{
$input = fopen("php://input", "r");
$temp = tmpfile();
$real_size = stream_copy_to_stream($input, $temp);
fclose($input);
echo $real_size;
if ($real_size != $this->get_size()){
return false;
}
$target = fopen($path, "w");
fseek($temp, 0, SEEK_SET);
stream_copy_to_stream($temp, $target);
fclose($target);
return true;
}
However, the $real_size always equal to 0. Strangely, the file can be uploaded successfully sometimes, but sometimes not.
I think maybe it's due to permission in Linux. Because I found that when I uploaded a file, the mod of the file is 644(But I think 644 is enough). And this problem also exists in Windows.
What's wrong with it?
You should not be using php://input. php://input is used to access the raw request body. It is empty for multipart encoded requests. All upload requests sent by Fine Uploader are multipart encoded by default. Instead, you should grab the file associated with the request using the $_FILES superglobal. There is a functional PHP example which will demonstrate this and more for you in the Fine Uploader server Github repo.
If you insist on writing your own PHP code to handle the requests, you really need to read the traditional server-side documentation for Fine Uploader first, which tells you that all upload requests are multipart encoded by default. This is set to the default in order to make it a bit easier to handle upload requests cross-browser, since we need to send the files in a MPE request from IE9 and older always anyway, since IE9 and older do not support uploading files via ajax requests (XHR2).

php check if file exists on an external doman (accessing form a sub domain)

I have a website on http://www.reelfilmlocations.co.uk
The above site has an admin area where images are uploaded and different size copies created in subfolders of an uploads/images directory.
I am creating a site for mobile devices, which will operate on a sub-domain, but use the database and images from the main domain,
http://2012.reelfilmlocations.co.uk
I want to be able to access the images that are on the parent domain, which i can do by linking to the image with the full domain i.e http:www.reelfilmlocations.co.uk/images/minidisplay/myimage.jpg
Though i need to check if the image exists first...
I have a php function that checks if the images exists, if it does it returns the full url of the image.
If it doesn't exist i want to return the path of a placeholder image.
The following function i have, returns the correct image if it exists, but if it doesn't, it is just returning the path to the directory where the placeholder image resides i.e http://www.reelfilmlocations.co.uk/images/thumbs/. without the no-image.jpg bit.
The page in question is: http://2012.reelfilmlocations.co.uk/browse-unitbases/
the code i have on my page to get the image is:
<img src="<?php checkImageExists('/uploads/images/thumbs/', $row_rs_locations['image_ubs']);?>">
My php function:
if(!function_exists("checkImageExists")){
function checkImageExists($path, $file){
$imageName = "http://www.reelfilmlocations.co.uk".$path.$file;
$header_response = get_headers($imageName, 1);
if(strpos($header_response[0], "404" ) !== false ){
// NO FILE EXISTS
$imageName = "http://www.reelfilmlocations.co.uk".$path."no-image.jpg";
}else{
// FILE EXISTS!!
$imageName = "http://www.reelfilmlocations.co.uk".$path.$file;
}
echo($imageName);
}
}
Failing to get this to work i did some digging around and read some posts about curl:
This just returns a placeholder image everytime.
if(!function_exists("remoteFileExists")){
function remoteFileExists($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;
}
}
if(!function_exists("checkImageExists")){
function checkImageExists($path, $file){
$imageName = "http://www.reelfilmlocations.co.uk".$path.$file;
$exists = remoteFileExists($imageName);
if ($exists){
// file exists do nothing we already have the correct $imageName
} else {
// file does not exist so set our image to the placeholder
$imageName = "http://www.reelfilmlocations.co.uk".$path."no-image.jpg";
}
echo($imageName);
}
}
I dont know if it could be to do with getting a 403, or how to check if this is the case.
any pointers or things i could try woud be greatly appreciated.
I'd do it using CURL, issuing a HEAD request and checking the response code.
Not tested, but should do the trick:
$URL = 'sub.domain.com/image.jpg';
$res = `curl -s -o /dev/null -IL -w "%{http_code}" http://$URL`;
if ($res == '200')
echo 'Image exists';
The code above will populate $res with status code of the requisition (pay attention that I DON'T include the http:// prefix to the $URL variable because I do it in the command line.
Of course the same might be obtained using PHP's CURL functions, and the above call might not work on your server. I am just explaining what I'd be doing if I had the same need.

How can I check if a file exists on a remote server using PHP?

How can I check if a specific file exists on a remote server using PHP via FTP connections?
Some suggestions:
Use ftp_size, which returns -1 if it doesn't exist: http://www.php.net/manual/en/function.ftp-size.php
Use fopen, e.g. fopen("ftp://user:password#example.com/somefile.txt", "r")
Use ftp_nlist, check to see if the filename you want is in the list: http://www.php.net/manual/en/function.ftp-nlist.php
I used this, a bit easier:
// the server you wish to connect to - you can also use the server ip ex. 107.23.17.20
$ftp_server = "ftp.example.com";
// set up a connection to the server we chose or die and show an error
$conn_id = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
ftp_login($conn_id,"ftpserver_username","ftpserver_password");
// check if a file exist
$path = "/SERVER_FOLDER/"; //the path where the file is located
$file = "file.html"; //the file you are looking for
$check_file_exist = $path.$file; //combine string for easy use
$contents_on_server = ftp_nlist($conn_id, $path); //Returns an array of filenames from the specified directory on success or FALSE on error.
// Test if file is in the ftp_nlist array
if (in_array($check_file_exist, $contents_on_server))
{
echo "<br>";
echo "I found ".$check_file_exist." in directory : ".$path;
}
else
{
echo "<br>";
echo $check_file_exist." not found in directory : ".$path;
};
// output $contents_on_server, shows all the files it found, helps for debugging, you can use print_r() as well
var_dump($contents_on_server);
// remember to always close your ftp connection
ftp_close($conn_id);
Functions used: (thanks to middaparka)
Login using ftp_connect
Get the remote file list via ftp_nlist
Use in_array to see if the file was present in the array
Just check the size of a file. If the size is -1, it doesn't exist, so:
$file_size = ftp_size($ftp_connection, "example.txt");
if ($file_size != -1) {
echo "File exists";
} else {
echo "File does not exist";
}
If the size is 0, the file does exist, it's just 0 bytes.
Source
A general solution would be to:
Login using ftp_connect
Navigate to the relevant directory via ftp_chdir
Get the remote file list via ftp_nlist or ftp_rawlist
Use in_array to see if the file was present in the array returned by ftp_rawlist
That said, you could potentially simply use file_exists if you have the relevant URL wrappers available. (See the PHP FTP and FTPS protocols and wrappers manual page for more information.)
This is an optimization of #JohanPretorius solution, and an answer for comments about "slow and inefficient for large dirs" of #Andrew and other: if you need more than one "file_exist checking", this function is a optimal solution.
ftp_file_exists() caching last folder
function ftp_file_exists(
$file, // the file that you looking for
$path = "SERVER_FOLDER", // the remote folder where it is
$ftp_server = "ftp.example.com", //Server to connect to
$ftp_user = "ftpserver_username", //Server username
$ftp_pwd = "ftpserver_password", //Server password
$useCache = 1 // ALERT: do not $useCache when changing the remote folder $path.
){
static $cache_ftp_nlist = array();
static $cache_signature = '';
$new_signature = "$ftp_server/$path";
if(!$useCache || $new_signature!=$cache_signature)
{
$useCache = 0;
//$new_signature = $cache_signature;
$cache_signature = $new_signature;
// setup the connection
$conn_id = ftp_connect($ftp_server) or die("Error connecting $ftp_server");
$ftp_login = ftp_login($conn_id, $ftp_user, $ftp_pwd);
$cache_ftp_nlist = ftp_nlist($conn_id, $path);
if ($cache_ftp_nlist===FALSE)die("erro no ftp_nlist");
}
//$check_file_exist = "$path/$file";
$check_file_exist = "$file";
if(in_array($check_file_exist, $cache_ftp_nlist))
{
echo "Found: ".$check_file_exist." in folder: ".$path;
}
else
{
echo "Not Found: ".$check_file_exist." in folder: ".$path;
};
// use for debuging: var_dump($cache_ftp_nlist);
if(!$useCache) ftp_close($conn_id);
} //function end
//Output messages
echo ftp_file_exists("file1-to-find.ext"); // do FTP
echo ftp_file_exists("file2-to-find.ext"); // using cache
echo ftp_file_exists("file3-to-find.ext"); // using cache
echo ftp_file_exists("file-to-find.ext","OTHER_FOLDER"); // do FTP
You can use ftp_nlist to list all the files on the remote server. Then you should search into the result array to check if the file what you was looking for exists.
http://www.php.net/manual/en/function.ftp-nlist.php
The code has been written by: #Drmzindec should be change a little:
if (in_array($check_file_exist, $contents_on_server))
to
if (in_array($file, $contents_on_server))

Categories