I have this URL
'http://2.bp.blogspot.com/-LBbpkomI7JQ/VnLmeFZANgI/AAAAAAAAWhc/MsdZjtxN0HQ/s0-Ic42/RCO001.jpg '
I tried to do some search and did this
$file = fopen("C:\Users\Alex\Desktop\script.txt", "r");
$links = array();
while (!feof($file)) {
$links[] = fgets($file);
}
fclose($file);
foreach($links as $num => $link)
{
echo "'".$link."'";
save_image("'".$link."'","'".$num."'".".jpg");
}
var_dump($links);
function save_image($inPath,$outPath)
{ //Download images from remote server
$in= fopen($inPath, "rb");
$out= fopen($outPath, "wb");
while ($chunk = fread($in,8192))
{
fwrite($out, $chunk, 8192);
}
fclose($in);
fclose($out);
}
All urls are in my script.txt file so I am storing them in an array then calling each url one by one but it says
failed to open stream: Invalid argument
Anything missing or wrong?
You could try this implementation (works great for me):
<?php
$links = explode("\n", file_get_contents("C:\Users\Alex\Desktop\script.txt"));
foreach($links as $num => $link)
{
echo $link . "\n";
save_image($link, $num.".jpg");
}
function save_image($inPath, $outPath)
{
$inPath = trim($inPath);
if ($inPath != "") {
file_put_contents($outPath, file_get_contents($inPath));
}
}
assuming your script.txt looks like this
http://2.bp.blogspot.com/-LBbpkomI7JQ/VnLmeFZANgI/AAAAAAAAWhc/MsdZjtxN0HQ/s0-Ic42/RCO001.jpg
In this line:
$file = fopen("C:\Users\Alex\Desktop\script.txt", "r");
Your backslashes might be converted into special chars by PHP, this could cause a problem, so
look at this topic:
failed to open stream: Invalid argument
Second thing:
It might be a problem with fopen configuration
Edit your php.ini and set:
allow_url_fopen = On
You can check this value (it's probably false):
var_dump(ini_get('allow_url_fopen'));
You'll need to speak to your web host, or try another method. Mabye CURL is enabled?
You should also check your display_errors and error_reporting values. PHP should have complained loudly about being unable to open the URL.
Related
I'm beginner in html and php. I trying to create a script that will open the directory, display all text files, open each of them for editing and save the changes to a file (all the script operation will be transferred to the html form). Unfortunately, after opening the directory and viewing the files, I have trouble reading their contents. Could someone tell me what I doing wrong ?
Thank for help
<?php
$path = "books/";
$books = opendir($path);
while (($book = readdir($books)) !== false)
{
echo $book;
foreach (glob("*.txt") as $readfile)
{
$readFile = fopen($book, "r") or die("Permission error");
echo fread($readFile, filesize($book));
fclose($readFile);
}
}
closedir();
?>
Server response:
...Atlas_chmur.txtDiuna.txt
I used the loop so that only .txt files were opened. Currently I have this:
<?php
$path = "books/";
$books = opendir($path);
while (($book = readdir($books)) !== false)
{
echo $book;
$readFile = fopen($book, "r") or die("Permission error");
echo fread($readFile, filesize($book));
fclose($readFile);
}
closedir();
?>
Now I'm getting an error when trying to read the files.
Server response:
. Warning: fopen (.): Failed to open stream: Permission denied in C: \ xampp \ htdocs \ BooksEditorForm \ index.php on line 9 Permission error
Try this code
$path = "blog/";
$books = opendir($path);
while (($book = readdir($books)) !== false)
{
if( substr($book, -4) === ".txt" )
{
$filePath = $path.$book;
$readFile = fopen($filePath, "r") or die("Permission error");
echo fread($readFile, filesize($filePath));
fclose($readFile);
}
}
closedir();
Let me explain it...
First, occasions where you need loop inside a loop are quite rare so if your code has them, analyze it because there's a big possibility that problem can be solved differently and more efficient.
Code: value of $book is string that contains filename so simple use of substr() function to check last 4 characters will tell us is it of "*.txt" format.
Other thing that is changed is filepath; $book contains it's name but your script is looking for a file from its own perspective so file path should be containing folder + filename.
And there's no need for closing PHP tags at the end unless you have something else following it that is not PHP (like HTML).
I have used the below code. It's working well.try this code
$files = scandir('books/');
if(count($files) > 0) {
foreach ($files as $key => $value) {
echo '<pre>'; print_r($value); echo '</pre>';
// to read files data
$readFileVar = fopen ($value, "r");
while ($filedata = fgets($readFileVar)) {
print_r($filedata);
}
}
}
I'm trying to make my PHP script open more than 1 text document and to read them.
My current script is as follows:
<?php
//$searchthis = "ignore this";
$matches = array();
$FileW = fopen('result.txt', 'w');
$handle = #fopen("textfile1.txt", "r");
ini_set('memory_limit', '-1');
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
if(stripos($buffer, $_POST["search"]) !== FALSE)
$matches[] = $buffer;
}
fwrite($FileW, print_r($matches, TRUE));
fclose($handle);
}
?>
I'm trying to fopen like a bunch of files, maybe like 8 of them or less.
How would I open, and read all these files?
Any help is GREATLY appreciated!
Program defensively, check the return's from functions to ensure you are not making incorrect assumptions about your code.
There is a function in PHP to read the file and buffer it:
enter link description here
I don't know why you would want to open a lot of files, it surely will use a lot of memory, anyway, you could use the file_get_contents function with a foreach:
$files = array("textfile1.txt", "textfile2.txt", "textfile3.txt");
$data = "";
foreach ($files as $file) {
$data .= #file_get_contents($file);
}
echo $data;
There is a function in php called file which reads entire file into an array.
<?php
// "file" function creates array with each line being 1 value to an array
$fileOne = file('fileOne.txt');
$fileTwo = file('fileTwo.txt');
// Print an array or do all array magic with $fileOne and $fileTwo
foreach($fileOne as $fo) {
echo $fo;
}
foreach($fileTwo as $ft) {
$echo $ft;
}
?>
Read more about : file function ion php
I need to read the content of a single file, "test.txt", inside of a zip file. The whole zip file is a very large file (2gb) and contains a lot of files (10,000,000), and as such extracting the whole thing is not a viable solution for me. How can I read a single file?
Try using the zip:// wrapper:
$handle = fopen('zip://test.zip#test.txt', 'r');
$result = '';
while (!feof($handle)) {
$result .= fread($handle, 8192);
}
fclose($handle);
echo $result;
You can use file_get_contents too:
$result = file_get_contents('zip://test.zip#test.txt');
echo $result;
Please note #Rocket-Hazmat fopen solution may cause an infinite loop if a zip file is protected with a password, since fopen will fail and feof fails to return true.
You may want to change it to
$handle = fopen('zip://file.zip#file.txt', 'r');
$result = '';
if ($handle) {
while (!feof($handle)) {
$result .= fread($handle, 8192);
}
fclose($handle);
}
echo $result;
This solves the infinite loop issue, but if your zip file is protected with a password then you may see something like
Warning: file_get_contents(zip://file.zip#file.txt): failed to open
stream: operation failed
There's a solution however
As of PHP 7.2 support for encrypted archives was added.
So you can do it this way for both file_get_contents and fopen
$options = [
'zip' => [
'password' => '1234'
]
];
$context = stream_context_create($options);
echo file_get_contents('zip://file.zip#file.txt', false, $context);
A better solution however to check if a file exists or not before reading it without worrying about encrypted archives is using ZipArchive
$zip = new ZipArchive;
if ($zip->open('file.zip') !== TRUE) {
exit('failed');
}
if ($zip->locateName('file.txt') !== false) {
echo 'File exists';
} else {
echo 'File does not exist';
}
This will work (no need to know the password)
Note: To locate a folder using locateName method you need to pass it like folder/ with a
forward slash at the end.
Okay, I have GOT to be missing something totally rudimentary here.
I have an extremely simple use of PHP's fopen function, but for some reason, it will not open the file no matter what I do.
The odd part about this is that I use fopen in another function in the same script and it's working perfectly. I'm using the fclose in both functions. So, I know it's not a matter of a rogue file handle.
I have confirmed the file's path and the existence of the target file also.
I'm running the script at the command-line as root, so I know it's not apache that's the cause. And since I am running the script as root, I am fairly confident that permissions are not the issue.
So, what on earth am I missing here?
function get_file_list() {
$file = '/home/site/tmp/return_files_list.txt';
$fp = fopen($file, 'r') or die("Could not open file: /home/site/tmp/return_files_list.txt for reading.\n");
$files_list = array();
while($line = fgets($fp)) {
$files_list[] = $line;
}
fclose($fp);
return $files_list;
}
function num_records_in_file($filename) {
$fp = fopen( $filename, 'r' ); # or die("Could not open file: $filename\n");
$counter = 0;
if ($fp) {
while (!feof( $fp )) {
$line = fgets( $fp );
$arr = explode( '|', $line );
if (( ( $arr[0] != 'HDR' && $arr[0] != 'TRL' ) && $arr[0] != '' )) {
++$counter;
continue;
}
}
}
fclose( $fp );
return $counter;
}
As requested, here's both functions. The second function is passed an absolute path to the file. That is what I used to confirm that the file is there and that the path is correct.
Wow! Well, I figured it out.
On a whim, I decided to try trimming the file name. Apparently, it was carrying some whitespace or something at the end of the filename. So, when it tried to open the file, it couldn't due to looking for $filename +
Learn something new everyday, I guess.
I'm trying to define an array with a list of file urls, and then have each file parsed and if a predefined string is found, for that string to be replaced. For some reason what I have isn't working, I'm not sure what's incorrect:
<?php
$htF = array('/home/folder/file.extension', '/home/folder/file.extension', '/home/folder/file.extension', '/home/folder/file.extension', '/home/folder/file.extension');
function update() {
global $htF;
$handle = fopen($htF, "r");
if ($handle) {
$previous_line = $content = '';
while (!feof($handle)) {
$current_line = fgets($handle);
if(stripos($previous_line,'PREDEFINED SENTENCE') !== FALSE)
{
$output = shell_exec('URL.COM');
if(preg_match('#([0-9]{1,3}\.){3}[0-9]{1,3}#',$output,$matches))
{
$content .= 'PREDEFINED SENTENCE '.$matches[0]."\n";
}
}else{
$content .= $current_line;
}
$previous_line = $current_line;
}
fclose($handle);
$tempFile = tempnam('/tmp','allow_');
$fp = fopen($tempFile, 'w');
fwrite($fp, $content);
fclose($fp);
rename($tempFile,$htF);
chown($htF,'admin');
chmod($htF,'0644');
}
}
array_walk($htF, 'update');
?>
Any help would be massively appreciated!
Do you have permissions to open the file?
Do you have permissions to write to /tmp ?
Do you have permissions to write to the destination file or folder?
Do you have permissions to chown?
Have you checked your regex? Try something like http://regexpal.com/ to see if it's valid.
Try adding error messages or throw Exceptions for all of the fail conditions for these.
there's this line:
if(stripos($previous_line,'PREDEFINED SENTENCE') !== FALSE)
and I think you just want a != in there. Yes?
You're using $htF within the update function as global, which means you're trying to fopen() an array.
$fh = fopen($htF, 'r');
is going to get parsed as
$fh = fopen('Array', 'r');
and return false, unless you happen to have a file named 'Array'.
You've also not specified any parameters for your function, so array_walk cannot pass in the array element it's dealing with at the time.