How to make this search engine work with subsrt_count? - php

So, i've been working on making a search engine without the use of a database. What it's supposed to do is find the word searched for in the webpage and automatically give it's link. Here's it's code:
<?php
session_start();
$searchInput = $_POST['search'];
$inputPage1 = $_SESSION['pOneText'];
$inputPage2 = isset($_SESSION['pTwoText']) ? $_SESSION['pTwoText'] : "";
$inputPage3 = isset($_SESSION['pThreeText']) ? $_SESSION['pThreeText'] : "";
$fUrl = file_get_contents("mDummyP.php");
$sUrl = file_get_contents("sDummyP.php");
$tUrl = file_get_contents("tDummyP.php");
if (substr_count($fUrl, $searchInput) !== false) {
echo "All results for <strong> $searchInput </strong> : <br>" ;
} elseif (substr_count($sUrl, $searchInput) !== false) {
echo "All results for <strong> $searchInput </strong> : <br>";
} elseif (substr_count($tUrl, $searchInput) !== false) {
echo "All results for <strong> $searchInput </strong> : <br>";
} else {
echo "No resulst for <strong> $searchInput </strong>! ";
}
?>
However, it never checks if the word actually exists or not, it always returns "all results for". So, i was wondering if anyone knew why or had suggestions to improve it. Keep in mind that it will never be used professionally, it's just to test my abilities. Thanks in advance!

You need to look at the php manual for substr_count
Return Values
This function returns an integer.
Thus it will ALWAYS go into this first if block:
if (substr_count($fUrl, $searchInput) !== false) {
because the return value of substr_count is only ever an integer and is NEVER going to be false - your code is checking for the exact value and type of false.
Furthermore, apart from the else block, all of the statements are just echo'ing the exact same string so you will not see any differentiation of output if execution did go into the if or elseif blocks. See below to get you on the right track:
$searchInput = 'some';
$fUrl = 'this is test file text';
$sUrl = 'this is some other text';
$tUrl = 'extra text';
if (substr_count($fUrl, $searchInput) !== 0) {
echo "a";
} elseif (substr_count($sUrl, $searchInput) !== 0) {
echo "b";
} elseif (substr_count($tUrl, $searchInput) !== 0) {
echo "c";
} else {
echo "No resulst for <strong> $searchInput </strong>! ";
}

Related

Using empty() to adjust output with multiple variables

I have two primary variables that are composed of strings and other variables. I want the two primary variables only to be echo'ed if all the variables that they are comprised of have data.
The two primary variables are $introduction and colortxt.
$introduction is comprised of $finalvehicle3, $bodystyle, $mileage, and $hi.
$colortxt is comprised of $model, $exterior, and $interiorspec.
If any of the secondary variables are empty, I don't want the primary variable to be displayed.
Below is the code I have created that doesn't seem to be working. I have been using empty().
My PHP:
<?php
$finalvehicle3 = "Toyota Camry";
$bodystyle = "sedan";
$mileage = "30,000";
$hi = null;
$model = "Camry";
$exterior = "red";
$interiorspec = "black cloth";
if (empty([$finalvehicle3, $bodystyle, $mileage, $hi]) == true){
$introduction = "";
}
else {
$introduction = "I am pleased to present this ".$finalvehicle3." ".$bodystyle." with ".$mileage." miles.";
}
if (empty([$model, $exterior, $interiorspec]) == true){
$colortxt = "";
}
else {
$colortxt = "This ".$model." is finished in ".$exterior." with a ".$interiorspec. " interior.";
}
echo "<textarea name='' id='' style='width: 565px;' rows='8' cols='60'>";
echo $introduction." ".$colortxt;
echo "</textarea>";
echo "<br><br>";
?>
In this case $introduction should not be displayed as $hi = null
I can't get empty([$finalvehicle3, $bodystyle, $mileage, $hi]) to work.
I was able to use:
if (empty($hi)
|| empty($finalvehicle3)
|| empty($bodystyle)
|| empty($mileage)){
$introduction = "";
}
else {
$introduction = "I am pleased to present this ".$finalvehicle3." ".$bodystyle."
with ".$mileage." miles.";
}
Will that not work?
Check if both variables are not empty echo them out:
if (!empty($introduction) && !empty($colortxt)) {
echo $introduction." ".$colortxt;
}
As a side, while coding style has personal preference, where you set these variables seems awkward as you set them to empty based on a condition, but logically (my logical at least) is to instead preset them to empty and add data if the data exists.
INSTEAD of your code here:
if (empty([$finalvehicle3, $bodystyle, $mileage, $hi]) == true){
$introduction = "";
}
else {
$introduction = "I am pleased to present this ".$finalvehicle3." ".$bodystyle." with ".$mileage." miles.";
}
if (empty([$model, $exterior, $interiorspec]) == true){
$colortxt = "";
}
else {
$colortxt = "This ".$model." is finished in ".$exterior." with a ".$interiorspec. " interior.";
}
Do this:
$introduction = "";
$colortxt = "";
if (!empty([$finalvehicle3, $bodystyle, $mileage, $hi]) == true) {
$introduction = "I am pleased to present this ".$finalvehicle3." ".$bodystyle." with ".$mileage." miles.";
}
if (!empty([$model, $exterior, $interiorspec]) == true) {
$colortxt = "This ".$model." is finished in ".$exterior." with a ".$interiorspec. " interior.";
}
Just looks cleaner to me :)
I'd also not create a new array to check multiple variables, and would do:
if (
!empty($finalvehicle3)
&& !empty($bodystyle)
&& !empty($mileage
&& !empty($hi)
) {
To clarify (not intended to take away from the other answers); only isset() can accept multiple comma-separated values, and not empty().
The manuals state:
on empty():
bool empty ( mixed $var )
on isset()
bool isset ( mixed $var [, mixed $... ] )
Therefore you need to separate and check if each value is empty.
I.e.:
if(empty($var1)) && empty($var2)){}
Or using the || (OR) logical operator depending on what you want to check for; if any or all are empty.
http://php.net/manual/en/language.operators.logical.php
Note:
What you used here:
if (empty([$finalvehicle3, $bodystyle, $mileage, $hi]) == true)
theoretically would be a "false positive".
If anything, you will need to use the == true in a separate statement.
I.e.:
if(empty($var1)) && empty($var2) && $x_var == true){}
However, the first 2 would need the ! negation operator since you're checking if something is true.
I.e.:
if(!empty($var1)) && !empty($var2) && $x_var == true){}

How can I check if all variables meet the requirements to put data into file?

I need to check if all variables meet the requirements if they do proceed with file handling.
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$s_id = $_POST['student_id'];
$tuition = $_POST['tuition'];
$payment = $_POST['payment'];
//Checking for Errors
if ($_SERVER["REQUEST_METHOD"] == "POST"){
//Checking Values
echo '<ul class="error">';
if(strlen($fname)<2){
echo '<li>'."First name must be 2 or more characters in length".'</li>';
}
if(strlen($lname)<3 || strlen($lname)>12){
echo '<li>'."Last name must be between 3 and 12 characters in length".'</li>';
}
if(strlen($s_id)!=9){
echo '<li>'."Student id must be exactly 9 characters in length".'</li>';
}
if($tuition < 2000 || $tuition > 10000){
echo '<li>'."Tuition must be between 2000 and 10000".'</li>';
}
echo '</ul>';
This parts work as it should it reports what errors have been encountered. Following this I need to make sure that all values are correct if they are output the success message and put data into file.
//Success
if($fname == true && $lname == true && $s_id == true && $tuition == true){
echo '<ul class="success">';
echo '<li>'."Payment Successful!".'</li>';
echo '</ul>';
//File Handling
$line = array($fname, $lname, $s_id, $tuition, $payment); //Creates a line to append to the file.
$handle = fopen("log.txt", "a+"); //Open for reading and writing; place the file pointer at the end of the file.
fputcsv($handle, $line); //Puts the values into the file.
fclose($handle); //Close the file.
}
}
I'm having problem checking if all variable meet the requirements I'm using if($fname == true && $lname == true && $s_id == true && $tuition == true), but it seems to go though even with errors. What exactly am I doing wrong?
A solution would be an approach like this:
$problems = [];
if(strlen($fname)<2){
$problems[] = "First name must be 2 or more characters in length";
}
if(strlen($lname)<3 || strlen($lname)>12){
$problems[] = "Last name must be between 3 and 12 characters in length";
}
if(strlen($s_id)!=9){
$problems[] = "Student id must be exactly 9 characters in length";
}
if($tuition < 2000 || $tuition > 10000){
$problems[] = "Tuition must be between 2000 and 10000";
}
if (count($problems)) {
echo '<ul class="error">';
foreach ($problems as $problem) {
echo '<li>'.$problem.'</li>';
}
echo '</ul>';
}
if (empty($problems)) {
// Success action here
}
That would make a list of all problems, print them if there are problems, and do the success action if there are no problems.
When you'd use a framework, printing the list would be done in a separate file called a "view", which would separate the html from the validation logic even further.
Edit: "it seems to go though even with errors. What exactly am I doing wrong?"
In this case, I'd argue you're not the only one doing something wrong. If I were PHP, I'd do the opposite: not letting anything through, even without errors.
Here's what happens:
Let's say $fname is "E". That's not valid input.
You ask PHP if $fname is true. That means asking if "E" is true.
PHP argues that "E" seems true enough.
A similar thing happens for all of the parameters. Only a completely empty $fname is denied. For the tuition, PHP only denies free courses.
The reason this happens is because PHP is "weak typed".
Most other languages would simply conclude that "E" is not exactly the same as true, and therefore deny the input. Then again, they would also conclude that "real_file_name.txt" is not exactly the same as true, and also deny the input you'd consider valid.
i advise you to work with isset(var) example of the code and make var $valid to check if conditions are true , i hope this could helps you :
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$s_id = $_POST['student_id'];
$tuition = $_POST['tuition'];
$payment = $_POST['payment'];
$valid="";
if (isset($fname, $lname, $s_id, $tuition, $payment)) {
$valid="1";
echo '<ul class="error">';
if(strlen($fname)<2){
echo '<li>'."First name must be 2 or more characters in length".'</li>';
$valid="0";
}
if(strlen($lname)<3 || strlen($lname)>12){
echo '<li>'."Last name must be between 3 and 12 characters in length".'</li>';
$valid="0";
}
if(strlen($s_id)!=9){
echo '<li>'."Student id must be exactly 9 characters in length".'</li>';
$valid="0";
}
if($tuition < 2000 || $tuition > 10000){
echo '<li>'."Tuition must be between 2000 and 10000".'</li>';
$valid="0";
}
echo '</ul>';
}
if ($valid == "1") {
echo '<ul class="success">';
echo '<li>'."Payment Successful!".'</li>';
echo '</ul>';
$line = array($fname, $lname, $s_id, $tuition, $payment);
$handle = fopen("log.txt", "a");
fwrite($handle, $line);
fclose($handle);
}
?>

PHP using strpos for checking for form specific word?

i'm trying to use strpos or some sort of method to search for the word 'validated' within a textarea known as $likes and it'll return an error if not found. I wasn't sure how to get around validating two conditions (the textfield 'likes' cannot be empty and it must contain the word 'validation') so I kind of threw another if statement which didn't work and now I am desperately plugging it into my html..
Here's my basic php validation, I removed all my other error handling and left the textarea one.
<?php
// define variables + initialize
$nameErr = $likesErr = $placesErr = $thingsErr = $emaiLErr = $shopErr = $emailyesErr= "";
$name = $likes = $places = $email = $emailyes = $shops = $things = "";
$shops = array();
$things = array();
$likesErr2 = "Your likes must include the word 'validated'!";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//textarea likes
if (empty($_POST["likes"])) {
$likesErr = "Please tell me what you like about hiking! :(";
}
else {
$likes = $_POST["likes"];
}
}
?>
Here is my attempted us at strpos: :(
<label>What do you like about hiking?</label><span class = "error">* <?php echo $likesErr;?></span><br>
<textarea rows="4" cols="50" input type="text" id="likes" name="likes">
<?php echo $likesErr2 (if ((strpos($likes, "validated") === false)?></textarea>
My current setup is resulting in a 500 error so I feel like I'm definetly doing something wrong with the php.
EDIT
I have updated my php to this:
//textfield likes
if (empty($_POST["likes"])) {
$likesErr = "Please tell me what you like about hiking! :(";
}
else if ((strpos($likes, "validated") === false){
$likesErr2 = "Please include the word 'validated' in your likes textarea!";
}
else {
$likes = $_POST["likes"];
}
and html portion
<div>
<br><br>
<label>What do you like about hiking?</label><span class = "error">* <?php echo $likesErr; echo $placesErr2;?></span><br>
<textarea rows="4" cols="50" id="likes" name="likes"></textarea>
<br><br>
</div>
And I'm still getting a 500 error ):
Here's an example use of strpos:
<?php
$str = 'Time spent with cats is never wasted.';
if (strpos($str, 'dog') === FALSE) {
echo 'no dog';
}
echo (strpos($str, 'dog') === FALSE) ? 'no dog' : 'hot dog!';
// Outputs: 'no dogno dog'

PHP - Apply code to subpages

I have this code:
<?php $url = JURI::getInstance()->toString();
if ($url == "http://example.com/news/latest/"){
echo "This is latest page";
} else {
echo "This is not latest page";
}
?>
What I'm trying to do is instead of 'http://example.com/news/latest/', how can I select the pages/items under /latest/. If it makes any more sense, here's a syntax:
if ($url == "http://example.com/news/latest/" + ANYTHING UNDER THIS)
I cannot use not equal to ($url !=) since it will include other parent pages not equal to /latest/. I just want what's under it. If anyone understands it, I need help on how to put it into code.
Update:
What I'm trying to do is if the page is example.com/news/latest, it will echo "Latest". And if for example, I am in example.com/news/latest/subpage1/subpage2, it will echo "You are in a page that is under Latest." Anything beyond "Latest" will echo that.
$str = 'example.com/news/latest/dfg';
preg_match('/example.com\/news\/([^\/]+)\/?(.*)/', $str, $page);
if(isset($page[2]) && $page[2])
echo 'You are under: ' , $page[1];
elseif(isset($page[1]))
echo 'At: ' , $page[1];
else
echo 'Error';
Edit: after clarification switched to regular expression.
Use a regular expression:
$matches = array();
if((preg_match('#http://example\.com/news/latest/(.*)#', $url, $matches)) === 1) {
if(strlen($matches[0]) > 0) {
echo "You're at page: $matches[0]";
} else {
echo "You're at the root";
}
} else {
// Error, incorrect URL (should not happen)
}
EDIT: Fixed, untested so you may have to tweak it a little

Multiple conditions in PHP

I know this is embarrassing easy but I cannot get this to work right now, keep getting syntax errors, I just added in a jquery code that pre-fills in a form filed and when you select the form field it will clear the default value. The result though is if a user submits the form without changing the default value, I need to see if it exist in addition to my normal string sanitations
In this snippet below of PHP I need to run 2 conditions on $fname but below will not work, can someone help please
$fname = 'first name';
if (trim($fname) == '') && ($fname != 'first name') {
$err .= "error";
}else{
$err .= "all good";
}
For karim79
this code below from your example, exactly like this gives me this error
Fatal Error: Can't use function return value in write context on line 5
<?PHP
$fname = '';
if(empty(trim($fname))) {
echo "First name is empty";
}
?>
$fname = 'first name';
if (trim($fname) == '' || $fname != 'first name') {
$err .= "error";
} else {
$err .= "all good";
}
I would prefer to use strcmp:
if (trim($fname) == '' || strcmp($fname,'first name') !== 0) {
$err .= "error";
} else {
$err .= "all good";
}
If the case of the first name is not important, you should consider using strcasecmp instead. Also note you can use empty to test for the empty string:
$fname = '';
$fname = trim($fname);
if(empty($fname)) {
echo "First name is empty";
} else {
echo "Not empty";
}
When using empty, beware the following (from the manual):
Note: empty() only checks variables as
anything else will result in a parse
error. In other words, the following
will not work: empty(trim($name)).
$fname = 'first name';
if (trim($fname) == '' || $fname == 'first name') {
$err .= "error";
}else{
$err .= "all good";
}
PS: I assumed you want to raise an error if the string is either empty or the standard value. If that's wrong let me know.
I would NOT recommend using empty() for anything. It has some tricky return patterns, including telling you that a 0 is empty, and things of that nature. This, unfortunately, is a shortcoming of PHP.
Instead, try this algorithm (The following assumes your form POSTs):
<?php
$err = array();
// this is for sticklers..with E_STRICT on, PHP
// complains about uninitialized indexes
if( isset($_POST['name']) )
{
$name = trim($_POST['name']);
}
else
{
$name = '';
}
if( strlen($name) == 0 )
{
$err[] = "First name is required.";
}
// after validation is complete....
if( count($err) > 0 )
{
echo "There are errors!";
// probably something more elaborate here, like
// outputting an ordered list to display each error
print_r($err);
}
else
{
echo "It's all good!";
}
?>

Categories