check preg_match results against other values? - php

I need some help with my PHP script.
So, here is the deal.
I have a preg_match which checks for the following text in a .txt file that changes every 30minutes or so: LYBE_TWR,LYBE_APP,LYBA_CTR,LYPG_TWR,LYPG_APP,LYTV_TWR,LYNI_APP)
It runs perfectly and gets the above strings if they are present.
But I need to do even further and check which of the seven combinations have been found because not all are present at all times.
Example:
The current text file contains LYBE_TWR, LYBE_APP, LYPG_TWR. The preg_match does its thing and I can echo the 3 values but I need this.
LYBE_TWR : PRESENT/NOT PRESENT
LYBE_APP: PRESENT/NOT PRESENT
LYBA_CTR PRESENT/NOT PRESENT
LYPG_TWR PRESENT/NOT RESENT
etc.
So if it is found in the text file it echos present, if not it echoes not present.
The correct results would be:
LYBE_TWR : PRESENT
LYBE_APP: PRESENT
LYBA_CTR NOT PRESENT
LYPG_TWR PRESENT
If I do for example if ($string == "LYBE_TWR") { echo 'present'; } else { echo 'not present'} it will echo the correct value for the LYBE_TWR but it will say not present for the later as they are not actually the one I if-ed for.
I hope you understand as I myself am not sure anymore (rofl)
edit: here is the current code..bare in mind it is still WIP so not finished and there will be some errors http://pastebin.com/z1r4A78E
Thanks.

This is the code working on the assumption that you're interested if the string appeared in your file, not in the line. I split the strings into prefixes and suffixes, and I'm ignoring any numerical values. I didn't copy all your code, for readability's sake
$prefixes = array("LYBA", "LYBE", "LYPG", "LYNI", "LYTV");
$suffixes = array("TWR", "APP", "CTR");
foreach($prefixes as $prefix)
{
foreach($suffixes as $suffix)
{
$results[$prefix."_".$suffix] = 0;
}
}
if(preg_match('/^('.implode("|",$prefixes).'|)_[A-Z0-9]*_*('.implode("|",$suffixes).')/', $line, $matches))
{
(... your code ...)
$match_string = $matches[1]."_".$matches[2];
$results[$match_string]++;
}
foreach($results as $key => $value)
{
echo $key;
if($value > 0)
{
echo " PRESENT";
}
else
{
echo " NOT PRESENT";
}
echo "<br/>";
}

Related

Return true/false if word in URL matches specific word

I currently use:
if(strpos($command->href,§current_view) !== false){
echo '<pre>true</pre>';
} else {
echo '<pre>false</pre>';
}
$command->href will output something like this: /path/index.php?option=com_component&view=orders Whereas
§current_view is outputting orders. These outputs are dynamically generated, but the scheme will always be the same.
What I need to do is return true/false if the words from $current_view match the view=orders in the URLs from $command->href. The issue with my code is, that it doesnt match anything.
What is the correct way to do this?
Please note that the $command->href and the whole code is inside a while function, that pass multiple URLs and this only needs to match the same ones.
Breaking it down to a simple example, using your code and variable values.
$current_view = 'orders';
$command = '/path/index.php?option=com_component&view=orders';
if(strpos($command,$current_view) !== false){
echo '<pre>true</pre>';
}
else {
echo '<pre>false</pre>';
}
The oputput is "true".
Now, go and debug the REAL values of $command->href and $current_view...
I'm pretty confident that the values are not what you think they are.
Does something like:
if(substr($command->href, strrpos($command->href, '&') + 6) == $current_view)
accomplish what you are after?
To explain, strpos get the last instance of a character in a string (& for you, since you said it always follows the scheme). Then we move over 6 characters to take "&view=" out of the string.
You should now be left with "orders" == "orders".
Or do you sometimes include some arguments after the view?
Try parsing url, extracting your view query string value and compare it to $current_view
$query= [];
parse_str(parse_url($command->href)['query'], $query);
if($current_view === $query["view"])
echo '<pre>true</pre>';
} else {
echo '<pre>false</pre>';
}

get all categories listing from database

Main purpose is to get all categories listing from database by passing variables to url and show it to the main page.here i have omitted some code bt i tried to clarify.
1.can I exclude encodeHtml() method, too difficult for me to understand
2.i am not getting specially this part of code and having my head for 4 days
foreach($cats as $cat) {
echo "<li><a href=\"/?page=catalogue&category=".$cat['id']."\"";//here id is 'category id' from database. this full line will echo what?
echo Helper::getActive(array('category' => $cat['id']));//it will output what ?
echo ">";
echo Helper::encodeHtml($cat['name']);//as from ur answer can we omit encodeHTML() method and use htmlspecialchars($cat['name']); instead ?
echo "</a>
3.any easier solution will be more appreciated
in our database we have 'id' and 'name' of catagory listing
please check below for reference
/*below is the code in header section of template */
<?php
$objCatalogue = new Catalogue();// creating object of Catalogue class
$cats = $objCatalogue->getCategories(); // this gets all categories from database
<h2>Categories</h2>
<?php
foreach($cats as $cat) {
echo "<li><a href=\"/?page=catalogue&category=".$cat['id']."\"";
echo Helper::getActive(array('category' => $cat['id']));
echo ">";
echo Helper::encodeHtml($cat['name']);
echo "</a></li>";
}
?>
/*below is the helper class which is Helper.php */
public static function getActive($page = null) {
if(!empty($page)) {
if(is_array($page)) {
$error = array();
foreach($page as $key => $value) {
if(Url::getParam($key) != $value) //getParam takes name of the parameter and returns us the value by $_GET
{
array_push($error, $key);
}
}
return empty($error) ? " class=\"act\"" : null;
}
}
//CHECK THIS LINE BROTHER
return $page == Url::currentPage() ? " class=\"act\"" : null;// url::currentPage returns the current page but what is 'class =act ' :(
}
public static function encodeHTML($string, $case = 2) {
switch($case) {
case 1:
return htmlentities($string, ENT_NOQUOTES, 'UTF-8', false);
break;
case 2:
$pattern = '<([a-zA-Z0-9\.\, "\'_\/\-\+~=;:\(\)?&#%![\]#]+)>';
// put text only, devided with html tags into array
$textMatches = preg_split('/' . $pattern . '/', $string);
// array for sanitised output
$textSanitised = array();
foreach($textMatches as $key => $value) {
$textSanitised[$key] = htmlentities(html_entity_decode($value, ENT_QUOTES, 'UTF-8'), ENT_QUOTES, 'UTF-8');
}
foreach($textMatches as $key => $value) {
$string = str_replace($value, $textSanitised[$key], $string);
}
return $string;
break;
}
}
Firstly, in your URL (/?page=catalogue&category=) you don't need to put &, as this is an HTML entity for actually displaying an ampersand in a web page. Just use /?page=catalogue&category=.
Secondly, you can use urlencode() to prepare strings for sending in the URL, and urldecode() on the other end.
In answer to your first point you just need to make sure that ANYTHING from the user (whether via $_POST or $_GET) is sanitized, prior to being used in code, output to a web page, or used in database queries. Use htmlspecialchars() for cleaning before outputting to a web page, and prepared statements prior to entering user input into a query.
In answer to your second point please read the documentation in the links I have provided above. Just reading the documentation on htmlspecialchars() will help you a lot.
Hope this helps.
Alright then.
<?php
foreach($cats as $cat) {
echo "<li><a href=\"/?page=catalogue&category=".$cat['id']."\"";
echo Helper::getActive(array('category' => $cat['id']));
echo ">";
echo Helper::encodeHtml($cat['name']);
echo "</a></li>";
}
?>
Im just going to kindof skim through it, because honestly if you really want to learn all this you should probably google the shit out of every piece of code you don't understand, it's the way we all learn things.
< ?php announces some php script to follow. And as you can see, there does follow some php code after.
foreach is a way of getting each element from an array or list and doing something to that element.
echo sends whatever string comes after it to the page, or whatever is listening to its output. In this case, it looks like the echo's are printing some <li> list item with an <a> anchor in it.
Helper::getActive(): Helper is some class that is defined somewhere, :: is syntax for calling a static function that belongs to the class (Helper in this case). getActive is the function name.
array('category' => $cat['id'] is a piece of code that creates an array with 1 element in it, being one with key 'category' and a value of whatever is in $cat['id'].
By looking at getActive: it looks like it's a function that checks the url for some value so it can determine which page to display. It also checks if the url contains errors.
By lookingat encodeHtml(): it looks like it's a function that makes sure that whatever text you're trying to put on the screen, isn't something that could cause harm. In some situations, people will try to make your server print javascript that could harm the user (by sending personal data to somewhere). The encodeHtml() will ensure that no such thing can be done by stripping certain characters from the text you're about to send to the page.
USE GOOGLE.

Checking Users HTML form input with PHP

I am creating a web application that takes in a user input (Scientific Paper DOI) and queries a database to display a graph. I've been trying to limit the connections made to the database since its on a remote server (private DMZ with web server) by checking the user input if it matches a correct DOI.. if it doesn't then no connection to the database will be made, I hope this will help speed up the application if there are many users at once making queries.
Pseudo: All paper DOIs start with "10.1103/" because they are all physics papers. This part I have implemented correctly using substr. Next I want to check every character in the input to make sure it only consists of only these characters:
Letter
Number
"/"
"."
Example DOIs:
10.1103/RevModPhys.9.1
10.1103/RevModPhys.76.1015
10.1103/PhysRevLett.95.208304
Here is my code:
function checkDOI($doi) {
if (substr($doi, 0, 8) != "10.1103/") {
echo "Invalid DOI";
return false;
}
for ($n = 0; $n < strlen($doi)+1; $n++) {
if ( !ctype_alnum($doi[n]) && $doi[n] != "." && $doi[n] != "/") {
echo "Invalid DOI";
return false;
}
}
echo "Valid DOI";
return true;
}
if(isset($_POST['submit'])) {
$doi_input = $_POST['doi_input'];
checkDOI($doi_input);
}
I am working with PHP and javascript for the very first time, the pseudo is fairly simple but for some reason, there is something wrong with the 2nd if statement. Not sure if I can really do that. The Echos are just for tests.
Do you think doing this check for every input will slow down the application significantly? Is it worth it to limit the amount of connections to mysql?
The bottom of the code will be modified once I have this working to only query the database if checked returns true.
Thanks for the help!
to check every character in the input to make sure it only consists of only these characters
I suggest you to use preg_match.Try this:
$value="10.1103/RevModPhys.9.1";
if(preg_match("/^[a-zA-Z0-9\/.]+$/", $value)){
echo "match found";
}else{
echo "no match found";
}
Check here: Demo
For more info: preg_match
Your error is $doi[n], it is not an array and should it be the index is invalid.
So use a function like
$chars_doi = str_split($doi);
Before the loop to get an array of characters then use in your loop
$chars_doi[$n]
So you should have something like:
$chars_doi = str_split($doi);
$size = sizeof($chars_doi) - 1;
for ($n = 0; $n < $size; $n++) {
if (!ctype_alnum($chars_doi[$n]) && $chars_doi[$n] != "." && $chars_doi[$n] != "/") {
echo "Invalid DOI";
return false;
}
}
Little tip, avoid use functions such as strlen / sizeof as a loop argument or it will get called at each iteration. It is better for performance to store the value in a variable beforehand.
I would just do:
if (! preg_match ('#^10\.1103/[\p{L}\p{N}.-_]+$#', $doi)) {
... // bad
return;
}
// good
Reference:
http://www.php.net/manual/en/reference.pcre.pattern.syntax.php
http://php.net/manual/en/regexp.reference.unicode.php

PHP in_array() does not find content that is in an array

i have a very simple script that reads out a txt file, puts the content in an array.
Which does perfectly, i can do print_r($array); and it outputs all the data.
My script:
<?php
$file = 'countries.txt';
$countries_output = file_get_contents($file);
$countries_pieces = explode("\n", $countries_output);
if (in_array("Sweden", $countries_pieces)) {
echo "Sweden was found";
}
else
{
echo'NOT FOUND';
}
print_r($countries_pieces);
?>
I don't understand why it doesn't find the value 'Sweden' in my array, when it clearly is in there.
This is the output: https://pastebin.com/z9rC9Qvk
I also print_r the array, so you can see that 'Sweden' is indeed in the array.
Hope someone can help :)
There is most likely new line characters that you're not taking into account. The following is a cleaner solution using file() and should work for you:
$file = 'countries.txt';
$countries_pieces = file($file, FILE_IGNORE_NEW_LINES);
if (in_array("Sweden", $countries_pieces)) {
echo "Sweden was found";
} else {
echo'NOT FOUND';
}
If there are still some issues, a common normalization is to trim() values to remove some left-overs:
$countries_pieces = array_map('trim', $countries_pieces);
But this must not cure all issues.
Is countries.txt from a Windows machine? If so, splitting on '\n' won't work very well since there's also a '\r' for every line.
Your print_r output would seem to indicate that since there seems to be an extra newline between every line of output.

PHP nextLine with String

I wrote a php search script on my site for checking to see if a package exists in a text file or not (I used file_get_contents.) It takes what the user entered and combines it with the string 'BUILD: ' Below is an example of the file and I'll explain in the paragraph following it:
BUILD: packageA
URL: www.package-a.com
BUILD: packageB
URL: www.package-b.com
BUILD: packageC
URL: www.package-c.com
So if a user were to search "packageB", it would be combined with "BUILD: " making the variable I'm testing with have the value: "BUILD: packageB". I have a conditional saying if that string exists or not; everything's working good on that end.
My question/problem is how can I list the URL: line beneath it with an echo? I've been testing some ideas with strlen() and I can't seem to get it and the text file has different strlens for entry. Is there a way to make PHP force a "nextLine()" if there is such a thing... does PHP recognize return delimits?
Thank you!
// The string you are searching for
$package = 'packageB';
// Get the file into an array
$data = file('myfile.txt');
// Loop the data
for ($i = 0, $found = FALSE; isset($data[$i]); $i++) {
if (trim($data[$i]) == "BUILD: $package") { // We found the one we're looking for
echo trim($data[++$i]); // Echo the next line
$found = TRUE;
break; // Stop looping
}
}
if ($found) {
echo "<br />\nI found the URL on line $i";
} else {
echo "I didn't find it!";
}
file() gets the file data as an array where each element is one line of the file, unlike a single string like file_get_contents() returns.
You can do a regex with the /m modifier which makes it match across multiple lines, then use a parenthesized pattern to capture the line following the match:
if (preg_match_all('/BUILD: packageB\n(.+)\n/m', file_get_contents('file.txt'), $match)) {
foreach ($match[1] as $match) {
echo "$match\n";
}
}
Outputs:
URL: www.package-b.com
If you are open to alternative methods, then here is a simpler/faster solution.
builds.php
<?php
$builds=array("packageA"=>"www.package-a.com",
"packageB"=>"www.package-b.com",
"packageC"=>"www.package-c.com",
"packageD"=>"www.package-d.com");
?>
OtherScript.php
<?php
if(isset($_POST['package'])){
include('./builds.php');
if(array_key_exists($_POST['package'], $builds)){
$notice="You Selected: ".$_POST['package']." Url:".$builds[$_POST['package']];
}else{
$notice="Package Not Found";
}
}
echo (isset($_POST['package']))?$notice:'';
?>

Categories