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')
Related
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);
i am trying to read contents from a text file in php. i am using wamp on windows. i m getting this error:
Warning: fopen(/input.txt): failed to open stream: No such file or directory in C:\wamp\www\cycle_gps_sender.php on line 3
this is my code:
$location = fopen("/input.txt", "r") or die("Unable to open file!");
echo $location;
fclose($location);
both the php file and input.txt are placed in www folder of wamp.
Hope this will help you:
$File = "log_post.txt";
$fh = fopen ($File, 't') or die("can't open file");
fclose($fh);
$location = fopen("input.txt", "r") or die("Unable to open file!");
echo $location;
fclose($location);
Use this code and keep the input.txt file in the same directory where this code is written.
First check if file exist or not?
$filename = '/path/to/foo.txt';
if (file_exists($filename)) {
chmod($filename, 0777);
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
$location = file_get_contents('./input.txt', FILE_USE_INCLUDE_PATH);
echo $location;
or
$location = file_get_contents('input.txt');
echo $location;
hope it will help
Add full path to file.
On the Windows platform, be careful to escape any backslashes used in the path to the file, or use forward slashes.
$location = fopen("C:\\folder\\input.txt", "r");
Remove '/'(Slash)
$location = fopen("input.txt", "r") or die("Unable to open file!");
$file = fopen("path/input.txt","a+") or die("Unable to open file!");
.....
fclose($file);
You have to create file before you READ or if you open file by 'r' , so if you open file by 'a+' , your file will be created automatically.
I have the following script to write a file that i grabbed from online.
$newfname = $data['transferPath'] . '/' . $data['filename'];
$file = fopen ($data['filePath'], "rb");
if(!$file) {
throw new Exception('Unable to open file for reading ' . $file);
}
if($file) {
$newf = fopen ($newfname, "wb");
if(!$newf) {
throw new Exception("Cant open file for writing");
}
if($newf) {
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
}
}
}
if($file) {
fclose($file);
}
if($newf) {
fclose($newf);
}
when i post the data and run this script I keep getting the exception for cant open file for writing because there already is a file but that name in the same directory. Im trying to overwrite the file with the new file any ideas what i can do. iv tried using the options for fopen using w and w+. I need to completely overwrite the file there if exists otherwise create the file.
Try using the a+ ending parameter to the fopen() function.
Look here for a complete list of the possible parameters and what they do to find the right one for your purpose!
If none of these satisfy your needs then you could do something like this:
$fopen($data['filePath'], "r");
if($file){
unlink($data['filePath']);
}
Then after it deletes the file, if it's there, then just do another fopen with the w parameter.
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);
}
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);