PHP Validate Value $_GET from url against lines of a txt file - php

i have a problem i couldn't figure out since im self-taught and still exploring the php world
so i have a text file that looks like this:
951753159
456787541
123156488
748651651
and i got an url with a variable
http://example.com/mypage.php?variable=951753159
what i want is to check if the url variable matches one of the txt file lines in order to execute a code
i already tried this
$search = $_GET["variable"];
$file = "variables.txt";
if (preg_match('/^' . $search . '$/m', file_get_contents($file))) {
THE CODE THAT I WANT TO EXECUTE
}
but for some reason it matches the whole content of the file
any help is highly appreciated
Thanks in advance :)

Try with an array from file():
$lines = file("variables.txt", FILE_IGNORE_NEW_LINES);
if(in_array($_GET["variable"], $lines)) {
// YES FOUND
} else {
// NOT FOUND
}

From the documentation on `file_get_contents', the entire contents of the file are read as a string. So that is why it is matching against the entire file.
The command that you want to use is file, this reads the file into an array of each line.

I would
Use file to read the file into an array.
Then array_flip the array so that it's values are now the keys
Which allows me to isset($array[$key])

You can do this.
<?php
#$search = $_GET["variable"];
$search = '123156488';
$file_txt = "content.txt";
$file = file($file_txt);//convert the txt in array
foreach ($file as $key => $value) {
if (trim($search) == trim($value)) {
print "DO something! " . $value;
}
}?>
Regards.
Nelson.

Related

How Can I Remove An Index From An Array and Echo It Out?

In PHP I am trying to have it so the user can insert an array of an index that they want removed and then it will echo out that array without the array that they didn't want. Right now the troublesome part of my code for the main file is
include("/opt/lampp/htdocs/upload/styles/styles.php");
if ($_SERVER['REQUEST_METHOD'] == "POST") {
//this is the content of the array that the user wants gone//
$want = $_POST['which'];
$file = fopen("/opt/lampp/htdocs/upload/styles/styles.php", "a");
if (in_array($want, $allStyles)) {
$index = array_search($want, $allStyles);
fwrite($file, " unset(\$allStyles[$index]);");
fclose($file);
echo implode(", ", $allStyles);
} else {
echo "error";
}
}
styles.php is
<?php
$allStyles[] = 'one';
$allStyles[] = 'all';
If I insert "all" for $want it will unset the array where it contains "all" and if I do
php styles.php
in my linux terminal it will only echo out "one" but if I do this on my page on my web browser it will echo out both strings. How can I make it so it will only echo the array that wasn't asked to be removed?
not sure if I understood your problem (or what you want to achieve) properly but, try this code:
$file='/opt/lampp/htdocs/upload/styles/styles.php';
include($file);
if(isset($_POST['which'])){
$want=$_POST['which'];
if(in_array($want,$allStyles)){
$index=array_search($want,$allStyles);
unset($allStyles[$index]);
file_put_contents($file,$allStyles);
}else{
echo "error";
}
}
You only want to change the file if $_POST['which'] is set, not on every POST action, I guess.
You just search the index (like you already did the right way) then unset it (what was wrong in your code, I guess) then you write it (file_put_contents() makes the code a bit more readable).
Last thing: I've moved the path to the file in $file in order to make it more maintainable

How to change all values in a column of a csv file to a specific value php

I have a csv file that looks something like this (there are many more rows):
Jim,jim#email.com,8882,456
Bob,bob#email.com,8882,343
What I want to do is to change all the values in the fourth column,456,343 to 500.
I'm new to php and am not sure how to do this.
I have tried
<?php
$file = fopen('myfile.csv', 'r+');
$toBoot = array();
while ($data = fgetcsv($file)) {
echo $data[3];
$data[3] = str_replace($data[3],'500');
array_push($toBoot, $data);
}
//print_r($toBoot);
echo $toBoot[0][3];
fputcsv($file, $toBoot);
fclose($file)
?>
But it prints
Jim,jim#email.com,8882,456
Bob,bob#email.com,8882,343
Array,Array
not
Jim,jim#email.com,8882,500
Bob,bob#email.com,8882,500
I've looked at this post, PHP replace data only in one column of csv but it doesn't seem to work.
Any help appreciated. Thanks
You can use preg_replace and replace all values at once and not loop each line of the CSV file.
Two lines of code is all that is needed.
$csv = file_get_contents($path);
file_put_contents($path, preg_replace("/(.*),\d+/", "$1,500", $csv));
Where $path is the path and to the CSV file.
You can see it in action here: https://3v4l.org/Mc3Pm
A quick and dirty way to way to solve your problem would be:
foreach (file("old_file.csv") as $line)
{
$new_line = preg_replace('/^(.*),[\d]+/', "$1,500", $line);
file_put_contents("new_file.csv", $new_line, FILE_APPEND);
}
To change one field of the CSV, just assign to that array element, you don't need to use any kind of replace function.
$data[3] = "500";
fputcsv() is used to write one line to a CSV file, not the entire file at once. You need to call it in a loop. You also need to go back to the beginning of the file and remove the old contents.
fseek($file, 0);
ftruncate($file, 0);
foreach ($toBoot as $row) {
fputcsv($file, $row);
}

PHP function GLOB: get and modify the results

I'm trying to import many xml files that I do not know the name.
I use this code:
foreach(glob('OLD/*.xml') as $file) {
$url= basename($file) . ', ';
$all_urls = array($url);
foreach ($all_urls as $url) {
$xml = simplexml_load_file($url);
I have a lot of files like agency.xml, annunci_324.xml, annunci_321.xml, ecc...
I only need the files that begin for annunci and end .xml. I also need to delete last value's comma and put it in the last foreach. how can i do it?
I think you can check if name contains annunci with strstr function (documentation here)
if(strstr($file, 'annunci')
{
//we found a file with name we are interessed in.
Now you can build directly your array without caring about commas
$all_urls = array();
foreach(glob('OLD/*.xml') as $file)
{
if(strstr($file, 'annunci')
{
$all_urls[] = array(basename($file));
}
}
This way we have all_urls as array of all the files starting with annunci and you can loop in it to simple_load them all.

php check if file exist: check only portion

in php we can check if file exist using
if(file_exists("destination/"))
{
condition
}
but what I wanted to do is...
for example I already have this file on my destination
hello_this_is_filename(2).doc
how would I know if there is a file in that directory having a name containing a character
hello_this_is_filename
I wanted to search that way because... if there is exists on that directory, what will I do is... renaming the file into
hello_this_is_filename(3).doc
I also need to count the existence of my search so I know what number I'm going to put like
(3), (4), (5) and so on
any help?
Use glob.
if (count(glob("destination/hello_this_is_filename*.doc"))) {
//...
}
Leveraging Marc B's suggestion and xdazz, I would do something as follows:
<?php
$files = glob("destination/hello_this_is_filename*");
if (count($files)) {
sort($files);
// last one contains the name we need to get the number of
preg_match("([\d+])", end($files), $matches);
$value = 0;
if (count($matches)) {
// increment by one
$value = $matches[0];
}
$newfilename = "destination/hello_this_is_filename (" . ++$value . ").doc";
?>
Sorry this is untested, but thought it provides others with the regexp work to actually do the incrementing...

searching a line in a txt file

I have a txt file in the server and it contains lines sth like that
one
two
three
four
five
i want to make a function that checks if a word exists in these lines.
any help is appreciated.
thank you
Here is how you may proceed with it:
$contents = file_get_contents('yourfile.txt');
$search_keyword = 'four';
// check if word is there
if (strpos($contents, $search_keyword) !== FALSE){
echo "$search_keyword was found !!";
}
else{
echo "$search_keyword was NOT found !!";
}
Does this really need to be done in php? You've just described the UNIX grep utility.
You could do it like:
$data = file($path_to_file,FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if (in_array($data,'word')) {
// do something
}
That is a simple hack but it should work.

Categories