Downloading file, changing extension and merging into 1 file - php

Trying to download files via the URL, rename from the .ADM extension to .txt
then put contents of each file into a single txt file
However its saying the fputs param 2 is a resource
The $logfile['name'] is the filename thats stored in the array
Heres my code
foreach($items as $logfile)
{
$getfile = $logfile['Download'];
$newfile = file_put_contents(str_replace('ADM','txt',$logfile['name']),
file_get_contents($getfile));
$name = str_replace('ADM','txt',$logfile['name']);
$newfile = $name;
$file = fopen($newfile, 'rb');
$output = fopen('tmp/test.txt', 'wb');
fputs($output, $file);
fclose($output);
fclose($file);
}
Its downloading each and renaming however its not moving the content & giving me this error
Warning: fputs() expects parameter 2 to be string, resource given in

The second parameter of fputs is the content of a file. Not a file resource.
Instead of
$file = fopen($newfile, 'rb');
You‘ll need to get the contents of the file
$content = file_get_contents($newfile);
Or, if you like to use fopen, you can use fread:
$file = fopen($newfile, 'rb');
$content = fread($fp, filesize($newfile));
Then you can put this content into another file:
fputs($output, $content);

Related

failed to open stream: HTTP wrapper does not support writeable connections

I have uploaded my localhost files to my website but it is showing me this error:-
: [2] file_put_contents( ***WebsiteURL*** /cache/lang/ ***FileName*** .php)
[function.file-put-contents]: failed to open stream: HTTP wrapper does
not support writeable connections | LINE: 127 | FILE: /home/content/
***Folders\FileName*** .php
What i personally feel that the contents get saved in a file in cache folder and when i uploaded the files to my web server it is trying to access the cached localhost folder.
Instead of doing file_put_contents(***WebSiteURL***...) you need to use the server path to /cache/lang/file.php (e.g. /home/content/site/folders/filename.php).
You cannot open a file over HTTP and expect it to be written. Instead you need to open it using the local path.
you could use fopen() function.
some example:
$url = 'http://doman.com/path/to/file.mp4';
$destination_folder = $_SERVER['DOCUMENT_ROOT'].'/downloads/';
$newfname = $destination_folder .'myfile.mp4'; //set your file ext
$file = fopen ($url, "rb");
if ($file) {
$newf = fopen ($newfname, "a"); // to overwrite existing file
if ($newf)
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
May this code help you. It works in my case.
$filename = "D:\xampp\htdocs\wordpress/wp-content/uploads/json/2018-10-25.json";
$fileUrl = "http://localhost/wordpress/wp-content/uploads/json/2018-10-25.json";
if(!file_exists($filename)):
$handle = fopen( $filename, 'a' ) or die( 'Cannot open file: ' . $fileUrl ); //implicitly creates file
fwrite( $handle, json_encode(array()));
fclose( $handle );
endif;
$response = file_get_contents($filename);
$tempArray = json_decode($response);
if(!empty($tempArray)):
$count = count($tempArray) + 1;
else:
$count = 1;
endif;
$tempArray[] = array_merge(array("sn." => $count), $data);
$jsonData = json_encode($tempArray);
file_put_contents($filename, $jsonData);
it is because of using web address, You can not use http to write data. don't use :
http:// or https:// in your location for upload files or save data or somting like that. instead of of using $_SERVER["HTTP_REFERER"] use $_SERVER["DOCUMENT_ROOT"].
for example :
wrong :
move_uploaded_file($_FILES["File"]["tmp_name"],$_SERVER["HTTP_REFERER"].'/uploads/images/1.jpg')
correct:
move_uploaded_file($_FILES["File"]["tmp_name"],$_SERVER["DOCUMENT_ROOT"].'/uploads/images/1.jpg')

how to read contents from PUT request and grab the file contents in variable php

below is the code which i want to modify
$input = fopen("php://input", "r");
$temp = tmpfile();
$realSize = stream_copy_to_stream($input, $temp);
fclose($input);
if ($realSize != $this->getSize()){
return false;
}
$target = fopen($path, "w");
fseek($temp, 0, SEEK_SET);
stream_copy_to_stream($temp, $target);
fclose($target);
I want to save the contents into the memory and transfer it accross to other server without saving it on apache server.
when i try to output the contents i only see resource id# 5. Any suggestion, comments are highly apprecited . thanks
The code you have opens file handles, which in themselves are not the content. To get the content into a variable, just read it like any other file:
$put = file_get_contents('php://input');
To get the contents of the stream:
rewind($temp); // rewind the stream to the beginning
$contents = stream_get_contents($temp);
var_dump($contents);
Or, use file_get_contents as #deceze mentions.
UPDATE
I noticed you're also opening a temp file on disk. You might want to consider simplifying your code like so:
$put = stream_get_contents(STDIN); // STDIN is an open handle to php://input
if ($put) {
$target = fopen('/storage/put.txt', "w");
fwrite($target, $put);
fclose($target);
}

Extracting text between values in txt file using php

Im trying to extract the values between eng_tid
and eng_data for http://fdguirhgeruih.x10.mx/html.txt and I keep getting T string errors.
why do I keep getting errors
<? php
//First, open the file. Change your filename
$file = "http://fdguirhgeruih.x10.mx/html.txt";
$word1='tid';
$word2='data';
$handle = fopen($file, "r");
$contents = fread($handle, filesize($file));
fclose($handle);
$between=substr($contents, strpos($contents, $word1), strpos($contents, $word2) - strpos($contents, $word1));
echo $between;
?>
UPDATE after seeing error messages...
Instead of fread() and attempting to use the size in bytes of your target file, you may simply use file_get_contents() to retrieve the remote file. Your error is because PHP wants to read the filesize of the file as though it is local, but it is a remote file over HTTP. filesize() reports 0 and an error. Instead do
// Don't do this...
//$handle = fopen($file, "r");
//$contents = fread($handle, filesize($file));
//fclose($handle);
// Instead do this...
$contents = file_get_contents($file);

In memory download and extract zip archive

I would like to download a zip archive and unzip it in memory using PHP.
This is what I have today (and it's just too much file-handling for me :) ):
// download the data file from the real page
copy("http://www.curriculummagic.com/AdvancedBalloons.kmz", "./data/zip.kmz");
// unzip it
$zip = new ZipArchive;
$res = $zip->open('./data/zip.kmz');
if ($res === TRUE) {
$zip->extractTo('./data');
$zip->close();
}
// use the unzipped files...
Warning: This cannot be done in memory — ZipArchive cannot work with "memory mapped files".
You can obtain the data of a file inside a zip-file into a variable (memory) with file_get_contentsDocs as it supports the zip:// Stream wrapper Docs:
$zipFile = './data/zip.kmz'; # path of zip-file
$fileInZip = 'test.txt'; # name the file to obtain
# read the file's data:
$path = sprintf('zip://%s#%s', $zipFile, $fileInZip);
$fileData = file_get_contents($path);
You can only access local files with zip:// or via ZipArchive. For that you can first copy the contents to a temporary file and work with it:
$zip = 'http://www.curriculummagic.com/AdvancedBalloons.kmz';
$file = 'doc.kml';
$ext = pathinfo($zip, PATHINFO_EXTENSION);
$temp = tempnam(sys_get_temp_dir(), $ext);
copy($zip, $temp);
$data = file_get_contents("zip://$temp#$file");
unlink($temp);
As easy as:
$zipFile = "test.zip";
$fileInsideZip = "somefile.txt";
$content = file_get_contents("zip://$zipFile#$fileInsideZip");
Old subject but still relevant since I asked myself the same question, without finding an answer.
I ended up writing this function which returns an array containing the name of each file contained in the archive, as well as the decompressed contents of that file:
function GetZipContent(String $body_containing_zip_file) {
$sectors = explode("\x50\x4b\x01\x02", $data);
array_pop($sectors);
$files = explode("\x50\x4b\x03\x04", implode("\x50\x4b\x01\x02", $sectors));
array_shift($files);
$result = array();
foreach($files as $file) {
$header = unpack("vversion/vflag/vmethod/vmodification_time/vmodification_date/Vcrc/Vcompressed_size/Vuncompressed_size/vfilename_length/vextrafield_length", $file);
array_push($result, [
'filename' => substr($file, 26, $header['filename_length']),
'content' => gzinflate(substr($file, 26 + $header['filename_length'], -12))
]);
}
return $result;
}
Hope this is useful ...
You can get a stream to a file inside the zip and extract it into a variable:
$fp = $zip->getStream('test.txt');
if(!$fp) exit("failed\n");
while (!feof($fp)) {
$contents .= fread($fp, 1024);
}
fclose($fp);
If you can use system calls, the simplest way should look like this (bzip2 case). You just use stdout.
$out=shell_exec('bzip2 -dkc '.$zip);

php input stream size limitations

I am trying to read a raw input stream from php using php://input. This works for most files, however, files over 4MB are being ignored in the upload. I have set post_max_size and upload_max_size to 20M each thinking it would solve my problem, but it didn't. Is there another php.ini setting that needs to be configured or do I need to do chunking of some sort? If so, how would I go about doing that? Here is the upload.php code:
$fileName = $_SERVER['HTTP_X_FILE_NAME'];
$contentLength = $_SERVER['CONTENT_LENGTH'];
file_put_contents('uploads/' . $fileName, file_get_contents("php://input"));
Try stream_copy_to_stream, which directly pumps the content of the input into the file without copying it all into memory first:
$input = fopen('php://input', 'rb');
$file = fopen($filename, 'wb');
stream_copy_to_stream($input, $file);
fclose($input);
fclose($file);
Alternative:
$input = fopen('php://input', 'rb');
$file = fopen($filename, 'wb');
while (!feof($input)) {
fwrite($file, fread($input, 102400));
}
fclose($input);
fclose($file);

Categories