I want to create a program as follows but I am stuck on how to even solve the problem:
- User searches for a fruit on
index.php
index.php
authenticates that the fruit entered is indeed a fruit.- Now the page I search page 1 of google for the fruit to see if there is fruit. Then search page 2, then 3 and so on until I reach page 100. This search takes 5 minutes.
My question is: I know how to authenticate a fruit. I know how to search for a fruit. How do I append a result when I do find a fruit on a page to show the user immediately?
Also how do I keep track of the page I have already searched? For example, if I've have searched up to page 15, I don't want to go back and search page 3 again. My security brain is telling me, don't let the user locally keep track of the page they have searched. As they may tamper with the script and just make it loop the search for page 5 a hundred times
index.php
<?php
if(isset($_POST['fruit'])) {
authenticate_fruit($fruit);
// Now start the search
}
function authenticate_fruit($fruit) {
$valid_fruits = ['banana', 'apple', 'pear'];
$lowercase_fruit = strtolower($fruit);
if(in_array($lowercase_fruit, $valid_fruits)) {
return true;
}
return false;
}
?>
<form action="/index.php" method="get">
<label for="fruit">Fruit:</label><br>
<input type="text" name="fruit"><br>
</form>
searcher.php
<?php
if(isset($_POST['fruit']) && isset($_POST['page'])) {
if (authenticate_fruit($_POST['fruit']) &&
authenicate_page($_POST['page'])) {
search_for_fruit($fruit, $page);
}
}
/* Mock up function for searching for fruit on google
* @return result array if fruit found, else return false
*/
function search_for_fruit($fruit, $page) {
// Symbolizing that it takes about 1-3 seconds to load a page
sleep(rand(1,3));
if ($page % 3 && rand(1,2) == 1) {
$result['sweetness'] = rand(1,100);
$result['calories'] = rand(1,5000);
$result['healthiness'] = rand(1,100);
return $result;
}
return false;
}
function authenticate_fruit($fruit) {
$valid_fruits = ['banana', 'apple', 'pear'];
$lowercase_fruit = strtolower($fruit);
if(in_array($lowercase_fruit, $valid_fruits)) {
return true;
}
return false;
}
function authenicate_page($page) {
if (ctype_digit($_POST['page']) &&
$_POST['page'] > 0 &&
$_POST['page'] <= 100) {
return true;
}
return false;
}
?>