Php fopen erros when file exists already - php

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.

Related

Downloading file, changing extension and merging into 1 file

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);

Write and read from the same file- PHP

I am trying to write to a file and then read the data from the same file. But sometimes I am facing this issue that the file reading process is getting started even before the file writing gets finished. How can I solve this issue ? How can i make file writing process finish before moving ahead?
// writing to file
$string= <12 kb of specific data which i need>;
$filename.="/ttc/";
$filename.="datasave.html";
if($fp = fopen($filename, 'w'))
{
fwrite($fp, $string);
fclose($fp);
}
// writing to the file
$handle = fopen($filename, "r") ;
$datatnc = fread($handle, filesize($filename));
$datatnc = addslashes($datatnc);
fclose($handle);
The reason it does not work is because when you are done writing a string to the file the file pointer points to the end of the file so later when you try to read the same file with the same file pointer there is nothing more to read. All you have to do is rewind the pointer to the beginning of the file. Here is an example:
<?php
$fileName = 'test_file';
$savePath = "tmp/tests/" . $fileName;
//create file pointer handle
$fp = fopen($savePath, 'r+');
fwrite($fp, "Writing and Reading with same fopen handle!");
//Now rewind file pointer to start reading
rewind($fp);
//this will output "Writing and Reading with same fopen handle!"
echo fread($fp, filesize($savePath));
fclose($fp);
?>
Here is more info on the rewind() method http://php.net/manual/en/function.rewind.php
I have mentioned the URL through which i got the solution. I implemented the same. If you want me to copy the text from that link then here it is :
$file = fopen("test.txt","w+");
// exclusive lock
if (flock($file,LOCK_EX))
{
fwrite($file,"Write something");
// release lock
flock($file,LOCK_UN);
}
else
{
echo "Error locking file!";
}
fclose($file);
Use fclose after writing to close the file pointer and then fopen again to open it.

Create html file with php script

I want to create a php script that will check if a certain html file exist or not. if it doesn't exist, then create a new one and give it a name.
I have tried the code below, but still not working.
$file = file_get_contents(site_url('appraisal/createReport'));
$filename = 'Service_delivery_report_'.date('Y-m-d', time()).'.html';
$filepath = dirname(__DIR__).'/views/sd_reports/'.$filename;
write_file($filepath, $file);
if(! file_exists ($filename))
{
$fp = fopen($filename, 'w');
fwrite($fp, $file);
fclose($fp);
}
I'm not familiar with the method you're using called 'site_url'. From a quick google search it looks like it's a method in Word Press. Ignoring the site_url method, you might want to test using a specific url, like http://ted.com for example. I've specified is_file rather than file_exists because file_exists will return true even if the path you've specified is a directory, whereas is_file will only return true if the path is an actual file. Try this code, setting the $site variable to a site url or path to a file.
I've also switched some code around, doing a check first to see if the file exists before attempting to read in the contents of $site. This way, if the file already exists, you're not needlessly reading in the contents of $site.
$filename = "Service_delivery_report_" . date("Y-m-d",
time()). ".html";
$filepath = realpath("./") . "/views/sd_reports/" . $filename;
if (!is_file($filepath))
{
$site = "http://somesite.com/somepage";
if ($content = file_get_contents($site))
{
file_put_contents($filepath,
$content);
}
else
{
echo "Could not grab the contents of some site";
}
}
Use file_exists();
<?php
$filename = '/path/to/foo.txt';
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
?>
Then, if it doesn't exist, create a file with fopen();, like so:
$handle = fopen($filename, "w");
Try this
$file = file_get_contents(site_url('appraisal/createReport'));
$filename = 'Service_delivery_report_'.date('Y-m-d', time()).'.html';
if(! file_exists ($filename))
{
$f = fopen($filename, "w");
fwrite($f, $file);
fclose($f);
}
else
echo "file already exist";

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')

File Handling using PHP

Can anyone tell the method to modify/delete the contents of a text file using PHP
Using file_put_contents:
file_put_contents($filename, 'file_content');
If you want to append to the file instead of replacing it's contents use:
file_put_contents($filename, 'append_this', FILE_APPEND);
(file_out_contents is the simpler alternative to using the whole fopen complex.)
By using fopen:
if (is_writable($filename)) {
if (!$handle = fopen($filename, 'w')) {
echo "Cannot open file ($filename)";
exit;
}
if (fwrite($handle, $somecontent) === FALSE) {
echo "Cannot write to file ($filename)";
exit;
}
echo "Success, wrote to file ($filename)";
fclose($handle);
}
Write "" to a file to delete its contents.
To delete contents line by line use:
$arr = file($fileName);
unset($arr[3]); // 3 is an arbitrary line
then write the file contents. Or are you referring to memory mapped files?
There are number of ways to read files. Large files can be handled very fast using
$fd = fopen ("log.txt", "r"); // you can use w/a switches to write append text
while (!feof ($fd))
{
$buffer = fgets($fd, 4096);
$lines[] = $buffer;
}
fclose ($fd);
you can also use file_get_contents() to read files. its short way of achieving same thing.
to modify or append file you can use
$filePointer = fopen("log.txt", "a");
fputs($filePointer, "Text HERE TO WRITE");
fclose($filePointer);
YOU CAN ALSO LOAD THE FILE INTO ARRAY AND THEN PERFORM SEARCH OPERATION TO DELETE THE SPECIFIC ELEMENTS OF THE ARRAY.
$lines = file('FILE WITH COMPLETE PATH.'); // SINGLE SLASH SHOULD BE DOUBLE SLASH IN THE PATH SOMTHING LIKE C://PATH//TO//FILE.TXT
Above code will load the file in $lines array.

Categories