PHP bulk file read only list file in loop - php

php bulk file read problem in loop.
I have 3 image files which are already on server. Say it is picture1.jpg, picture2.jpg, picture3.jpg
I have this code which read the file but $thepic = fread($fh, $fs); only read last file ( picture3.jpg) in the array.
$imgfolder = "images/";
foreach ($picturefile as $pfile) {
echo $imgpath = "./". $imgfolder.$pfile; // This echo shows all files path when loop run
$picFile = $imgpath;
$fh = fopen($picFile, 'r');
$fs = filesize($picFile);
$thepic = fread($fh, $fs);
echo $thepic; // $thepic variable only show last file.
echo "<br>-----------------------------------------------<br>";
fclose($fh);
}

Related

Finding a file with PHP

I want to find a file with a wildcard in the same directory as my index.php is.
When I assign the $file_name manually with the name string, it works fine.
<?php
$file_name = glob("*.csv");
$handle = fopen($file_name, "r");
$file = fread($handle, filesize($file_name));
fclose($handle);
echo $file;
?>
The browser should output the content of the .csv file, like when I assign the $file_name manually.
you need a loop because glob() returns an array:
foreach (glob("*.csv") as $filename) {
$handle = fopen($filename, "r");
$file = fread($handle, filesize($filename));
fclose($handle);
echo $filename;
}
This script will find some images in working folder.
<?php
$workdir = getcwd(); // my working dir
$patternTofind = ".{jpg,gif,png}"; // Images example
$files = glob("$workdir*$patternTofind", GLOB_BRACE);
// Print result found
print_r($files);
?>

PHP to Increase counter by 1 and save in a txt file

I am trying my php script to read the current count from "counter.txt" file and add 1 and save it back in the counter text file.
$filename = 'counter.txt';
// create the file if it doesn't exist
if (!file_exists($filename)) {
$counter_file = fopen($filename, "w");
fwrite($counter_file, "0");
$counter = 0;
} else {
$counter_file = fopen($filename, "r");
// will read the first line
$counter = fgets($counter_file);
}
// increase $counter
$counter++;
// echo counter
echo $counter;
// save the increased counter
fwrite($counter_file, "0");
// close the file
fclose($counter_file);
The script reads and echos the number fine but it doesn't save the file with the increased number.
Please help
This may not be helpful if this is just a learning exercise to familiarize yourself with the various file functions, but this could be a lot simpler using file_get_contents and file_put_contents.
$file = 'counter.txt';
// default the counter value to 1
$counter = 1;
// add the previous counter value if the file exists
if (file_exists($file)) {
$counter += file_get_contents($file);
}
// write the new counter value to the file
file_put_contents($file, $counter);
Of course, whether or not this will work either this way or the way you're trying to do it totally depends on whether or not the file is writable, so you'll also need to be sure its permissions are set properly.
Works for me:
$counter = 1;
$file_name = 'test.'.$counter.'.ext';
if (file_exists($file_name)) {
$counter++;
fopen('test'.$counter.'.ext' , "w");
}
else {
fopen('test'.$counter.'.ext' , "w");
}
<?php
$filename = 'counter.txt';
// create the file if it doesn't exist
if (!file_exists($filename)) {
$counter_file = fopen($filename, "w");
fwrite($counter_file, "1");
fclose($counter_file);
} else {
$counter_file = fopen($filename, "w+");
$fsize = filesize($filename);
// will read the whole file
$counter = (int) fread($counter_file, $fsize);
$counter++;
fwrite($counter_file, $counter);
fclose($counter_file);
}

Trying to find file extension on hidden download url

I am trying to make a script to take a downloadable file and put it onto my ftp server to then update a database. I cannot figure out what the url extention should be to able to make this work.
<?php
$src = fopen('https://www.atf.gov/firearms/docs/0516-ffl-listxlsx/download', 'r');
$dest1 = fopen('first1k.xlsx', 'w');
$dest2 = fopen('remainder.xlsx', 'w');
echo stream_copy_to_stream($src, $dest1, 19759460) . " bytes copied to first1k.txt\n";
echo stream_copy_to_stream($src, $dest2) . " bytes copied to remainder.txt\n";
?>
This is where I am trying to get the data from https://www.atf.gov/firearms/listing-federal-firearms-licensees-ffls-2016
<?php
$file = "0516.xlsx";
$url = 'https://www.atf.gov/firearms/docs/0516-ffl-listxlsx/download' ;
$handle = fopen("0516.xlsx", "w+");
fwrite($handle, file_get_contents($url));
rewind($handle);
$read = htmlentities(fread($handle, filesize($file)));
?>
fixed it out

Issue with multiple image write

Now I am fed up with this issue, have been trying to fix it since 2-3 days.
The problem:
I am downloading certain images, and then writing them on to disk with php script.
The images are high resolution may be around 7000 pixels. The data is being downloaded properly.
When I write this data on to file, some time 1 image gets write, some times 2,3 etc.
The script is not showing any error and just breaks.
I don't have access to server logs and can't check those either.
It breaks after curl_get_contents , means where I write file, if I comment that section it works properly.
Below is the code:
<?php
ini_set ("display_errors", "1");
error_reporting(E_ALL);
ini_set('max_execution_time', 3000);
include_once("../config.php");
include_once("../utils.php");
$DIR = "../wallpapers";
$URL = "Website url";
$info = array();
$dom = new domDocument;
#$dom->loadHTML(file_get_contents($URL));
$dom->preserveWhiteSpace = false;
$links = $dom->getElementsByTagName('img');
$i = 0;
foreach ($links as $tag){
$iurl = $tag->getAttribute('src');
$lastHyphenAt = strrpos($iurl, "-");
$iurl = substr ($iurl, 0, $lastHyphenAt).".jpg";
$info[$i]["url"] = $iurl;
$info[$i]["name"] = basename($iurl);
$i++;
}
foreach($info as $item){
$url = $item["url"];
$name = $item["name"];
if(!file_exists($DIR."/".$name)){
echo "Downloading: ".$url."<br><br>";
$data = curl_get_contents($url);
$file = fopen($DIR."/".$name,"w") or die('Cannot open file: '.$my_file);
fwrite($file,$data);
fclose($file);
}else
echo "Exists ".($DIR."/".$name)."<br><br>";
}
?>
you can write high resolution images by applying chunk functionality, check below code for the same :-
$chunk = 102400;
$filePointer = fopen($url, "rb");
if ($filePointer!=false){
while (!feof($filePointer))
{
if($chunk<TOTALFILESIZE)
{
$fileData = fread($filePointer, 102400); //102400 is chunk size
$myFile = $DIR."/".$_REQUEST['filename'].'.'.$_REQUEST['ext']; //store the file into temp. location
chmod($myFile, 0777);
$fp = fopen($myFile, 'a+');
fwrite($fp, $fileData);
fclose($fp);
}
}
}

Read all txt files in a specific folder and write all contents in one txt file

I try to read all *.txt files from a folder and write all content from each file into another txt file. But somehow it only writes one line into the txt file.
I tried with fwrite() and file_put_contents(), neither worked.
Here is my code:
<?php
$dh = opendir('/Applications/XAMPP/xamppfiles/htdocs/test/');
while($file = readdir($dh)) {
$contents = file_get_contents('/Applications/XAMPP/xamppfiles/htdocs/test/' . $file);
$dc = array($contents);
}
file_put_contents('content.txt', $dc);
?>
This should work for you:
(Here I get all *.txt files in a directory with glob(). After this I loop through every file with a foreach loop and get the content of each single file with file_get_contents() and I put the content into the target file with file_put_contents())
<?php
$files = glob("path/*.txt");
$output = "result.txt";
foreach($files as $file) {
$content = file_get_contents($file);
file_put_contents($output, $content, FILE_APPEND);
}
?>
try this
$contents = array();
$line = file(/*next file in dir*/);
foreach($lines as line){
array_push($line, $contents);
}
//File path of final result
$filepath = "mergedfiles.txt";
$out = fopen($filepath, "w");
//Then cycle through the files reading and writing.
foreach($filepathsArray as $file){
$in = fopen($file, "r");
while ($line = fgets($in)){
print $file;
fwrite($out, $line);
}
fclose($in);
}
//Then clean up
fclose($out);
return $filepath;

Categories