Sending match from preg_replace to scandir inside function - php

I'm having issues using scandir with a variable sent through a function from preg_replace. I'm getting warning when I run the code PHP Warning: scandir(../dir/$1): failed to open dir: No such file or directory, however, when I echo $dir it echos it correctly with $1 expanded to the variable. Here's my code:
$str = preg_replace('/([0-9]{2})/', $this->functionName("$1"), $str);
private function functionName($year) {
$path = '../dir/'.$year;
echo $path; // echos 'dir/14'
$results = scandir($path); // claims $path is 'dir/$1'
}

Related

Search all files in directory PHP

I'm trying to search all of the files in a directory instead of one, but I don't know what to use to do that.
results.php:
<?php
// error_reporting(E_ERROR | E_PARSE);
$file = 'db/test.txt';
$searchfor = $_GET['q'];
if (!$_GET['q']) { // returns this if query is empty
echo "Search something.";
}
else {
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if (preg_match_all($pattern, $contents, $matches))
{
echo "<centerResults</center><br>";
echo "<pre>";
echo implode($matches[0]);
echo "</pre>";
}
else
{
echo "<center>No results</center>";
}
}
I wanted to do something like this on line 3:
$file = 'db/*';
So that it could search through test.txt, and other txt files in that directory.
And i've tried googling, and nothing helpful has come up, any help?
Ther is function called glob it accept a required parameter which is the path and it can be a pattern of the files and it return an array of the paths of all the files that match that pattern .
in other words , you can use this function with "dir/*.txt" and it is going to return all the files that ar in the dir folder and has the txt extension

Regex to not match ._filename.php files

MAC OSX creates some unwanted dot underscore files to store file information.
There are currently two files in a directory on my file system - Test.php and ._Test.php.
I need to write a preg_match to accept only first file and ignore the metadata file. For eg.
preg_match('/^(.+)\.php$/', $fileName, $matches);
But, here $matches returns the same output for both $fileName = Test.php and ._Test.php.
Is there anyway to modify the regex to ignore the metadata file and accept only Test.php?
Use a negative lookahead to assert that the string doesn't start with ._:
^(?!\._)(.+)\.php$
Demo
PHP sample
<?php
$tests[] = "Test.php";
$tests[] = "._Test.php";
$tests[] = ".Testing.php";
$tests[] = "_Testing2.php";
$tests[] = "._greajo.com";
$tests[] = "_.greajo.com";
foreach ($tests as $test) {
if (preg_match("/^(?!\._)(.+)\.php$/i", $test, $m)) {
echo "Valid file: ".$m[1].PHP_EOL;
}
else {
echo "Invalid file".PHP_EOL; // discard?
}
}
Demo
Result
Valid file: Test
Invalid file
Valid file: .Testing
Valid file: _Testing2
Invalid file
preg_match('/^[^\.].*\.php$/', $fileName, $matches);
See demo https://implode.io/evnXDC

replace deprecated function in many php file with new function

I had used this function-----> import_request_variables('p') in more than 50 php files with this function --> extract($_GET, EXTR_PREFIX_ALL, 'p'); is there and php script can do this job without opening each file
I want something like this :
//read the entire string
$str=implode("",file('../*.php'));
$fp=fopen('../*.php','w');
//replace something in the file string, here i am replacing import_request_variables('p') to extract($_GET, EXTR_PREFIX_ALL, 'p')
$str=str_replace('import_request_variables('p')','extract($_GET, EXTR_PREFIX_ALL, 'p')',$str);
//now, save the file
fwrite($fp,$str,strlen($str));
this code may help you!
foreach (glob("path/to/files/*.php") as $filename)
{
$file = file_get_contents($filename);
file_put_contents($filename, str_replace("import_request_variables('p')","extract($_GET, EXTR_PREFIX_ALL",$file));
}

Batch download URLs in PHP?

So, I have a PHP script that is supposed to download images that the user inputs. However, if the user uploads a TXT file and it contains direct links to images, it should download the images from all the URLs in the file. My script seems to be working, although it seems that only the last file is downloaded while the others are stored as files containing no data.
Here's the portion of my script where it parses the TXT
$contents = file($file_tmp);
$parts = new SplFileObject($file_tmp);
foreach($parts as $line) {
$url = $line;
$dir = "{$save_loc}".basename($url);
$fp = fopen ($destination, 'w+');
$raw = file_get_contents($url);
file_put_contents($dir, $raw);
}
How do I make it download every URL from the TXT file?
When you iterate over an SplFileObject, you get the whole line, including whitespace. Your URL will thus be something like
http://example.com/_
(php seems to mangle the newline to an underscore) and thus you'll get an error for many URLs (some URLs will still work fine, since they contain the important information prior. For instance, Batch download URLs in PHP? works, but https://stackoverflow.com/_ does not). If an error occurs, file_get_contents will return false, and file_put_contents will interpret that like an empty string.
Also, the line $fp = fopen ($destination, 'w+'); is really strange. For one, since $destination is not defined, it would error anyways. Even if $destination is defined, you'll end up with lots of file handles and overwrite that poor file multiple times. You can just remove it.
To summarize, your code should look like
<?php
$file_tmp = "urls.txt";
$save_loc = "sav/";
$parts = new SplFileObject($file_tmp);
foreach($parts as $line) {
$url = trim($line);
if (!$url) {
continue;
}
$dir = "{$save_loc}".basename($url);
$raw = file_get_contents($url);
if ($raw === false) {
echo 'failed to donwload ' . $url . "\n";
continue;
}
file_put_contents($dir, $raw);
}
It looks like line
$parts = new SplFileObject($file_tmp);
isn't necessary as well as
$fp = fopen ($destination, 'w+');
file() function reads entire file into array. You just have call trim() on each array element to remove new line from characters. Following code should work properly:
<?php
$save_loc = './';
$urls = file('input.txt');
foreach($urls as $url) {
$url = trim($url);
$destination = $save_loc . basename($url);
$content = file_get_contents($url);
if ($content) {
file_put_contents($destination, $content);
}
}

PHP Having problems with find and replace in LARGE CSV

I am writing a PHP script so that I can do a find and replace in a large CSV file. I wrote this script:
// FIND AND REPLACE
$sourcePath = 'custom.csv';
$tempPath = $sourcePath . 'temp';
$source = fopen($sourcePath, 'r');
$target = fopen($tempPath, 'w');
while(!feof($source)) {
$line = preg_replace ("village", "village/",fgets($source));
fwrite($target, $line);
}
fclose($source);
fclose($target);
unlink($sourcePath);
rename($tempPath, $sourcePath);
But I am getting these errors,
Warning: feof() expects parameter 1 to be resource, boolean given
Warning: fgets() expects parameter 1 to be resource, boolean given
Warning: preg_replace(): Delimiter must not be alphanumeric or backslash
$source = fopen($sourcePath, 'r'); isn't returning what you think it is.
It's likely returning false, which typically happens when PHP can't find the file at the path you provided. If you're certain the file exists, you should confirm that the user executing the script has the proper permissions to read the file.
You're second issue regarding preg_replace() is being caused by not using delimiters. They are needed in the first argument.
$line = preg_replace ("/village/", "village/",fgets($source));
However, regular expressions aren't needed with this simple of a replacement. You should instead use str_replace() and the script should run faster.
Your code should look like this:
<?php
$sourcePath = 'custom.csv';
$tempPath = $sourcePath . 'temp';
$source = fopen($sourcePath, 'r');
$target = fopen($tempPath, 'w');
if($source){
while(!feof($source)) {
$line = str_replace("Village\\", "Village",fgets($source));
fwrite($target, $line);
}
} else {
echo "$sourcePath not found, or using the wrong permissions.";
}
fclose($source);
fclose($target);
unlink($sourcePath);
rename($tempPath, $sourcePath);
?>
You are not checking if fopen is actually returning a file pointer resource or a false result. It is likely returning false and throwing the warning that a boolean is provided.
Also, you could use:
$line = str_replace("village", "village/", fgets($source));

Categories