How to download image from URL in php? - php

I am downloading the image from URL using file_get_contents function. But in some case I get the error like this
"file_get_contents(http://www.aaaaa.com/multimedia/dynamic/02456/RK_2456652g.jpg): failed to open stream: HTTP request failed!".
Only for some of the URL am getting this error, other images are easily downloaded using this code.
I am getting this error when I run this code in cron. But when I manually downloading the image from same URL its downloading. Can anyone please help me to solve this problem.
My code is
$arr="http://www.aaaa.com/multimedia/dynamic/02077/saibaba_jpg_2077721g.jpg";
$file = basename($arr);
$date = date('Ymd');
$id=2225;
if (!file_exists('../media/'.$date)) {
$path=mkdir('../media/'.$date, 0777, true);
}
if (!file_exists('../media/'.$date.'/'.$id)) {
$path=mkdir('../media/'.$date.'/'.$id, 0777, true);
}
//Get the file
$content= file_get_contents($arr);
//Store in the filesystem.
$fp = fopen('../media/'.$date.'/'.$id.'/'.$file, "w");
fwrite($fp, $content);
fclose($fp);

If you are execute your function then you must provide full path to of your file.LIKE
$arr="http://www.aaaa.com/multimedia/dynamic/02077/saibaba_jpg_2077721g.jpg";
$file = basename($arr);
$date = date('Ymd');
$id=2225;
if (!file_exists('/var/www/path_to_Your_folder/media/'.$date)) {
$path=mkdir('/var/www/path_to_Your_folder/media/'.$date, 0777, true);
}
if (!file_exists('/var/www/path_to_Your_folder/media/'.$date.'/'.$id)) {
$path=mkdir('/var/www/path_to_Your_folder/media/'.$date.'/'.$id, 0777, true);
}
//Get the file
$content= file_get_contents($arr);
//Store in the filesystem.
$fp = fopen('/var/www/path_to_Your_folder/media/'.$date.'/'.$id.'/'.$file, "w");
fwrite($fp, $content);
fclose($fp)

Related

Create CSV File in PHP and Save to SFTP using phpseclib

I need to generate a CSV file from a MySQL query and save the file to an SFTP server. I have tried the code below. The CSV file gets created, but it is empty. I also receive an error message in the browser that says Warning: is_file() expects parameter 1 to be a valid path, resource given in regard to this line $sftp->put($fileName, $fp, NET_SFTP_LOCAL_FILE);. If I move fclose($fp); to the last line, I don't get the error but data still doesn't appear in the file. Could someone please let me know how to get the data to save in the file that was created?
$fileName = 'dataFiles/reports/Report Summary/Report Summary.csv';
$sql = mysqli_query($db, "
SELECT *
FROM reports
WHERE reportID = 1
");
$fp = fopen('php://output', 'w');
$first = true;
while($row = mysqli_fetch_assoc($sql)){
if ($first) {
fputcsv($fp, array_keys($row));
$first = false;
}
fputcsv($fp, $row);
}
fclose($fp);
$sftp->put($fileName, $fp, NET_SFTP_LOCAL_FILE);
Try something like this:
<?php
$fp = fopen('php://temp', 'r+');
// do stuff
rewind($fp);
$sftp->put($filename, $fp);
phpseclib (assuming you're using a new enough version) will detect that the second parameter is a stream resource and will try to read from it accordingly.
The second argument is not a handle but the content directly.
I think you could do: stream_get_contents($fp); in the second argument.
$content = stream_get_contents($fp);
fclose($fp);
$sftp->put($fileName, $content, NET_SFTP_LOCAL_FILE);

PHP - Not able to get content with fread

I am trying to get the API data from a cache file if there already was the same request recently. Everything works fine but I am just not able to get the content from the cache file even tho it is there. I can't find an error. I hope u can help me.
$url = /* API URL */;
function getJson($url) {
$cacheFile = 'cache' . DIRECTORY_SEPARATOR . md5($url) . '.json';
if (file_exists($cacheFile)) {
$fh = fopen($cacheFile, 'r');
$cacheTime = filemtime($cacheFile);
if ($cacheTime > strtotime('-60 minutes')) {
$json = fread($fh);
return $json;
}
fclose($fh);
unlink($cacheFile);
}
$json = file_get_contents($url);
$fh = fopen($cacheFile, 'w');
fwrite($fh, $json);
fclose($fh);
return $json;
}
$datab = getJson($url);
$data = json_decode($datab, true);
print_r($data);
Il you dont check for your error log or display errors on screen you gonna have a bad time finding its.
Here you have a $cacheFile which should be a $cachePath, so prefix with './' or better DIR
Then you call fread without second parameter, and so on...check your error log, enable all errors.
You must specify the length that needs to be read in fread.
Use:
if (file_exists($cacheFile)) {
$fh = fopen($cacheFile, 'r');
$cacheTime = filemtime($cacheFile);
if ($cacheTime > strtotime('-60 minutes')) {
$json = fread($fh,filesize($cacheFile));
fclose($fh); //Remember to release resources
return $json;
}
fclose($fh);
unlink($cacheFile);
}
Alternatively use file_get_contents($cacheFile) to get the whole file without the need for an fopen first.

Copying a mp3 File from a URL to server with php, no sound?

i am trying to save a mp3 file from a website "http...../filename.mp3" to my server from with the following php code, i receive the url in the $url from ajax. thats my code:
$url = $_POST['data'];
$filename = substr($url, strrpos($url, '/') + 1);
$directory = './fileuploads/tmp/';
$data = file_get_contents($url);
$file = fopen($directory.$filename, "w+");
fwrite($file, $data);
fclose($file);
It works fine but the new mp3 file on my server is "empty". it doesnt play any sound. how do you guys would solve such a problem? please make it as simple as possible. best regards

PHP: fopen error handling

I do fetch a file with
$fp = fopen('uploads/Team/img/'.$team_id.'.png', "rb");
$str = stream_get_contents($fp);
fclose($fp);
and then the method gives it back as image. But when fopen() fails, because the file did not exists, it throws an error:
[{"message":"Warning: fopen(uploads\/Team\/img\/1.png): failed to open stream: No such file or directory in C:\...
This is coming back as json, obviously.
The Question is now: How can i catch the error and prevent the method from throwing this error directly to the client?
You should first test the existence of a file by file_exists().
try
{
$fileName = 'uploads/Team/img/'.$team_id.'.png';
if ( !file_exists($fileName) ) {
throw new Exception('File not found.');
}
$fp = fopen($fileName, "rb");
if ( !$fp ) {
throw new Exception('File open failed.');
}
$str = stream_get_contents($fp);
fclose($fp);
// send success JSON
} catch ( Exception $e ) {
// send error message if you can
}
or simple solution without exceptions:
$fileName = 'uploads/Team/img/'.$team_id.'.png';
if ( file_exists($fileName) && ($fp = fopen($fileName, "rb"))!==false ) {
$str = stream_get_contents($fp);
fclose($fp);
// send success JSON
}
else
{
// send error message if you can
}
You can use the file_exists() function before calling fopen().
if(file_exists('uploads/Team/img/'.$team_id.'.png')
{
$fp = fopen('uploads/Team/img/'.$team_id.'.png', "rb");
$str = stream_get_contents($fp);
fclose($fp);
}
[{"message":"Warning: fopen(uploads\/Team\/img\/1.png): failed to open stream: No such file or directory in C:\...
the error is clear: you've put the wrong directory, you can try what you whant but it'll not work. you can make it work with this:
take your file and put it in the same folder of your php file
(you'll be able to move it after don't worry, it's about your error)
or on a folder "higher" of your script (just not outside of your www
folder)
change the fopen to ('./$team_id.'png',"rb");
rerun your script file
don't forget this : you can't access a file that is'nt in your "www" folder
(he doesn't found your file because he give you her name: the name come from the $team_id variable)
Generically - This is probably the best way to do file-io in php (as mentioned by #Cendak here)
$fileName = 'uploads/Team/img/'.$team_id.'.png';
if ( file_exists($fileName) && ($fp = fopen($fileName, "rb"))!==false ){
$str = stream_get_contents($fp);
fclose($fp);
// send success JSON
}else{
// send an error message if you can
}
But it does not work with PHP 7.3, these modifications do,
if(file_exists($filename) && ($fp = fopen($filename,"r") !== false)){
$fp = fopen($filename,"r");
$filedata = fread($fp,filesize($filename));
fclose($fp);
}else{
$filedata = "default-string";
}

Download Campaign Performance Reports using Bings Ads in PHP

I was struck in this since a weeks. Please tell me if any one can help me out from this.
I tried this samples they given. I'm trying to download only campaign performance reports, Where i'm able to download a zip file which has a csv file in it. Here is the another direct example i followed for keywords and did the same way for campaign performance. Which giving me a link to download the reports. When i'm trying to download the url manually i can download but I cannot download it through my code.
function DownloadFile($reportDownloadUrl, $downloadPath) {
if (!$reader = fopen($reportDownloadUrl, 'rb')) {
throw new Exception("Failed to open URL " . $reportDownloadUrl . ".");
}
if (!$writer = fopen($downloadPath, 'wb')){
fclose($reader);
throw new Exception("Failed to create ZIP file " . $downloadPath . ".");
}
$bufferSize = 100 * 1024;
while (!feof($reader)) {
if (false === ($buffer = fread($reader, $bufferSize))) {
fclose($reader);
fclose($writer);
throw new Exception("Read operation from URL failed.");
}
if (fwrite($writer, $buffer) === false) {
fclose($reader);
fclose($writer);
$exception = new Exception("Write operation to ZIP file failed.");
}
}
fclose($reader);
fflush($writer);
fclose($writer);
}
But I couldn't download the file. I can't move forward from there so any help like downloading reports in any-other form or the simple code changes in current method is greatly appreciated. Thanks in advance.
When I tried this I also had problems with the DownloadFile function so replaced this with a different version
function DownloadFile($reportDownloadUrl, $downloadPath) {
$url = $reportDownloadUrl;
// Example for the path would be in this format
// $path = '/xxx/yyy/reports/keywordperf.zip';
// using the server path and not relative to the file
$path = $downloadPath;
$fp = fopen($path, 'w');
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSLVERSION, 3);
curl_setopt($ch, CURLOPT_FILE, $fp);
if($result = curl_exec($ch)) {
$status = true;
}
else
{
$status = false;
}
curl_close($ch);
fclose($fp);
return status;
}

Categories